text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { assert } from 'chai'; import * as path from 'path'; import { INVALID_TEST_REQUESTS, STRICTLY_INVALID_TEST_REQUESTS, STRICTLY_VALID_TEST_REQUESTS, VALID_TEST_REQUESTS, } from './test_data/test-requests'; import { NON_COMPLIANT_SERVERS, STRICTLY_NON_COMPLIANT_SERVERS, } from './test_data/test-target-servers'; import { killProcesses } from './util/process'; import { spawnProxyServer, testRequestForEachFile, testRequestForEachFileWithServers, } from './util/testing'; import findProcess = require('find-process'); import { PROXY_PORT, TARGET_SERVER_PORT, SCHEMAS_DIR, DEFAULT_OPENAPI_FILE, } from './config'; import { ChildProcess } from 'child_process'; import { Readable } from 'stream'; import axios, { AxiosRequestConfig } from 'axios'; import { runProxy } from '../src/app'; import { closeServer } from '../src/util'; describe('integration.test.js', function() { this.slow(1000 * 15); // 15 seconds const contentType = 'application/json'; const clients = { proxy: axios.create({ baseURL: `http://localhost:${PROXY_PORT}`, headers: { 'content-type': contentType }, validateStatus: () => true, }), target: axios.create({ baseURL: `http://localhost:${TARGET_SERVER_PORT}`, headers: { 'content-type': contentType }, validateStatus: () => true, }), }; before(async function() { // Kill active processes listening on any of the given ports const pid1 = await findProcess('port', PROXY_PORT); const pid2 = await findProcess('port', TARGET_SERVER_PORT); await killProcesses([ ...pid1.filter(p => p.cmd.indexOf('node') !== -1).map(p => p.pid), ...pid2.filter(p => p.cmd.indexOf('node') !== -1).map(p => p.pid), ]); }); describe('OpenAPI v3', function() { const schemasDirV3 = path.join(SCHEMAS_DIR, 'v3'); describe('Invariance tests', function() { testRequestForEachFile({ testTitle: 'should return the same status and response bodies as the target server in silent mode', dir: schemasDirV3, testRequests: VALID_TEST_REQUESTS.v3, client: clients, silent: true, callback(proxyRes, targetRes) { assert.deepStrictEqual(proxyRes.data, targetRes.data); assert.equal(proxyRes.status, targetRes.status); }, }); testRequestForEachFile({ testTitle: 'should return the same headers as the target server except from the openapi-cop headers in silent mode', dir: schemasDirV3, testRequests: VALID_TEST_REQUESTS.v3, client: clients, silent: true, callback(proxyRes, targetRes) { assert.property(proxyRes.headers, 'openapi-cop-validation-result'); assert.property(proxyRes.headers, 'openapi-cop-source-request'); delete proxyRes.headers['openapi-cop-validation-result']; delete proxyRes.headers['openapi-cop-source-request']; // ignore date header delete proxyRes.headers['date']; delete targetRes.headers['date']; assert.deepStrictEqual( proxyRes.headers, targetRes.headers, 'Actual is proxy, expected is target', ); }, }); }); it('should return the source request object inside the response header', async function() { console.log('Starting proxy server...'); const server = await runProxy({ port: PROXY_PORT, host: 'localhost', targetUrl: `http://localhost:${TARGET_SERVER_PORT}`, apiDocFile: DEFAULT_OPENAPI_FILE, defaultForbidAdditionalProperties: false, }); const originalRequest: AxiosRequestConfig = { method: 'GET', url: '/pets', data: JSON.stringify({ search: 'something' }), }; const proxyResponse = await clients.proxy.request(originalRequest); const openapiCopRequest = JSON.parse( proxyResponse.headers['openapi-cop-source-request'], ); assert.deepStrictEqual(openapiCopRequest, { method: originalRequest.method, path: originalRequest.url, body: JSON.parse(originalRequest.data), query: {}, headers: { accept: 'application/json, text/plain, */*', connection: 'close', 'content-length': '22', 'content-type': 'application/json', host: 'localhost:8888', 'user-agent': 'axios/0.19.2', }, }); await closeServer(server); }); testRequestForEachFile({ testTitle: 'should respond with validation headers that are ValidationResult', dir: schemasDirV3, testRequests: VALID_TEST_REQUESTS.v3, client: clients, callback(proxyRes, _targetRes) { const validationResults = JSON.parse( proxyRes.headers['openapi-cop-validation-result'], ); const validationResultsKeys = [ 'request', 'response', 'responseHeaders', ]; assert.hasAllKeys(validationResults, validationResultsKeys); for (const k of validationResultsKeys) { assert.isObject( validationResults[k], `validation results should contain key '${k}'`, ); assert.hasAllKeys(validationResults[k], ['valid', 'errors']); assert.isBoolean(validationResults[k]['valid']); assert( validationResults[k]['errors'] === null || Array.isArray(validationResults[k]['errors']), 'validation error should be null or an array', ); if (Array.isArray(validationResults[k]['errors'])) { const validKeys = [ 'keyword', 'dataPath', 'schemaPath', 'params', 'message', 'propertyName', 'schema', 'parentSchema', 'data', ]; validationResults[k]['errors'].forEach((err: any) => { assert( Object.keys(err).every(k => validKeys.includes(k)), // all keys are valid keys 'validation error elements should conform with Ajv.ValidationError', ); }); } } }, }); it('should fail when target server is not available', async function() { this.timeout(10000); console.log('Starting proxy server...'); const ps: ChildProcess = await spawnProxyServer( PROXY_PORT, TARGET_SERVER_PORT, DEFAULT_OPENAPI_FILE, ); console.log('Reading output'); let output = ''; (ps.stdout as Readable).on('data', (data: Buffer) => { output += data; if (data.toString().includes('Proxying client request')) { setTimeout(() => { ps.kill(); }, 1500); } }); clients.proxy.request({ method: 'GET', url: '/pets' }); return new Promise((resolve, reject) => { ps.on('exit', (code: number, signal: string) => { assert.notEqual(code, -1); assert.isTrue( output.includes('Validation results'), 'should yield validation results', ); assert.isTrue( output.includes('Target server is unreachable'), 'should show failure to communicate with the target server', ); resolve(); }); }); }); testRequestForEachFile({ testTitle: 'should NOT return any validation errors for valid REQuests', dir: schemasDirV3, testRequests: VALID_TEST_REQUESTS.v3, client: clients, callback(proxyRes, _targetRes, fileName, requestObject) { const validationResults = JSON.parse( proxyRes.headers['openapi-cop-validation-result'], ); const reqValidationResults = validationResults['request']; assert.isTrue(reqValidationResults['valid']); assert.isNull(reqValidationResults['errors']); }, }); testRequestForEachFile({ testTitle: 'should NOT return any validation errors for strictly valid REQuests', dir: schemasDirV3, testRequests: STRICTLY_VALID_TEST_REQUESTS.v3, client: clients, callback(proxyRes, _targetRes, fileName, requestObject) { const validationResults = JSON.parse( proxyRes.headers['openapi-cop-validation-result'], ); const reqValidationResults = validationResults['request']; assert.isTrue(reqValidationResults['valid']); assert.isNull(reqValidationResults['errors']); }, }); testRequestForEachFile({ testTitle: 'should return correct validation errors for invalid REQuests', dir: schemasDirV3, testRequests: INVALID_TEST_REQUESTS.v3, client: clients, callback(proxyRes, _targetRes, fileName, requestObject) { const validationResults = JSON.parse( proxyRes.headers['openapi-cop-validation-result'], ); const reqValidationResults = validationResults['request']; assert.isNotTrue(reqValidationResults['valid']); assert.isNotNull(reqValidationResults['errors']); assert.isArray(reqValidationResults['errors']); assert.lengthOf(reqValidationResults['errors'], 1); assert.isDefined( requestObject.expectedError, '"expectedError" property should be set for test requests that check for validation errors', ); for (const k of Object.keys(requestObject.expectedError)) { assert.deepEqual( reqValidationResults['errors'][0][k], requestObject.expectedError[k], ); } }, }); testRequestForEachFileWithServers({ testTitle: 'should return correct validation errors for invalid RESponses', dir: schemasDirV3, testServers: NON_COMPLIANT_SERVERS.v3, client: clients, callback(proxyRes, targetRes, fileName, expectedError) { assert.isDefined( expectedError, '"expectedError" property should be set for test requests that check for validation errors', ); const validationResults = JSON.parse( proxyRes.headers['openapi-cop-validation-result'], ); const resValidationResults = validationResults['response']; assert.isNotTrue( resValidationResults['valid'], 'Response should be invalid', ); assert.isNotNull( resValidationResults['errors'], 'There should be at least one error present', ); assert.isArray(resValidationResults['errors']); for (const k of Object.keys(expectedError)) { assert.deepEqual( resValidationResults['errors'][0][k], expectedError[k], ); } }, }); testRequestForEachFile({ testTitle: 'should return correct validation errors for strictly invalid REQuests', dir: schemasDirV3, testRequests: STRICTLY_INVALID_TEST_REQUESTS.v3, client: clients, defaultForbidAdditionalProperties: true, callback(proxyRes, _targetRes, fileName, requestObject) { const validationResults = JSON.parse( proxyRes.headers['openapi-cop-validation-result'], ); const reqValidationResults = validationResults['request']; assert.isNotTrue(reqValidationResults['valid']); assert.isNotNull(reqValidationResults['errors']); assert.isArray(reqValidationResults['errors']); assert.lengthOf(reqValidationResults['errors'], 1); for (const k of Object.keys(requestObject.expectedError)) { assert.deepEqual( reqValidationResults['errors'][0][k], requestObject.expectedError[k], ); } }, }); testRequestForEachFileWithServers({ testTitle: 'should return correct validation errors for strictly invalid RESponses', dir: schemasDirV3, testServers: STRICTLY_NON_COMPLIANT_SERVERS.v3, client: clients, defaultForbidAdditionalProperties: true, callback(proxyRes, targetRes, fileName, expectedError) { assert.isDefined( expectedError, '"expectedError" property should be set for test requests that check for validation errors', ); const validationResults = JSON.parse( proxyRes.headers['openapi-cop-validation-result'], ); const resValidationResults = validationResults['response']; assert.isNotTrue( resValidationResults['valid'], 'Response should be invalid', ); assert.isNotNull( resValidationResults['errors'], 'There should be at least one error present', ); assert.isArray(resValidationResults['errors']); for (const k of Object.keys(expectedError)) { assert.deepEqual( resValidationResults['errors'][0][k], expectedError[k], ); } }, }); }); });
the_stack
module RatingUtils { "use strict"; //----------------------------------------------------------------------------------- // List of exceptions the rating control throws. export var exceptions = { elementIsInvalid: "Invalid argument: Rating control expects a valid DOM element as the first argument.", tooltipsInvalid: "Invalid argument: tooltipStrings must be null or an array of strings." }; //----------------------------------------------------------------------------------- // List of css parts defined for rating control. export var parts = { overallControl: "win-rating", averageEmpty: "win-star win-average win-empty", averageFull: "win-star win-average win-full", userEmpty: "win-star win-empty win-user", userFull: "win-star win-user win-full", tentativeEmpty: "win-star win-tentative win-empty", tentativeFull: "win-star win-tentative win-full", disabledEmpty: "win-star win-empty win-disabled", disabledFull: "win-star win-full win-disabled" }; //----------------------------------------------------------------------------------- // List of localized strings. export var localizedStrings = { "en-US": { userLabel: "User Rating", averageLabel: "Average Rating", tentativeLabel: "Tentative Rating", clearYourRating: "Clear your rating", unrated: "Unrated" } }; //----------------------------------------------------------------------------------- // TODO: Make this dynamically figure out the current language... and add the strings to localizedStrings array. export var currentLanguage = "en-US"; // Default values for rating control parts. export var defaultMaxRating = 5; export var defaultUserRating = 0; export var defaultAverageRating = 0; export var defaultDisabled = false; export var defaultEnableClear = true; export var defaultTooltipStrings = null; export var currentTheme = "dark"; //----------------------------------------------------------------------------------- // Handles to event listeners we will hang off each instantiated control. export var previewchangeListener = null; export var changeListener = null; export var cancelListener = null; //----------------------------------------------------------------------------------- export function setUp() { /// <summary> /// Test setup to run prior to every test case. /// </summary> LiveUnit.LoggingCore.logComment("In setup"); Helper.addTag("div", "rating"); //WinBlue:280045 // our code calls releasePointerCapture on faked events, which causes an exception when the pointerid is invalid var element = document.getElementById("rating"); var oldReleasePointerCapture = element.releasePointerCapture; element.releasePointerCapture = function (id) { try { oldReleasePointerCapture.call(document.getElementById("rating"), id); } catch (e) { LiveUnit.LoggingCore.logComment("Caught exception for WinBlue:280045 ... " + e.message); } }; return WinJS.Promise.wrap(); } //----------------------------------------------------------------------------------- export function cleanUp() { /// <summary> /// Test cleanup to run prior to every test case. /// </summary> LiveUnit.LoggingCore.logComment("In cleanUp"); Helper.removeElementById("rating"); } //----------------------------------------------------------------------------------- export function addTag(tagName, tagId, attributes?) { /// <summary> /// Add a tag of type tagName to the document with id set to tagId and other HTML attributes set to attributes /// </summary> /// <param name="tagName" type="string"> /// String specifying type of tag to create /// </param> /// <param name="tagId" type="string"> /// String specifying HTML id to give to created tag /// </param> /// <param name="attributes" type="object"> /// JavaScript object containing list of attributes to set on HTML tag (note that tagId takes precedence for "id" attribute) /// </param> return Helper.addTag(tagName, tagId, attributes); } //----------------------------------------------------------------------------------- export function getClientRect(elem) { /// <summary> /// Get the client rectangle for the given element /// <param name="elem" type="object"> /// Handle to element to get the client rectangle for /// </param> /// <returns type="object" /> /// </summary> return Helper.getClientRect(elem); } //----------------------------------------------------------------------------------- export function removeElementById(tagId) { /// <summary> /// Remove an existing tag from the DOM /// </summary> /// <param name="tagId" type="string"> /// String specifying the tag to remove. /// </param> var element = Helper.removeElementById(tagId); LiveUnit.Assert.isNotNull(element, "removeElementById: Couldn't find element " + tagId); return element; } export function classesMatch(expected, actual) { var result = true, expectedClasses = String(expected).split(" "); for (var i = 0; i < expectedClasses.length; ++i) { if (-1 == actual.indexOf(expectedClasses[i])) { result = false; } } return result; } //----------------------------------------------------------------------------------- export function instantiate(element, options?, expectFailure = false) { /// <summary> /// Instantiate a ratings control out of the element specified by element with given options. /// and verify expected result (success when all inputs valid, exception otherwise) and that /// all options set correctly in success case. /// </summary> /// <param name="element" type="string"> /// String specifying the tag to create a ratings control out of, or the element itself. /// If "null" is passed, the code will create a new element and add the rating control to that. /// </param> /// <param name="options" type="object"> /// JavaScript object containing a list of options to set on rating control. /// </param> /// <param name="expectFailure" type="boolean"> /// Explictly declare whether this call to instantiate expected to pass or fail /// Note we use "expectFailure" rather than "expectSuccess" so that the caller can leave the /// parameter off in the more common "expectSuccess" case /// </param> /// <returns type="object" /> LiveUnit.LoggingCore.logComment("Instantiating rating on element '" + element + "' with options = \"" + Helper.getOptionsAsString(options) + "\""); if (typeof (element) === "string") { element = document.getElementById(element); } var maxRatingInit = this.defaultMaxRating, userRatingInit = this.defaultUserRating, averageRatingInit = this.defaultAverageRating, disabledInit = this.defaultDisabled, enableClearInit = this.defaultEnableClear, tooltipStringsInit = this.defaultTooltipStrings; var rating = null; // Check if rating control already instantiated if so, save off initial options values so we can verify they don't update if (element) { rating = this.getControl(element); if (rating) { maxRatingInit = rating.maxRating; userRatingInit = rating.userRating; averageRatingInit = rating.averageRating; disabledInit = rating.enableClear; disabledInit = rating.disabled; } } // Many tests use "Math.random()" to generate data, causing us to sometimes run into false positive failures due to // rounding problems. Rather than re-author the tests, limit all floating point values to just 10 digits precision if (options && "averageRating" in options && typeof (options.averageRating) === "number" && options.averageRating !== 0) { options.averageRating = Number(String(Number(options.averageRating).toPrecision(10)).replace(/0*$/, '').replace(/\.*$/, '')); } // Make the call to WinJS.UI.Rating, catching any exceptions to verify later var exception = null; try { rating = new WinJS.UI.Rating(element, options); } catch (e) { exception = e; LiveUnit.LoggingCore.logComment(exception.message); } // Verify WinJS.UI.Rating did the expected thing if (rating) { // rating is not null, means call to WinJS.UI.Rating succeeded LiveUnit.Assert.areEqual(false, expectFailure, "Rating control instantiation succeeded, verify expectFailure=false."); // Verify DOM attributes for rating control are enumerated and of the proper JavaScript type LiveUnit.Assert.areNotEqual(Number.NaN, Number(rating.maxRating), "Verify maxRating is a number."); LiveUnit.Assert.areNotEqual(Number.NaN, Number(rating.userRating), "Verify userRating is a number."); LiveUnit.Assert.areNotEqual(Number.NaN, Number(rating.averageRating), "Verify averageRating is a number"); LiveUnit.Assert.areEqual("boolean", typeof (rating.disabled), "Verify disabled is of correct type."); LiveUnit.Assert.areEqual("object", typeof (rating.tooltipStrings), "Verify tooltipStrings is of correct type."); // Verify options handled correctly if (options && "maxRating" in options && !isNaN(options.maxRating)) { if (options.maxRating < 1) { LiveUnit.Assert.areEqual(maxRatingInit, rating.maxRating, "Verify maxRating cannot be set less than 1."); } else { LiveUnit.Assert.areEqual(Number(options.maxRating), rating.maxRating, "Verify maxRating set properly on instantiation."); } } else { LiveUnit.Assert.areEqual(maxRatingInit, rating.maxRating, "Verify default value used for maxRating when not set via options."); } if (options && "userRating" in options && !isNaN(options.userRating)) { if (options.userRating < 0) { LiveUnit.Assert.areEqual(0, rating.userRating, "Verify userRating cannot be set less than 0."); } else if (options.userRating > rating.maxRating) { LiveUnit.Assert.areEqual(rating.maxRating, rating.userRating, "Verify userRating coerced to maxRating if greater than max."); } else { LiveUnit.Assert.areEqual(Math.floor(options.userRating), rating.userRating, "Verify userRating set properly on instantiation."); } } else { LiveUnit.Assert.areEqual(userRatingInit, rating.userRating, "Verify default value used for userRating when not set (or improperly set) via options."); } if (options && "averageRating" in options && !isNaN(options.averageRating)) { if (options.averageRating < 1) { LiveUnit.Assert.areEqual(0, rating.averageRating, "Verify any averageRating less than 1 coerced to 0."); } else if (options.averageRating > rating.maxRating) { LiveUnit.Assert.areEqual(rating.maxRating, rating.averageRating, "Verify averageRating coerced to maxRating if greater than max."); } else { LiveUnit.Assert.areEqual(Number(options.averageRating), rating.averageRating, "Verify averageRating set properly on instantiation."); } } else { LiveUnit.Assert.areEqual(averageRatingInit, rating.averageRating, "Verify default value used for averageRating when not set (or improperly set) via options."); } if (options && "disabled" in options) { LiveUnit.Assert.areEqual(!!options.disabled, rating.disabled, "Verify disabled set properly on instantiation."); } else { LiveUnit.Assert.areEqual(disabledInit, rating.disabled, "Verify default value used for disabled when not set (or improperly set) via options."); } if (options && "enableClear" in options) { LiveUnit.Assert.areEqual(!!options.enableClear, rating.enableClear, "Verify enableClear set properly on instantiation."); } else { LiveUnit.Assert.areEqual(enableClearInit, rating.enableClear, "Verify default value used for enableClear when not set (or improperly set) via options."); } if (options && "tooltipStrings" in options) { if (options.tooltipStrings === null) { for (var i = 0; i < rating.maxRating; ++i) { LiveUnit.Assert.areEqual(i + 1, rating.tooltipStrings[i], "Verify tooltipStrings uses default tooltips when set to null."); } LiveUnit.Assert.areEqual(this.localizedStrings[this.currentLanguage].clearYourRating, rating.tooltipStrings[rating.maxRating], "Verify tooltipStrings uses default clear rating tooltip when set to null."); } else { var tooltipIndex; for (tooltipIndex = 0; tooltipIndex < options.tooltipStrings.length && tooltipIndex <= rating.maxRating; ++tooltipIndex) { LiveUnit.Assert.areEqual(options.tooltipStrings[tooltipIndex], rating.tooltipStrings[tooltipIndex], "Verify tooltipStrings set properly on instantiation."); } if (tooltipIndex < options.tooltipStrings.length) { // test provided too many tooltips, verify rest of rating.tooltipStrings undefined for (; tooltipIndex < options.tooltipStrings.length; ++tooltipIndex) { LiveUnit.Assert.areEqual(undefined, rating.tooltipStrings[tooltipIndex], "Verify tooltipStrings only allows setting of up to maxRating tooltips. The rest are left undefined."); } } else if (tooltipIndex < rating.tooltipStrings.length) { // test provided too few tooltips, verify default used for rest for (; tooltipIndex < rating.maxRating; ++tooltipIndex) { LiveUnit.Assert.areEqual(tooltipIndex + 1, rating.tooltipStrings[tooltipIndex], "Verify tooltipStrings uses default tooltips when test did not provide enough."); } LiveUnit.Assert.areEqual(this.localizedStrings[this.currentLanguage].clearYourRating, rating.tooltipStrings[rating.maxRating], "Verify tooltipStrings uses default clear rating tooltip when test did not provide enough."); } } } else { for (var i = 0; i < rating.maxRating; ++i) { LiveUnit.Assert.areEqual(i + 1, rating.tooltipStrings[i], "Verify tooltipStrings uses default tooltips when test did not provide them."); } LiveUnit.Assert.areEqual(this.localizedStrings[this.currentLanguage].clearYourRating, rating.tooltipStrings[rating.maxRating], "Verify tooltipStrings uses default clear rating tooltip when set to null."); } // Validating Layout and ARIA requires control added to page. if (null === element) { document.body.appendChild(rating.element); rating.element.id = "rating2"; } // Only validate layout if element actually on page, otherwise a number of CSS styles wont resolve and it will look broken if (rating.element.parentNode) { this.verifyLayout(rating.element); } this.verifyARIA(rating.element); // In some cases, internal ratings code should be calling setPointerCapture on touch down to block panning. // Since touch tests send synthasized touch events rather than the real thing, in order to validate the control // blocks panning in the proper instances, overwrite the internal call with our own validation method that we can // use to track the number of calls made to the method. // Note that there is also a by-design exception thrown by setPointerCapture when a synthasized MSPointer event // object is passed to it, so if we don't overwrite setPointerCapture, internal IE code will throw an exception // during our touch tests, making it impossible to validate touch via synthasized events (so overwriting this is a win-win). rating.element.setPointerCapture = function (pointerId) { // hang an attribute off the element tracking the number of times pointer capture has been called on it rating.element.setAttribute("controlSetPointerCapture", Number(rating.element.getAttribute("controlSetPointerCapture")) + 1); }; LiveUnit.LoggingCore.logComment("Rating has been instantiated."); } else { // Call to WinJS.UI.Controls.Rating failed, let's diagnose whether this was expected LiveUnit.Assert.areEqual(true, expectFailure, "Rating control instantiation failed with error: " + exception.message + ", verify expectFailure=true."); // Since element was not null, only valid reason we failed was due to options-related exception. // Check to see if proper exception was thrown. if (options && "tooltipStrings" in options && ( typeof (options.tooltipStrings) !== "object" // tooltipStrings must be an object ) ) { LiveUnit.Assert.areEqual(this.exceptions.tooltipsInvalid, exception.message); // All options valid, no reason for the call to have failed. LiveUnit.Assert.fail("Rating instantiation failed when element referenced a valid element and all options valid! " + ((exception) ? "Exception: " + exception.message : "")); } else { // Instantiation failed because element was NULL LiveUnit.LoggingCore.logComment("Rating instantiation failed as expected since elmentId does not reference a valid element."); LiveUnit.Assert.areEqual(this.exceptions.elementIsInvalid, exception.message); } } // Register generic event handlers on the newly created control if (rating && LiveUnit.GetWrappedCallback) { try { this.previewchangeListener = LiveUnit.GetWrappedCallback(this.verifyEvent); rating.addEventListener("previewchange", this.previewchangeListener, false); this.changeListener = LiveUnit.GetWrappedCallback(this.verifyEvent); rating.addEventListener("change", this.changeListener, false); this.cancelListener = LiveUnit.GetWrappedCallback(this.verifyEvent); rating.addEventListener("cancel", this.cancelListener, false); } catch (e) { LiveUnit.Assert.fail("rating.addEventListener threw exception: " + e.message); } } return rating; } export function getControl(element) { /// <summary> /// Get a handle to a previously created Rating Control /// </summary> /// <param name="element" type="string"> /// String specifying id of element rating control previously created out of, or element itself. /// </param> /// <returns type="object" /> var rating = null; if (typeof (element) === "string") { element = document.getElementById(element); } try { rating = element.winControl; } catch (e) { LiveUnit.Assert.fail("Failed to get a handle to the rating control with exception: " + e); } return rating; } //----------------------------------------------------------------------------------- export function setOptionsAndVerify(element, options?, expectFailure = false, useProperties = false) { /// <summary> /// Call WinJS.UI.setOptions(rating, options) on a rating control built out of element and verify handled /// correctly by rating control(set proper values, threw exceptions when expected, didn't alter unset values) /// </summary> /// <param name="element" type="string"> /// String specifying element rating control previously created out of, or element itself. /// </param> /// <param name="options" type="object"> /// JavaScript object containing a list of options to set on rating control. /// </param> /// <param name="expectFailure" type="boolean"> /// Explictly declare whether this call to WinJS.UI.setOptions(rating, ) expected to pass or fail. /// Note we use "expectFailure" rather than "expectSuccess" so that the caller can leave the /// parameter off in the more common "expectSuccess" case /// </param> /// <param name="useProperties" type="boolean"> /// Set the supplied options directly on the rating control via its DOM attributes. /// </param> /// <returns type="object" /> if (typeof (element) === "string") { element = document.getElementById(element); } // Get a handle to the (supposedly existing) rating control. var rating = this.getControl(element); LiveUnit.Assert.isNotNull(rating, "Verify ratings control exists."); // Store off the initial values for each option so we can verify they got updated (or didn't) later on var maxRatingInit = rating.maxRating, userRatingInit = rating.userRating, averageRatingInit = rating.averageRating, disabledInit = rating.disabled, enableClearInit = rating.enableClear, tooltipsInit = rating.tooltipStrings; LiveUnit.LoggingCore.logComment("Current options: \"{maxRating: " + maxRatingInit + ", userRating: " + userRatingInit + ", averageRating: " + averageRatingInit + ", disabled: " + disabledInit + "}\"."); LiveUnit.LoggingCore.logComment("Setting options to: \"" + Helper.getOptionsAsString(options) + "\"."); // Many tests use "Math.random()" to generate data, causing us to sometimes run into false positive failures due to // rounding problems. Rather than re-author the tests, limit all floating point values to just 10 digits precision if (options && "averageRating" in options && typeof (options.averageRating) === "number" && options.averageRating !== 0) { options.averageRating = Number(String(Number(options.averageRating).toPrecision(10)).replace(/0*$/, '').replace(/\.*$/, '')); } // Set the options, catching any exceptions and saving them for later verification. var exception = null; try { if (useProperties) { for (var opt in options) { if (typeof (rating[opt]) !== "undefined") { rating[opt] = options[opt]; } } } else { WinJS.UI.setOptions(rating, options); } } catch (e) { exception = e; LiveUnit.LoggingCore.logComment(exception.message); } if (exception) { // Since we got an exception, verify it was expected and gave us the correct exception message. if (useProperties) { LiveUnit.Assert.areEqual(true, expectFailure, "Setting rating properties to " + Helper.getOptionsAsString(options) + ") threw exception: " + exception.message + ", verify expectFailure=true."); } else { LiveUnit.Assert.areEqual(true, expectFailure, "Call to WinJS.UI.setOptions(rating, " + Helper.getOptionsAsString(options) + ") threw exception: " + exception.message + ", verify expectFailure=true."); } LiveUnit.Assert.isNotNull(options, "Exception shouldn't be thrown when options null, exception.message: " + exception.message); if (options && "tooltipStrings" in options && typeof (options.tooltipStrings) !== "object") { LiveUnit.Assert.areEqual(this.exceptions.tooltipsInvalid, exception.message); } else { // All options valid and DOM element valid, no reason for us to fail. if (useProperties) { LiveUnit.Assert.fail("Unexpected exception thrown when setting rating properties to " + Helper.getOptionsAsString(options) + ": " + exception.message); } else { LiveUnit.Assert.fail("Unexpected exception thrown by WinJS.UI.setOptions(rating, " + Helper.getOptionsAsString(options) + "): " + exception.message); } } // Since we got an exception, all values should have been left un-updated LiveUnit.Assert.areEqual(maxRatingInit, rating.maxRating, "Verify maxRating not changed when exception thrown while setting rating options to " + Helper.getOptionsAsString(options)); LiveUnit.Assert.areEqual(userRatingInit, rating.userRating, "Verify userRating not changed when exception thrown while setting rating options to " + Helper.getOptionsAsString(options)); LiveUnit.Assert.areEqual(averageRatingInit, rating.averageRating, "Verify averageRating not changed when exception thrown while setting rating options to " + Helper.getOptionsAsString(options)); LiveUnit.Assert.areEqual(disabledInit, rating.disabled, "Verify disabled not changed when exception thrown while setting rating options to " + Helper.getOptionsAsString(options)); if (tooltipsInit) { for (var i = 0; i < rating.maxRating; ++i) { LiveUnit.Assert.areEqual(tooltipsInit[i], rating.tooltipStrings[i], "Verify tooltipStrings not changed when exception thrown while setting rating options to " + Helper.getOptionsAsString(options)); } } else { LiveUnit.Assert.areEqual(null, rating.tooltipStrings, "Verify tooltipStrings not changed from null when exceptiong thrown while setting rating options to " + Helper.getOptionsAsString(options)); } } else { // No exception means function must have succeeded (as all failures should throw an exception) if (useProperties) { LiveUnit.Assert.areEqual(false, expectFailure, "Setting rating properties to " + Helper.getOptionsAsString(options) + " succeeded, verify expectFailure=false."); } else { LiveUnit.Assert.areEqual(false, expectFailure, "Call to WinJS.UI.setOptions(rating, " + Helper.getOptionsAsString(options) + ") succeeded, verify expectFailure=false."); } // Verify options handled correctly if (options && "maxRating" in options && !isNaN(options.maxRating)) { if (options.maxRating <= 0) { LiveUnit.Assert.areEqual(maxRatingInit, rating.maxRating, "Verify maxRating cannot be set less than maxRating, gets coerced back to input value."); } else { LiveUnit.Assert.areEqual(Math.floor(options.maxRating), rating.maxRating, "Verify maxRating set properly."); for (var i = 0; i < rating.maxRating; ++i) { tooltipsInit[i] = i + 1; } tooltipsInit[rating.maxRating] = this.localizedStrings[this.currentLanguage].clearYourRating; } } else { LiveUnit.Assert.areEqual(maxRatingInit, rating.maxRating, "Verify default value used for maxRating when not set (or improperly set) via options."); } if (options && "userRating" in options && !isNaN(options.userRating)) { if (options.userRating < 0) { LiveUnit.Assert.areEqual(0, rating.userRating, "Verify userRating cannot be set less than 0."); } else if (options.userRating > rating.maxRating) { LiveUnit.Assert.areEqual(rating.maxRating, rating.userRating, "Verify userRating coerced to maxRating if greater than max."); } else { LiveUnit.Assert.areEqual(Math.floor(options.userRating), rating.userRating, "Verify userRating set properly."); } } else { LiveUnit.Assert.areEqual(userRatingInit, rating.userRating, "Verify default value used for userRating when not set (or improperly set) via options."); } if (options && "averageRating" in options && !isNaN(options.averageRating)) { if (options.averageRating < 1) { LiveUnit.Assert.areEqual(0, rating.averageRating, "Verify setting averageRating less than 1 is coerced to 0."); } else if (options.averageRating > rating.maxRating) { LiveUnit.Assert.areEqual(rating.maxRating, rating.averageRating, "Verify averageRating coerced to maxRating if greater than max."); } else { LiveUnit.Assert.areEqual(Number(options.averageRating), rating.averageRating, "Verify averageRating set properly."); } } else { LiveUnit.Assert.areEqual(averageRatingInit, rating.averageRating, "Verify default value used for averageRating when not set (or improperly set) via options."); } if (options && "disabled" in options) { LiveUnit.Assert.areEqual(!!options.disabled, rating.disabled, "Verify disabled set properly."); } else { LiveUnit.Assert.areEqual(disabledInit, rating.disabled, "Verify default value used for disabled when not set (or improperly set) via options."); } if (options && "enableClear" in options) { LiveUnit.Assert.areEqual(!!options.enableClear, rating.enableClear, "Verify enableClear set properly."); } else { LiveUnit.Assert.areEqual(enableClearInit, rating.enableClear, "Verify default value used for enableClear when not set (or improperly set) via options."); } if (options && "tooltipStrings" in options) { if (options.tooltipStrings === null) { for (var i = 0; i < rating.maxRating; ++i) { LiveUnit.Assert.areEqual(i + 1, rating.tooltipStrings[i], "Verify tooltipStrings uses default tooltips when set as part of setting rating options to " + Helper.getOptionsAsString(options)); } LiveUnit.Assert.areEqual(this.localizedStrings[this.currentLanguage].clearYourRating, rating.tooltipStrings[rating.maxRating], "Verify tooltipStrings uses default clear rating tooltip when set to null."); } else { var tooltipIndex; for (tooltipIndex = 0; tooltipIndex < options.tooltipStrings.length && tooltipIndex <= rating.maxRating; ++tooltipIndex) { LiveUnit.Assert.areEqual(options.tooltipStrings[tooltipIndex], rating.tooltipStrings[tooltipIndex], "Verify tooltipStrings set properly while setting rating options to " + Helper.getOptionsAsString(options)); } if (tooltipIndex < options.tooltipStrings.length) { // test provided too many tooltips, verify rest of rating.tooltipStrings undefined for (; tooltipIndex < options.tooltipStrings.length; ++tooltipIndex) { LiveUnit.Assert.areEqual(undefined, rating.tooltipStrings[tooltipIndex], "Verify tooltipStrings only allows setting of up to maxRating tooltips when tooltipStrings supplied more than maxRating tooltips as part of" + Helper.getOptionsAsString(options)); } } else if (tooltipIndex < rating.tooltipStrings.length) { // test provided too few tooltips, verify default used for rest for (; tooltipIndex < rating.maxRating; ++tooltipIndex) { LiveUnit.Assert.areEqual(tooltipIndex + 1, rating.tooltipStrings[tooltipIndex], "Verify tooltipStrings uses default tooltips when tooltipStrings was not supplied enough tooltips as part of " + Helper.getOptionsAsString(options)); } LiveUnit.Assert.areEqual(this.localizedStrings[this.currentLanguage].clearYourRating, rating.tooltipStrings[rating.maxRating], "Verify tooltipStrings uses default clear rating tooltip when tooltipStrings was not supplied enough tooltips as part of " + Helper.getOptionsAsString(options)); } } } else { if (tooltipsInit) { for (var i = 0; i < rating.maxRating; ++i) { LiveUnit.Assert.areEqual(tooltipsInit[i], rating.tooltipStrings[i], "Verify tooltipStrings not changed from initial value while setting rating options to " + Helper.getOptionsAsString(options)); } LiveUnit.Assert.areEqual(this.localizedStrings[this.currentLanguage].clearYourRating, rating.tooltipStrings[rating.maxRating], "Verify clear rating tooltip not changed from initial value when setting rating options to " + Helper.getOptionsAsString(options)); } else { LiveUnit.Assert.areEqual(null, rating.tooltipStrings, "Verify tooltipStrings not changed from null while setting rating options to " + Helper.getOptionsAsString(options)); } } } if (element) { this.verifyLayout(element); this.verifyARIA(element); } } //----------------------------------------------------------------------------------- export function verifyLayout(element, styleExpected?, clearRatingTooltipExpected?) { /// <summary> /// Verify the layout of the rating control by verifying each div contains the proper child elements in the proper order. /// </summary> /// <param name="element" type="string"> /// String id of the rating control's element, or the element itself. /// </param> /// <param name="styleExpected" type="string"> /// Optional string telling verifyLayout to explicitly expect a particular styling of the control, rather than /// dynamically figuring out which styling the control is using based off its option values. /// </param> /// <param name="clearRatingTooltipExpected" type="boolean"> /// Specifies whether the special "clear your rating" tooltip is expected to be showing. /// </param> if (typeof (element) === "string") { element = Helper.getElementById(element); } // Get a handle to the (supposedly existing) ratings control var rating = this.getControl(element); // Figure out what type of rating we expect the control to be displaying var expect = null; if (typeof (styleExpected) !== "undefined") { expect = styleExpected; } else if (rating.disabled) { expect = "disabled"; } else if (rating.averageRating && !rating.userRating) { expect = "average"; } else { expect = "user"; } LiveUnit.LoggingCore.logComment("verifyLayout: Expect '" + expect + "' styles"); var numStars = element.querySelectorAll(".win-star").length; LiveUnit.Assert.areEqual(rating.maxRating + 1, numStars, "Verify there are a total of maxRating+1 " + expect + "-rating stars under the element rating was created out of."); // Make sure the styles for the overall control are set correctly var ratingControlStyle = window.getComputedStyle(element); LiveUnit.Assert.areEqual(Helper.translateCSSValue("display", "inline-flex"), ratingControlStyle.getPropertyValue("display"), "Overall element should be a flex box"); // Don't test touch action if it isn't supported var touchActionSupported = "touchAction" in document.documentElement.style || "msTouchAction" in document.documentElement.style if (touchActionSupported) { LiveUnit.Assert.areEqual("auto", ratingControlStyle.getPropertyValue(Helper.translateCSSProperty("touch-action")), "Rating control should not block panning at its root element."); } // Walk through the divs, verifying the proper number of star divs in the proper ratio of userRating/averageRating full stars followed by empty stars up to maxRating var rectElem = this.getClientRect(element); var overallWidth = 0; var hitExtraAverageFullDiv = false; for (var i = 0; i < rating.maxRating + 1; ++i) { var star = element.childNodes[i]; var rectStar = this.getClientRect(star); var starStyle = window.getComputedStyle(star), starBeforePartStyle = window.getComputedStyle(star, ":before"); // Verify star uses a font glyph if (starStyle.display !== "none") { LiveUnit.Assert.isTrue("\ue082" === starBeforePartStyle.getPropertyValue("content") || "\"\ue082\"" === starBeforePartStyle.getPropertyValue("content"), "Verify star " + (i + 1) + " uses the proper glyph by default."); } // Check to see if we are showing a floating-point average rating, and, if so, whether we are // currently looking at what we expect to be the partially-filled star if ((expect === "average" || expect === "disabled" && rating.averageRating && !rating.userRating) && ( rating.averageRating === Math.floor(rating.averageRating) && i === Math.floor(rating.averageRating) - 1 || rating.averageRating !== Math.floor(rating.averageRating) && i === Math.floor(rating.averageRating) ) ) { // Sitting on the partially filled in star hitExtraAverageFullDiv = true; // Verify current star is a partially displayed averageFull if (expect === "disabled") { LiveUnit.Assert.isTrue(this.classesMatch(this.parts.disabledFull, star.getAttribute("class")), "Verify correct class used for partial star " + (i + 1) + ". Expected: '" + this.parts.disabledFull + "', Actual: '" + star.getAttribute("class") + "'"); if (touchActionSupported) { LiveUnit.Assert.areEqual("auto", starStyle.getPropertyValue(Helper.translateCSSProperty("touch-action")), "Disabled rating control should *not* block panning. Verify star " + (i + 1) + " uses -ms-touch-action: auto."); } } else if (touchActionSupported) { LiveUnit.Assert.areEqual("none", starStyle.getPropertyValue(Helper.translateCSSProperty("touch-action")), "Rating control should block panning at each star. Verify star " + (i + 1) + " uses -ms-touch-action: none."); } LiveUnit.Assert.isTrue(this.classesMatch(this.parts.averageFull, star.getAttribute("class")), "Verify correct class used for partial star " + (i + 1) + ". Expected: '" + this.parts.averageFull + "', Actual: '" + star.getAttribute("class") + "'"); var percentFull = rating.averageRating - Math.floor(rating.averageRating); if (Math.floor(rating.averageRating) === rating.averageRating) { LiveUnit.Assert.areEqual("1 1 auto", Helper.getCSSPropertyValue(starStyle, "flex"), "Verify the averageRating star (child # " + (i + 1) + ") with class \"" + star.getAttribute("class") + "\" has flex: 1;"); } else { // We are sitting on the partial-full star for a floating point averageRating. // Validate flex is the proper percentage, allowing for 1% numerical imprecision. if (Math.abs(percentFull - parseFloat(Helper.getCSSPropertyValue(starStyle, "flex"))) > 0.01) { LiveUnit.Assert.areEqual(percentFull + " " + percentFull + " auto", Helper.getCSSPropertyValue(starStyle, "flex"), "Verify the averageRating star (child # " + (i + 1) + ") with class \"" + star.getAttribute("class") + "\" has correct ms-flex;"); } } overallWidth += rectStar.width; // Verify next star is averageEmpty and takes up the rest of the space for the partially filled star star = element.childNodes[++i]; rectStar = this.getClientRect(star); starStyle = window.getComputedStyle(star), starBeforePartStyle = window.getComputedStyle(star, ":before"); // Verify star uses a font glyph LiveUnit.Assert.isTrue("\ue082" === starBeforePartStyle.getPropertyValue("content") || "\"\ue082\"" === starBeforePartStyle.getPropertyValue("content"), "Verify star " + (i + 1) + " uses the proper glyph by default."); if (Math.floor(rating.averageRating) === rating.averageRating) { LiveUnit.Assert.areEqual("0 0 auto", Helper.getCSSPropertyValue(starStyle, "flex"), "Verify the extra star (child # " + (i + 1) + ") with class \"" + star.getAttribute("class") + "\" has flex: 0;"); } else { if (expect === "disabled") { LiveUnit.Assert.isTrue(this.classesMatch(this.parts.disabledEmpty, star.getAttribute("class")), "Verify correct class used for partial star " + (i + 1) + ". Expected: '" + this.parts.disabledEmpty + "', Actual: '" + star.getAttribute("class") + "'"); if (touchActionSupported) { LiveUnit.Assert.areEqual("auto", starStyle.getPropertyValue(Helper.translateCSSProperty("touch-action")), "Disabled rating control should *not* block panning. Verify star " + (i + 1) + " uses -ms-touch-action: auto."); } } else if (touchActionSupported) { LiveUnit.Assert.areEqual("none", starStyle.getPropertyValue(Helper.translateCSSProperty("touch-action")), "Rating control should block panning at each star. Verify star " + (i + 1) + " uses -ms-touch-action: none."); } LiveUnit.Assert.isTrue(this.classesMatch(this.parts.averageEmpty, star.getAttribute("class")), "Verify correct class used for partial star " + (i + 1) + ". Expected: '" + this.parts.averageEmpty + "', Actual: '" + star.getAttribute("class") + "'"); if (Math.abs((1 - percentFull) - Helper.getCSSPropertyValue(starStyle, "flex")) > 0.1) { LiveUnit.Assert.areEqual((1 - percentFull) + " " + (1 - percentFull) + " auto", Helper.getCSSPropertyValue(starStyle, "flex"), "Verify the helper star (child # " + (i + 1) + ") with class \"" + star.getAttribute("class") + "\" has correct ms-flex;"); } } } else { // Workaround for extra average-full <div> used for floating-point averageRatings hanging around (Windows 8 Bug 69883, wont fix) if ("none" === window.getComputedStyle(star, null).display) { // If we are not expecting average to display, then for sure this is the extra star. // OR If we ARE expecting average to display, see if we aren't expecting a partial star (aka // averageRating is an Integer) AND then see if this average-full star is beyond where // we would expect it in the control (not part of the first averageRating # of stars) if (expect !== "average" || ( Math.floor(rating.averageRating) === rating.averageRating && i >= rating.averageRating ) ) { // We found a spurious extra average-full star. Make sure it is hidden ("display: none;"). LiveUnit.Assert.areEqual("none", starStyle.display, "Verify the extra star (child # " + (i + 1) + ") with class \"" + star.getAttribute("class") + "\" has display: 'none';"); LiveUnit.Assert.areEqual("0 0 auto", Helper.getCSSPropertyValue(starStyle, "flex"), "Verify the extra star (child # " + (i + 1) + ") with class \"" + star.getAttribute("class") + "\" has flex: 0;"); // For thoroughness, make sure we don't run into more than one of these LiveUnit.Assert.isFalse(hitExtraAverageFullDiv, "Verify we only run into the extra " + this.parts.averageFull + " star 1 time"); hitExtraAverageFullDiv = true; continue; } } // Verify current star offset expected amount from left side of control if (element.getAttribute("dir") === "ltr" || getComputedStyle(element).direction === "ltr") { // Switching to flexbox yielded a +/- 1 cumulative error in this calculation, allow for the error if (rectElem.left + overallWidth < rectStar.left - (i + 1) || rectElem.left + overallWidth > rectStar.left + (i + 1)) { LiveUnit.Assert.areEqual(rectElem.left + overallWidth, rectStar.left, "Verify the left side of star " + (i + 1) + " is offset the correct distance from the left of the control."); } } else { // Switching to flexbox yielded a +/- 1 cumulative error in this calculation, allow for the error if (rectElem.left + rectElem.width - overallWidth < rectStar.left + rectStar.width - (i + 1) || rectElem.left + rectElem.width - overallWidth > rectStar.left + rectStar.width + (i + 1)) { LiveUnit.Assert.areEqual(rectElem.left + rectElem.width - overallWidth, rectStar.left + rectStar.width, "Verify the right side of star " + (i + 1) + " is offset the correct distance from the right of the control."); } } // Now verify the current star has the expected class (and by extension, is using the correct styles) // Note that there is a possibility that we already ran into the non-displayed, extra average-full prior to // running through all the normal "full" divs, hence the second check after the || in each if statement below. var expectedClassName = ""; switch (expect) { case "user": if (i < rating.userRating || hitExtraAverageFullDiv && i === rating.userRating) { expectedClassName = this.parts.userFull; } else { expectedClassName = this.parts.userEmpty; } break; case "average": if (i < rating.averageRating || hitExtraAverageFullDiv && i === rating.averageRating) { expectedClassName = this.parts.averageFull; } else { expectedClassName = this.parts.averageEmpty; } break; case "tentative": if (i < element.tentativeRatingLast || hitExtraAverageFullDiv && i === element.tentativeRatingLast) { expectedClassName = this.parts.tentativeFull; } else { expectedClassName = this.parts.tentativeEmpty; } break; case "disabled": if (rating.userRating || !rating.averageRating) { if (i < rating.userRating || hitExtraAverageFullDiv && i === rating.userRating) { expectedClassName = this.parts.userFull; } else { expectedClassName = this.parts.userEmpty; } } else { if (i < rating.averageRating || hitExtraAverageFullDiv && i === rating.averageRating) { expectedClassName = this.parts.averageFull; } else { expectedClassName = this.parts.averageEmpty; } expectedClassName += " win-disabled"; } break; } // Verify disabled stars enable panning if (touchActionSupported) { if (expect === "disabled") { LiveUnit.Assert.areEqual("auto", starStyle.getPropertyValue(Helper.translateCSSProperty("touch-action")), "Disabled rating control should *not* block panning. Verify star " + (i + 1) + " uses -ms-touch-action: auto."); } else { LiveUnit.Assert.areEqual("none", starStyle.getPropertyValue(Helper.translateCSSProperty("touch-action")), "Rating control should block panning at each star. Verify star " + (i + 1) + " uses -ms-touch-action."); } } LiveUnit.Assert.isTrue(this.classesMatch(expectedClassName, star.getAttribute("class")), "Verify correct class used for star " + (i + 1) + ". Expected: '" + expectedClassName + "', Actual: '" + star.getAttribute("class") + "'"); LiveUnit.Assert.areEqual("1 1 auto", Helper.getCSSPropertyValue(starStyle, "flex"), "Verify star " + (i + 1) + " has flex: 1;"); } overallWidth += rectStar.width; } // Switching to flexbox yielded a +/- 1 error per star in this calculation, allow for the error if (rectElem.width < overallWidth - rating.maxRating || rectElem.width > overallWidth + rating.maxRating) { LiveUnit.Assert.areEqual(rectElem.width, overallWidth, "Verify width of overall control is the sum of the widths of each star in the control."); } } //----------------------------------------------------------------------------------- export function verifyARIA(element, ariaExpected, ariaValueExpected, ariaTextExpected) { /// <summary> /// Verify ARIA information for the input ratings control /// </summary> /// <param name="element" type="string"> /// String id of the rating control's element, or the element itself /// </param> /// <param name="ariaExpected" type="string"> /// Optional string telling verifyARIA to explicitly expect a particular ARIA state for the control to be in, /// rather than dynamically figuring out which state the control is using based off its option values. /// </param> /// <param name="ariaValueExpected" type="string"> /// Optional string telling verifyARIA to explicitly expect a particular ariaValueExpected. /// This isonly used for mitigating wont fix dev code bugs. /// </param> /// <param name="ariaTextExpected" type="string"> /// Optional string telling verifyARIA to explicitly expect a particular ariaValueExpected. /// This is only used for mitigating wont fix dev code bugs. /// </param> if (typeof (element) === "string") { element = Helper.getElementById(element); } // Get a handle to the (supposedly existing) ratings control var rating = this.getControl(element); // Verify ARIA info that will be true regardless of current state of the control LiveUnit.Assert.areEqual("slider", element.getAttribute("role"), "Verify ARIA role set correctly."); LiveUnit.Assert.areEqual((rating.enableClear) ? "0" : "1", element.getAttribute("aria-valuemin"), "Verify aria-valuemin set correctly given that enableClear set to " + rating.enableClear + "."); LiveUnit.Assert.areEqual(rating.maxRating.toString(), element.getAttribute("aria-valuemax"), "Verify aria-valuemax set correctly."); LiveUnit.Assert.areEqual(rating.disabled.toString(), element.getAttribute("aria-readonly"), "Verify aria-readonly set correctly."); // Verify ARIA info that is dependent on current state (label, valuenow, and valuetext) var expectedValueNow, expectedValueText, expectedLabel; if ("tentative" === ariaExpected) { expectedLabel = this.localizedStrings[this.currentLanguage].tentativeLabel; expectedValueNow = element.tentativeRatingLast; // tentativeRatingLast is not part of Rating API, it is hung off element for test purposes if (expectedValueNow === 0) { // Expect "clear your rating". See if we should use default tooltip or if it is overridden if (rating.tooltipStrings && rating.tooltipStrings[rating.maxRating]) { expectedValueText = rating.tooltipStrings[rating.maxRating]; // Clear your rating tooltip } else { expectedValueText = this.localizedStrings[this.currentLanguage].clearYourRating; } expectedValueNow = this.localizedStrings[this.currentLanguage].unrated; } } else if ("user" === ariaExpected || rating.userRating) { expectedLabel = this.localizedStrings[this.currentLanguage].userLabel; expectedValueNow = rating.userRating; if (rating.userRating === 0) { expectedValueNow = this.localizedStrings[this.currentLanguage].unrated; expectedValueText = this.localizedStrings[this.currentLanguage].unrated; } } else if ("average" === ariaExpected || rating.averageRating) { expectedLabel = this.localizedStrings[this.currentLanguage].averageLabel; expectedValueNow = rating.averageRating; } else { expectedLabel = this.localizedStrings[this.currentLanguage].userLabel; expectedValueNow = this.localizedStrings[this.currentLanguage].unrated; expectedValueText = this.localizedStrings[this.currentLanguage].unrated; } LiveUnit.LoggingCore.logComment("verifyARIA: Expect '" + expectedLabel + "' labels."); // If we haven't set expectedValueText yet, grab it from either rating.tooltipStrings or set it to the value if (!expectedValueText) { if (rating.tooltipStrings && rating.tooltipStrings[expectedValueNow - 1]) { expectedValueText = rating.tooltipStrings[expectedValueNow - 1]; } else { expectedValueText = expectedValueNow; } } if (typeof (ariaValueExpected) !== "undefined") { expectedValueNow = ariaValueExpected; } if (typeof (ariaTextExpected) !== "undefined") { expectedValueText = ariaTextExpected; } // Now validate all three are set correctly. LiveUnit.Assert.areEqual(String(expectedValueNow), element.getAttribute("aria-valuenow"), "Verify aria-valuenow set correctly."); LiveUnit.Assert.areEqual(String(expectedValueText), element.getAttribute("aria-valuetext"), "Verify aria-valuetext set correctly."); LiveUnit.Assert.areEqual(String(expectedLabel), element.getAttribute("aria-label"), "Verify aria-label set correctly."); } //----------------------------------------------------------------------------------- export function randomString(maxLength) { /// <summary> /// Create a string of random chars of a random length up to maxLength /// </summary> /// <param name="maxLength" type="integer"> /// Number specifying maximum length for created string. /// </param> /// <returns type="string" /> return Helper.randomString(maxLength); } //----------------------------------------------------------------------------------- export function randomHTML(totalElements, returnString) { /// <summary> /// Create a random block of HTML as either an element or a string /// </summary> /// <param name="totalElements" type="integer"> /// Number specifying total number of elements to add. /// </param> /// <param name="returnString" type="boolean"> /// </param> /// <returns type="object" /> return Helper.randomHTML(totalElements, returnString); } //----------------------------------------------------------------------------------- export function random(min:number, max:number):number { /// <summary> /// Generate a random number between min and max /// </summary> /// <param name="min" type="number"> /// Minimum value for random number /// </param> /// <param name="max" type="number"> /// Maximum value for random number /// </param> /// <returns type="number" /> return min + Math.random() * (max - min); } //----------------------------------------------------------------------------------- export function randomInt(min, max) { /// <summary> /// Generate a random number between min and max /// </summary> /// <param name="min" type="number"> /// Minimum value for random number /// </param> /// <param name="max" type="number"> /// Maximum value for random number /// </param> /// <returns type="number" /> return Math.round(this.random(min, max)); } export function randomNewMaxRating(limit, current) { /// <summary> /// Randomly generate a new maxRating between 2 and limit, guaranteeing we don't set the current rating /// </summary> /// <param name="limit" type="integer"> /// Max limit for the new maxRating /// </param> /// <param name="current" type="integer"> /// Current maxRating we guarantee to not return /// </param> /// <returns type="number" /> var newMax; do { newMax = Math.round(this.random(2, limit)); } while (newMax === current); return newMax; } //----------------------------------------------------------------------------------- export function verifyFunction(rating, functionName) { /// <summary> /// Verify given function is defined on rating control. /// </summary> /// <param name="rating" type="object"> /// Handle to actual rating control. /// </param> /// <param name="functionName" type="string"> /// Name of function to verify is on control. /// </param> LiveUnit.LoggingCore.logComment("Verifying that function " + functionName + " exists"); if (rating[functionName] === undefined) { LiveUnit.Assert.fail(functionName + " missing from rating API."); } LiveUnit.Assert.isNotNull(rating[functionName]); LiveUnit.Assert.areEqual("function", typeof (rating[functionName]), functionName + " exists on rating, but it isn't a function"); } //----------------------------------------------------------------------------------- // ASYNC Event Test Helper Code export var timeBetweenActions = 0; export var nextAction = null; //----------------------------------------------------------------------------------- export function startAsyncEventTest(signalTestCaseCompleted, actions) { /// <summary> /// Start running an Event test /// </summary> /// <param name="signalTestCaseCompleted" type="function"> /// Callback function to call when all actions have occurred and all events verified. /// </param> if (typeof (actions) === "undefined" || typeof (actions[1]) === "undefined") { LiveUnit.Assert.fail("startEventTest called with no actions defined."); } window['async'] = { actions: actions, actionNum: 0, signalTestCaseCompleted: signalTestCaseCompleted, ratingUtils: this }; window['async'].ratingUtils.nextAction = setTimeout(LiveUnit.GetWrappedCallback(window['async'].ratingUtils.invokeNextAction), window['async'].ratingUtils.timeBetweenActions); } //----------------------------------------------------------------------------------- export function invokeNextAction() { /// <summary> /// Invoke the next action in the window['async'].actions array /// </summary> if (window['async'].actionNum !== 0) { var action = window['async'].actions[window['async'].actionNum]; for (var event in action.expectedEvents) { if (action.expectedEvents[event] > 0) { if (typeof (action.actualEvents) === "undefined" || typeof (action.actualEvents[event]) === "undefined") { LiveUnit.Assert.areEqual(action.expectedEvents[event], 0, "Action " + window['async'].actionNum + " did not receive any callbacks for \"" + event + "\"."); } else { LiveUnit.Assert.areEqual(action.expectedEvents[event], action.actualEvents[event], "Action " + window['async'].actionNum + " did not receive proper number of callbacks for \"" + event + "\"."); } } } } window['async'].actionNum++; if (typeof (window['async'].actions[window['async'].actionNum]) === "undefined") { LiveUnit.LoggingCore.logComment("No more actions to invoke, test complete!"); clearTimeout(window['async'].ratingUtils.nextAction); // Make 100% certain we wont have any additional actions come through after the test window['async'].signalTestCaseCompleted(); return; } LiveUnit.LoggingCore.logComment(window['async'].actionNum + ": " + window['async'].actions[window['async'].actionNum].action); window['async'].actions[window['async'].actionNum].action(); // Wait between each action for events to go through. window['async'].ratingUtils.nextAction = setTimeout(LiveUnit.GetWrappedCallback(window['async'].ratingUtils.invokeNextAction), window['async'].ratingUtils.timeBetweenActions); } //----------------------------------------------------------------------------------- export function verifyEvent(event) { /// <summary> /// Generic event handler to register for all events /// </summary> /// <param name="event" type="object"> /// Event object built by Ratings control /// </param> if (typeof (window['async']) === "undefined" || typeof (window['async'].actions) === "undefined") { // callback in async test that isn't using infrastructure. return; } LiveUnit.LoggingCore.logComment("Received callback for: \"" + event.type + "\" on control with id: \"" + event.target.id + "\" and tentativeRating: " + event.detail.tentativeRating); var action = null; if (typeof (window['async'].actions[window['async'].actionNum]) !== "undefined") { action = window['async'].actions[window['async'].actionNum]; } if (!action || !action.expectedEvents) { LiveUnit.Assert.fail("Received unexpected event from control '" + event.target.id + "': " + event.type); } // March through all the events we expect for the current action for (var eventType in action.expectedEvents) { if (typeof (action.expectedEvents[eventType]) === "undefined") { // Got an event we don't expect to receive from control LiveUnit.Assert.fail("Received unexpected event from control '" + event.target.id + "': " + event.type + " after invoking: '" + action.action + "'."); } else if (eventType === event.type) { // event is expected type, let's make sure we haven't gotten too many. if (action.expectedEvents[eventType] > 0) { if (typeof (action.actualEvents) === "undefined") { action.actualEvents = new Array(); } if (typeof (action.actualEvents[eventType]) === "undefined") { action.actualEvents[eventType] = 1; } else { action.actualEvents[eventType]++; } } else { LiveUnit.Assert.fail("Received too many events for " + event.type + " after invoking: '" + action.action + "'."); } } } // We've verified this is a valid event, verify various attributes are what we expected if (typeof (action.targetExpected) === "undefined") { action.targetExpected = document.getElementById("rating"); } LiveUnit.Assert.areEqual(action.targetExpected, event.target, "Verify target set as expected after invoking " + action.action); if (typeof (action.tentativeRatingExpected) !== "undefined") { LiveUnit.Assert.areEqual(action.tentativeRatingExpected, event.detail.tentativeRating, "Verify tentativeRating set as expected after invoking " + action.action); } event.target.tentativeRatingLast = event.detail.tentativeRating; if (typeof (action.userRatingExpected) !== "undefined") { LiveUnit.Assert.areEqual(action.userRatingExpected, window['async'].ratingUtils.getControl(event.target).userRating, "Verify userRating set as expected after invoking " + action.action); } // Verify layout and ARIA info for the control is correct // If test case didn't define action.styleExpected or action.ariaExpected, figure out what style and ARIA state // the control should be in based on the event type and the option values for the control. // Note that the only reason a test case would set styleExpected or ariaExpected is because there is a "wont fix" or // "by design" reason the current event would leave the control in a slightly different state than one we can predict // based simply off the event and option values. For example, when the control is first focused, a previewchange // is thrown and the visual style updates to tentative, but the ARIA state doesn't update so that an accessibility // user can still check the value by tabbing to the control. It would be expensive and make the code more complex // for this code to determine each of these differing states one-by-one, so as a simplifying measure, the test cases // hitting these scenarios explicitly provide the states we expect. if ("previewchange" === event.type) { if (typeof (action.styleExpected) === "undefined") { action.styleExpected = "tentative"; } if (typeof (action.ariaExpected) === "undefined") { action.ariaExpected = "tentative"; } } else { var ratingControl = window['async'].ratingUtils.getControl(event.target); if (typeof (action.styleExpected) === "undefined") { action.styleExpected = (ratingControl.userRating || !ratingControl.averageRating) ? "user" : "average"; } if (typeof (action.ariaExpected) === "undefined") { action.ariaExpected = (ratingControl.userRating || !ratingControl.averageRating) ? "user" : "average"; } } window['async'].ratingUtils.verifyLayout(event.target.id, action.styleExpected, action.clearRatingTooltipExpected); window['async'].ratingUtils.verifyARIA(event.target.id, action.ariaExpected, action.ariaValueExpected, action.ariaTextExpected); } export function mouseOver(fromElement, toElement?) { Helper.mouseOverUsingMiP(fromElement, toElement); } export function mouseDown(element) { Helper.mouseDownUsingMiP(element); } export function mouseUp(element) { Helper.mouseUpUsingMiP(element); } export function click(element) { Helper.clickUsingMiP(element); } export function touchOver(fromElement, toElement) { Helper.touchOver(fromElement, toElement); } export function touchDown(element) { // Rating tests are expected to be touching down on the star of a rating control, check that the parent is a rating control. if (element && element.parentNode.winControl && typeof element.parentNode.winControl.userRating !== "undefined") { // If the control is *not* disabled, expect a call to setPointerCapture to occur when the touch down happens if (!element.parentNode.winControl.disabled) { element.parentNode.setAttribute("callsToPointerCaptureExpected", Number(element.parentNode.getAttribute("callsToPointerCaptureExpected")) + 1); } Helper.touchDown(element); if (element.setPointerCapture) { LiveUnit.Assert.areEqual( element.parentNode.getAttribute("callsToPointerCaptureExpected"), element.parentNode.getAttribute("controlSetPointerCapture"), "Total calls of setPointerCapture should match expected if the rating control is properly" + (!element.parentNode.winControl.disabled) ? " blocking panning when enabled." : " allowing panning when disabled."); } } else { Helper.touchDown(element); } } export function touchUp(element) { Helper.touchUp(element); } export function touchCancel(element) { Helper.touchCancel(element); } export function tap(element) { Helper.tap(element); } export function keyDown(element, keyCode) { // Would like to use createEvent/initKeyboardEvent, but those don't initialize // the "keyCode" property which the rating control uses. Instead, directly call // the rating's keyDown handler, providing values for the properties it checks. var rating = element.winControl; rating._onKeyDown({ keyCode: keyCode, stopPropagation: function () { }, preventDefault: function () { } }); } export function focus(element) { Helper.focus2(element); } export function blur(element) { Helper.blur(element); } //----------------------------------------------------------------------------------- export function generateMouseHoverActions(starElement, tentativeRatingExpected, userRatingExpected) { /// <summary> /// Returns an "actions" array containing the actions necessary to hover over and off the input star. /// </summary> /// <param name="starElement" type="element"> /// Element to hover over /// </param> /// <param name="tentativeRatingExpected" type="number"> /// tentativeRating we expect to have set while hovering the input star. /// </param> /// <param name="userRatingExpected" type="number"> /// userRating we expect to have set during/after hovering the input star. /// </param> /// <returns type="object" /> return { 1: { action: function (element) { return function () { window['async'].ratingUtils.mouseOver(null, element); }; } (starElement), expectedEvents: { previewchange: 1, change: 0, cancel: 0 }, tentativeRatingExpected: tentativeRatingExpected, userRatingExpected: userRatingExpected }, 2: { action: function (element) { return function () { window['async'].ratingUtils.mouseOver(element, null); }; } (starElement), expectedEvents: { previewchange: 0, change: 0, cancel: 1 }, tentativeRatingExpected: null, userRatingExpected: userRatingExpected } }; } //----------------------------------------------------------------------------------- export function generateClickActions(starElement, newRating, initialRating) { /// <summary> /// Returns an "actions" array containing the actions necessary to hover over, click, and then hover off an input star. /// </summary> /// <param name="starElement" type="element"> /// Element to click /// </param> /// <param name="newRating" type="number"> /// Rating we expect to set when clicking the star. /// </param> /// <param name="initialRating" type="number"> /// Current rating value we expect to see prior to clicking the star. /// </param> /// <returns type="object" /> return { 1: { action: function (element) { return function () { window['async'].ratingUtils.mouseOver(null, element); }; } (starElement), expectedEvents: { previewchange: 1, change: 0, cancel: 0 }, tentativeRatingExpected: newRating, userRatingExpected: initialRating }, 2: { action: function (element) { return function () { window['async'].ratingUtils.mouseDown(element); }; } (starElement), expectedEvents: { previewchange: 0, change: 0, cancel: 0 } }, 3: { action: function (element) { return function () { window['async'].ratingUtils.mouseUp(element); }; } (starElement), expectedEvents: { previewchange: 0, change: (initialRating === newRating) ? 0 : 1, cancel: 0 }, tentativeRatingExpected: newRating, userRatingExpected: newRating }, 4: { action: function (element) { return function () { window['async'].ratingUtils.mouseOver(element, null); }; } (starElement), expectedEvents: { previewchange: 0, change: 0, cancel: (initialRating === newRating) ? 1 : 0 }, tentativeRatingExpected: null, userRatingExpected: newRating } }; } //----------------------------------------------------------------------------------- export function generateTapActions(starElement, newRating, initialRating) { /// <summary> /// Returns an "actions" array containing the actions necessary to tap a star in the rating control. /// </summary> /// <param name="starElement" type="element"> /// Element to tap /// </param> /// <param name="newRating" type="number"> /// Rating we expect to set when tapping the star. /// </param> /// <param name="initialRating" type="number"> /// Current rating value we expect to see prior to tapping the star. /// </param> /// <returns type="object" /> return { 1: { action: function (element) { return function () { window['async'].ratingUtils.touchOver(null, element); }; } (starElement), expectedEvents: { previewchange: 0, change: 0, cancel: 0 } }, 2: { action: function (element) { return function () { window['async'].ratingUtils.touchDown(element); }; } (starElement), expectedEvents: { previewchange: 1, change: 0, cancel: 0 }, tentativeRatingExpected: newRating, userRatingExpected: initialRating }, 3: { action: function (element) { return function () { window['async'].ratingUtils.touchUp(element); }; } (starElement), expectedEvents: { previewchange: 0, change: (initialRating === newRating) ? 0 : 1, cancel: 0 }, tentativeRatingExpected: newRating, userRatingExpected: newRating }, 4: { action: function (element) { return function () { window['async'].ratingUtils.touchOver(element, null); }; } (starElement), expectedEvents: { previewchange: 0, change: 0, cancel: (initialRating === newRating) ? 1 : 0 }, tentativeRatingExpected: null, userRatingExpected: newRating } }; } //----------------------------------------------------------------------------------- export function generateKeydownActions(ratingElement, key) { /// <summary> /// Returns an "actions" array containing the actions necessary to send a particular key to the rating control. /// </summary> /// <param name="ratingElement" type="element"> /// Element to send the input key to /// </param> /// <param name="key" type="number"> /// Identifier for the key to send /// </param> /// <returns type="object" /> var rating = this.getControl(ratingElement); LiveUnit.Assert.isNotNull(rating, "Validate ratingElement passed to generateKeydownActions is a valid rating control"); LiveUnit.LoggingCore.logComment("Sending key: '" + key + "' to control"); var actions = { 1: { action: function () { window['async'].ratingUtils.focus(ratingElement); }, expectedEvents: { previewchange: (rating.disabled) ? 0 : 1, change: 0, cancel: 0 }, tentativeRatingExpected: rating.userRating, userRatingExpected: rating.userRating, styleExpected: (rating.userRating > 0) ? "user" : "tentative", ariaExpected: (rating.userRating > 0 || rating.averageRating === 0) ? "user" : "average" }, 2: { action: function () { window['async'].ratingUtils.keyDown(ratingElement, key); }, expectedEvents: { previewchange: 0, change: 0, cancel: 0 }, tentativeRatingExpected: rating.userRating, userRatingExpected: rating.userRating, styleExpected: "tentative", ariaExpected: "tentative", clearRatingTooltipExpected: undefined } }; switch (key) { case WinJS.Utilities.Key.rightArrow: if (getComputedStyle(ratingElement).direction === "ltr") { actions[2].tentativeRatingExpected = (rating.userRating === rating.maxRating) ? rating.maxRating : rating.userRating + 1; } else { actions[2].tentativeRatingExpected = (rating.userRating === 0) ? 0 : rating.userRating - 1; } break; case WinJS.Utilities.Key.upArrow: actions[2].tentativeRatingExpected = (rating.userRating === rating.maxRating) ? rating.maxRating : rating.userRating + 1; break; case WinJS.Utilities.Key.end: actions[2].tentativeRatingExpected = rating.maxRating; break; case WinJS.Utilities.Key.leftArrow: if (getComputedStyle(ratingElement).direction === "ltr") { actions[2].tentativeRatingExpected = (rating.userRating === 0) ? 0 : rating.userRating - 1; } else { actions[2].tentativeRatingExpected = (rating.userRating === rating.maxRating) ? rating.maxRating : rating.userRating + 1; } break; case WinJS.Utilities.Key.downArrow: actions[2].tentativeRatingExpected = (rating.userRating === 0) ? 0 : rating.userRating - 1; break; case WinJS.Utilities.Key.home: actions[2].tentativeRatingExpected = 0; break; default: var tentativeExpected = -1; if ((key >= WinJS.Utilities.Key.num0) && (key <= WinJS.Utilities.Key.num9)) { tentativeExpected = key - WinJS.Utilities.Key.num0; } if ((key >= WinJS.Utilities.Key.numPad0) && (key <= WinJS.Utilities.Key.numPad9)) { tentativeExpected = key - WinJS.Utilities.Key.numPad0; } if (tentativeExpected >= 0 && tentativeExpected <= 9) { actions[2].tentativeRatingExpected = (tentativeExpected >= rating.maxRating) ? rating.maxRating : tentativeExpected; } break; } if (actions[2].tentativeRatingExpected === 0) { if (rating.enableClear) { if (!rating.disabled) { actions[2].clearRatingTooltipExpected = true; } } else { actions[2].clearRatingTooltipExpected = false; actions[2].tentativeRatingExpected = 1; } } if (actions[2].tentativeRatingExpected !== rating.userRating && !rating.disabled) { actions[2].expectedEvents.previewchange = 1; } return actions; } //----------------------------------------------------------------------------------- export function generateKeydownThenBlurActions(ratingElement, key) { /// <summary> /// Returns an "actions" array containing the actions necessary to send a particular key to the rating control, and then blurs the control. /// </summary> /// <param name="ratingElement" type="element"> /// Element to send the input key to /// </param> /// <param name="key" type="number"> /// Identifier for the key to send /// </param> /// <returns type="object" /> var rating = this.getControl(ratingElement); LiveUnit.Assert.isNotNull(rating, "Validate ratingElement passed to generateKeydownThenBlurActions is a valid rating control"); var actions = this.generateKeydownActions(ratingElement, key); // if disabled or we didn't expect a preview from the first key, expect a cancel event, or nothing if (rating.disabled || !actions[2].expectedEvents.previewchange) { actions[3] = { action: function () { window['async'].ratingUtils.blur(ratingElement); }, expectedEvents: { previewchange: 0, change: 0, cancel: (rating.disabled) ? 0 : 1 }, tentativeRatingExpected: null, userRatingExpected: rating.userRating }; } else { // we got a preview and we aren't disabled, so expect a change event actions[3] = { action: function () { window['async'].ratingUtils.blur(ratingElement); }, expectedEvents: { previewchange: 0, change: 1, cancel: 0 }, tentativeRatingExpected: actions[2].tentativeRatingExpected, userRatingExpected: actions[2].tentativeRatingExpected }; } return actions; } //----------------------------------------------------------------------------------- export function generateKeydownThenEscapeActions(ratingElement, key) { /// <summary> /// Returns an "actions" array containing the actions necessary to send a particular key to the rating control, and then sends "Escape" to the control. /// </summary> /// <param name="ratingElement" type="element"> /// Element to send the input key to /// </param> /// <param name="key" type="number"> /// Identifier for the key to send /// </param> /// <returns type="object" /> var rating = this.getControl(ratingElement); LiveUnit.Assert.isNotNull(rating, "Validate ratingElement passed to generateKeydownThenEscapeActions is a valid rating control"); var actions = this.generateKeydownActions(ratingElement, key); actions[3] = { action: function () { window['async'].ratingUtils.keyDown(ratingElement, WinJS.Utilities.Key.escape); }, expectedEvents: { previewchange: 0, change: 0, cancel: (rating.disabled) ? 0 : 1 }, tentativeRatingExpected: null, userRatingExpected: rating.userRating }; return actions; } //----------------------------------------------------------------------------------- export function generateKeydownThenEnterActions(ratingElement, key) { /// <summary> /// Returns an "actions" array containing the actions necessary to focus a rating control and send a particular key to it /// </summary> /// <param name="ratingElement" type="element"> /// Element to send the input key to /// </param> /// <param name="key" type="number"> /// Identifier for the key to send /// </param> /// <returns type="object" /> var rating = this.getControl(ratingElement); LiveUnit.Assert.isNotNull(rating, "Validate ratingElement passed to generateKeydownThenEnterActions is a valid rating control"); var actions = this.generateKeydownActions(ratingElement, key); actions[3] = { action: function () { window['async'].ratingUtils.keyDown(document.getElementById("rating"), WinJS.Utilities.Key.enter); }, expectedEvents: { previewchange: 0, change: (!actions[2].expectedEvents.previewchange || rating.disabled) ? 0 : 1, cancel: 0 }, tentativeRatingExpected: actions[2].tentativeRatingExpected, userRatingExpected: actions[2].tentativeRatingExpected }; actions[4] = { action: function () { window['async'].ratingUtils.blur(document.getElementById("rating")); }, expectedEvents: { previewchange: 0, change: 0, cancel: (rating.disabled) ? 0 : (!actions[3].expectedEvents.change) ? 1 : 0 }, tentativeRatingExpected: null, userRatingExpected: rating.userRating } return actions; } //----------------------------------------------------------------------------------- export function generateKeydownThenTabActions(ratingElement, key) { /// <summary> /// Returns an "actions" array containing the actions necessary to send a particular key to the rating control, followed by "tab" to commit. /// </summary> /// <param name="ratingElement" type="element"> /// Element to send the input key to /// </param> /// <param name="key" type="number"> /// Identifier for the key to send /// </param> /// <returns type="object" /> var rating = this.getControl(ratingElement); LiveUnit.Assert.isNotNull(rating, "Validate ratingElement passed to generateKeydownThenBlurActions is a valid rating control"); var actions = this.generateKeydownActions(ratingElement, key); actions[3] = { action: function () { window['async'].ratingUtils.keyDown(document.getElementById("rating"), WinJS.Utilities.Key.tab); }, expectedEvents: { previewchange: 0, change: (!actions[2].expectedEvents.previewchange || rating.disabled) ? 0 : 1, cancel: 0 }, tentativeRatingExpected: actions[2].tentativeRatingExpected, userRatingExpected: actions[2].tentativeRatingExpected }; actions[4] = { action: function () { window['async'].ratingUtils.blur(document.getElementById("rating")); }, expectedEvents: { previewchange: 0, change: 0, cancel: (rating.disabled) ? 0 : (!actions[3].expectedEvents.change) ? 1 : 0 }, tentativeRatingExpected: null, userRatingExpected: rating.userRating } return actions; } }
the_stack
import * as zlib from 'zlib'; import * as Long from 'long'; import {BitsUtil} from '../util/BitsUtil'; /** * Simplified version of Java client's MetricDescriptor * sufficient for needs of Node.js client. * @internal */ export interface MetricDescriptor { prefix?: string; metric: string; discriminator?: string; discriminatorValue?: string; unit?: ProbeUnit; } /** * Note: enum values must match with Java's ProbeUnit ordinals. * @internal */ export enum ProbeUnit { BYTES = 0, MS = 1, NS = 2, PERCENT = 3, COUNT = 4, BOOLEAN = 5, ENUM = 6, /** * Note: This unit and subsequent ones should be processed * in a backwards-compatible way (see ProbeUnit#newUnit * handling in Java). If we start using it, we need to * port this functionality. */ US = 7 } /** * Note: enum values must match with Java's ValueType ordinals. * @internal */ export enum ValueType { LONG = 0, DOUBLE = 1 } const MASK_PREFIX = 1; const MASK_METRIC = 1 << 1; const MASK_DISCRIMINATOR = 1 << 2; const MASK_DISCRIMINATOR_VALUE = 1 << 3; const MASK_UNIT = 1 << 4; const MASK_EXCLUDED_TARGETS = 1 << 5; const MASK_TAG_COUNT = 1 << 6; const NULL_DICTIONARY_ID = -1; const NULL_UNIT = -1; const UNSIGNED_BYTE_MAX_VALUE = 255; const BITS_IN_BYTE = 8; const BYTE_MASK = 0xFF; const BINARY_FORMAT_VERSION = 1; const SIZE_VERSION = 2; const SIZE_DICTIONARY_BLOB = 4; const SIZE_COUNT_METRICS = 4; /** * This class generates binary representation of client metrics * (i.e. numeric statistics). * @internal */ export class MetricsCompressor { private readonly metricsBuffer: OutputBuffer; private readonly dictionaryBuffer: OutputBuffer; private readonly dictionary: MetricsDictionary; private metricsCount = 0; private lastDescriptor: MetricDescriptor; constructor() { this.metricsBuffer = new OutputBuffer(); this.dictionaryBuffer = new OutputBuffer(); this.dictionary = new MetricsDictionary(); } addLong(descriptor: MetricDescriptor, value: number): void { this.writeDescriptor(descriptor); this.metricsBuffer.writeByte(ValueType.LONG); this.metricsBuffer.writeLong(value); } addDouble(descriptor: MetricDescriptor, value: number): void { this.writeDescriptor(descriptor); this.metricsBuffer.writeByte(ValueType.DOUBLE); this.metricsBuffer.writeDouble(value); } generateBlob(): Promise<Buffer> { // start with Promise.resolve() to catch all errors return Promise.resolve() .then(() => { this.writeDictionary(); const metricsBuf = this.metricsBuffer.toBuffer(); const dictionaryBuf = this.dictionaryBuffer.toBuffer(); return Promise.all([ this.compressBuffer(metricsBuf), this.compressBuffer(dictionaryBuf) ]); }) .then(([compressedMetricsBuf, compressedDictionaryBuf]) => { const completeSize = SIZE_VERSION + SIZE_DICTIONARY_BLOB + compressedDictionaryBuf.length + SIZE_COUNT_METRICS + compressedMetricsBuf.length; const finalBuf = new OutputBuffer(completeSize); finalBuf.writeByte((BINARY_FORMAT_VERSION >>> BITS_IN_BYTE) & BYTE_MASK); finalBuf.writeByte(BINARY_FORMAT_VERSION & BYTE_MASK); finalBuf.writeInt(compressedDictionaryBuf.length); finalBuf.writeBuffer(compressedDictionaryBuf); finalBuf.writeInt(this.metricsCount); finalBuf.writeBuffer(compressedMetricsBuf); return finalBuf.toBuffer(); }); } private writeDescriptor(descriptor: MetricDescriptor): void { const mask = this.calculateDescriptorMask(descriptor); this.metricsBuffer.writeByte(mask); if ((mask & MASK_PREFIX) === 0) { this.metricsBuffer.writeInt(this.getDictionaryId(descriptor.prefix)); } if ((mask & MASK_METRIC) === 0) { this.metricsBuffer.writeInt(this.getDictionaryId(descriptor.metric)); } if ((mask & MASK_DISCRIMINATOR) === 0) { this.metricsBuffer.writeInt(this.getDictionaryId(descriptor.discriminator)); } if ((mask & MASK_DISCRIMINATOR_VALUE) === 0) { this.metricsBuffer.writeInt(this.getDictionaryId(descriptor.discriminatorValue)); } if ((mask & MASK_UNIT) == 0) { if (descriptor.unit === undefined) { this.metricsBuffer.writeByte(NULL_UNIT); } else { this.metricsBuffer.writeByte(descriptor.unit); } } // include excludedTargets and tags bytes for compatibility purposes if ((mask & MASK_EXCLUDED_TARGETS) == 0) { this.metricsBuffer.writeByte(0); } if ((mask & MASK_TAG_COUNT) == 0) { this.metricsBuffer.writeByte(0); } this.metricsCount++; this.lastDescriptor = descriptor; } private calculateDescriptorMask(descriptor: MetricDescriptor): number { let mask = 0; if (this.lastDescriptor === undefined) { return mask; } if (descriptor.prefix === this.lastDescriptor.prefix) { mask |= MASK_PREFIX; } if (descriptor.metric === this.lastDescriptor.metric) { mask |= MASK_METRIC; } if (descriptor.discriminator === this.lastDescriptor.discriminator) { mask |= MASK_DISCRIMINATOR; } if (descriptor.discriminatorValue === this.lastDescriptor.discriminatorValue) { mask |= MASK_DISCRIMINATOR_VALUE; } if (descriptor.unit === this.lastDescriptor.unit) { mask |= MASK_UNIT; } // include excludedTargets and tags bits for compatibility purposes mask |= MASK_EXCLUDED_TARGETS; mask |= MASK_TAG_COUNT; return mask; } private getDictionaryId(word: string): number { if (word === undefined) { return NULL_DICTIONARY_ID; } return this.dictionary.getDictionaryId(word); } private writeDictionary(): void { const words = this.dictionary.words(); this.dictionaryBuffer.writeInt(words.length); let lastWordText = ''; for (const word of words) { const wordText = word.word; if (wordText.length > UNSIGNED_BYTE_MAX_VALUE) { // this should have been checked earlier, this is a safety check throw new Error('Dictionary element too long: ' + wordText); } const maxCommonLen = Math.min(lastWordText.length, wordText.length); let commonLen = 0; while (commonLen < maxCommonLen && wordText.charAt(commonLen) === lastWordText.charAt(commonLen)) { commonLen++; } const diffLen = wordText.length - commonLen; this.dictionaryBuffer.writeInt(word.dictionaryId); this.dictionaryBuffer.writeByte(commonLen); this.dictionaryBuffer.writeByte(diffLen); for (let i = commonLen; i < wordText.length; i++) { this.dictionaryBuffer.writeChar(wordText.charAt(i)); } lastWordText = wordText; } } private compressBuffer(buf: Buffer): Promise<Buffer> { return new Promise((resolve, reject) => { zlib.deflate( buf, // set level to 1 for best speed (less CPU overhead) { level: 1 }, (err, compressedBuf) => { if (err) { return reject(err); } resolve(compressedBuf); } ); }); } } const OUTPUT_BUFFER_INITIAL_SIZE = 1024; const OUTPUT_BUFFER_GROW_FACTOR = 1.2; /** * Simple grow-on-demand wrapper for Buffer. * @internal */ export class OutputBuffer { private buffer: Buffer; private pos: number; constructor(size?: number) { this.buffer = Buffer.allocUnsafe(size || OUTPUT_BUFFER_INITIAL_SIZE); this.pos = 0; } toBuffer(): Buffer { return this.buffer.slice(0, this.pos); } writeBuffer(buf: Buffer): void { this.ensureAvailable(buf.length); buf.copy(this.buffer, this.pos); this.pos += buf.length; } writeByte(byte: number): void { this.ensureAvailable(BitsUtil.BYTE_SIZE_IN_BYTES); BitsUtil.writeUInt8(this.buffer, this.pos, byte & BYTE_MASK); this.pos += BitsUtil.BYTE_SIZE_IN_BYTES; } writeChar(char: string): void { this.ensureAvailable(BitsUtil.CHAR_SIZE_IN_BYTES); BitsUtil.writeUInt16(this.buffer, this.pos, char.charCodeAt(0), true); this.pos += BitsUtil.CHAR_SIZE_IN_BYTES; } writeDouble(double: number): void { this.ensureAvailable(BitsUtil.DOUBLE_SIZE_IN_BYTES); BitsUtil.writeDouble(this.buffer, this.pos, double, true); this.pos += BitsUtil.DOUBLE_SIZE_IN_BYTES; } writeInt(int: number): void { this.ensureAvailable(BitsUtil.INT_SIZE_IN_BYTES); BitsUtil.writeInt32(this.buffer, this.pos, int, true); this.pos += BitsUtil.INT_SIZE_IN_BYTES; } writeLong(value: number): void { const long = Long.fromNumber(value); this.ensureAvailable(BitsUtil.LONG_SIZE_IN_BYTES); BitsUtil.writeInt32(this.buffer, this.pos, long.high, true); this.pos += BitsUtil.INT_SIZE_IN_BYTES; BitsUtil.writeInt32(this.buffer, this.pos, long.low, true); this.pos += BitsUtil.INT_SIZE_IN_BYTES; } private available(): number { return this.buffer.length - this.pos; } private ensureAvailable(size: number): void { if (this.available() < size) { // grow more memory than needed let newSize = Math.floor((this.pos + size) * OUTPUT_BUFFER_GROW_FACTOR); if (newSize % 2 !== 0) { newSize++; } const newBuffer = Buffer.allocUnsafe(newSize); this.buffer.copy(newBuffer, 0, 0, this.pos); this.buffer = newBuffer; } } } interface Word { word: string; dictionaryId: number; } /** * Metrics dictionary used to store word -> id mapping. * @internal */ export class MetricsDictionary { private readonly ids: Map<string, number>; constructor() { this.ids = new Map(); } getDictionaryId(word: string): number { if (word.length > UNSIGNED_BYTE_MAX_VALUE) { throw new Error('Too long value in metric descriptor, maximum is ' + UNSIGNED_BYTE_MAX_VALUE + ': ' + word); } let id = this.ids.get(word); if (id === undefined) { id = this.ids.size; this.ids.set(word, id); } return id; } /** * Returns all stored word<->id mappings ordered by word. */ words(): Word[] { if (this.ids.size === 0) { return []; } const words: Word[] = Array.from(this.ids.entries()) .map(([word, dictionaryId]) => ({ word, dictionaryId })); words.sort((w1, w2) => { if (w1.word < w2.word) { return -1; } if (w1.word > w2.word) { return 1; } return 0; }); return words; } }
the_stack
import { Component, ElementRef, ViewEncapsulation, AfterViewInit, QueryList, ContentChildren, Renderer2, ViewChild, Input, OnDestroy } from '@angular/core'; import { Subject } from 'rxjs'; import { takeUntil } from 'rxjs/operators'; import { some, find, map, differenceBy } from 'lodash'; import { ScrollNavLinkDirective } from './scroll-nav-link.directive'; import { CdkScrollable } from '@angular/cdk/overlay'; /** Container for scroll navigation links. */ @Component({ selector: 'hc-scroll-nav', encapsulation: ViewEncapsulation.None, styleUrls: ['scroll-nav.component.scss'], templateUrl: 'scroll-nav.component.html' }) export class HcScrollNavComponent implements AfterViewInit, OnDestroy { /** Set to true to enable scrolling the nav link pane as the content pane scrolls */ @Input() public scrollNavWithContent = false; /** Set to true to enable the component to change for dynamic content changes that might not be picked up by Angular */ @Input() public hasDynamicContent = false; @ViewChild('scrollContainer', {read: CdkScrollable, static: false}) public _cdkScrollableElement: CdkScrollable; @ContentChildren(ScrollNavLinkDirective, { descendants: true }) private linkList: QueryList<ScrollNavLinkDirective>; public get _links(): Array<HTMLElement> { return this.linkList.toArray().map(e => e.nativeElement); } public isScrolling = false; private unsubscribe$ = new Subject<void>(); private previousElementPosition = 0; private previousList: ScrollNavLinkDirective[] = []; private tryRefresh = false; private dynamicInterval; private readonly SCROLL_LINK_ATTRIBUTE = 'hcScrollLink'; private readonly ACTIVE_CLASS = 'hc-scroll-nav-link-active'; private readonly INACTIVE_CLASS = 'hc-scroll-nav-link-inactive'; private readonly ACTIVE_PARENT_SECTION_CLASS = 'hc-scroll-nav-active-parent-section-link'; private readonly INACTIVE_PARENT_SECTION_CLASS = 'hc-scroll-nav-inactive-parent-section-link'; private readonly SUBSECTION_CLASS = 'hc-scroll-nav-subsection-link'; private readonly PARENT_SECTION_CLASS = 'hc-scroll-nav-parent-section-link'; private readonly PARENT_SECTION_CONTENT_CLASS = 'hc-scroll-nav-parent-section-link-content'; private readonly LINKS_CONTAINER_CLASS = 'hc-scroll-nav-links-container'; private readonly UNORDERED_LIST_TAG_NAME = 'UL'; private readonly LIST_TAG_NAME = 'LI'; constructor(public _elementRef: ElementRef, private renderer: Renderer2) {} public ngOnDestroy(): void { if (this.dynamicInterval) { clearInterval(this.dynamicInterval); } } public ngAfterViewInit(): void { setTimeout(() => { this.initializeLinks(true); this.previousList = this.linkList.toArray(); }, 100); if (this.hasDynamicContent) { this.refreshScrollNavLinks(); this.dynamicInterval = setInterval(() => { this.refreshScrollNavLinks(); }, 300); } // If links are added dynamically, refresh the scrollNav this.linkList.changes.pipe(takeUntil(this.unsubscribe$)).subscribe((newLinkList: QueryList<ScrollNavLinkDirective>) => { if (this.previousList.length === 0) { this.previousList = newLinkList.toArray(); this.initializeLinks(true); } else if (newLinkList.length === 0 && this.previousList.length > 0) { this.refreshScrollNavLinks(this.previousList); } else { this.previousList = newLinkList.toArray(); this.initializeLinks(); } }); } /** Refresh the scroll nav links when dynamic changes have been made. updateScrollLinkArray parameter is optional */ public refreshScrollNavLinks(updateScrollLinkArray: ScrollNavLinkDirective[] = []): void { if (updateScrollLinkArray.length > 0) { this.linkList.reset(updateScrollLinkArray); this.linkList.notifyOnChanges(); return; } const scrollLinkNodeList: NodeList = this._elementRef.nativeElement.querySelectorAll(`[${this.SCROLL_LINK_ATTRIBUTE}]`); // create array to make the difference calculation off of const scrollLinkList: CombinedLinkList[] = []; scrollLinkNodeList.forEach((dynamicLink: HTMLElement) => { const scrollLinkAttributeValue: string | null = dynamicLink.getAttribute(this.SCROLL_LINK_ATTRIBUTE); if (scrollLinkAttributeValue) { scrollLinkList.push({ hcScrollLink: scrollLinkAttributeValue, linkElement: dynamicLink }); } }); if ( this.linkList.length !== scrollLinkList.length || differenceBy(scrollLinkList, this.linkList.toArray(), 'hcScrollLink').length > 0 ) { const newLinkList: ScrollNavLinkDirective[] = map(scrollLinkList, (dynamicLink: CombinedLinkList) => { let rtnLink: ScrollNavLinkDirective = <ScrollNavLinkDirective>{}; if (some(this.linkList.toArray(), ['hcScrollLink', dynamicLink.hcScrollLink])) { const queryDirective: ScrollNavLinkDirective | undefined = find(this.linkList.toArray(), ["hcScrollLink", dynamicLink.hcScrollLink]); if (queryDirective) { rtnLink = queryDirective; } } else { const scrollNavLinkDirective: ScrollNavLinkDirective = new ScrollNavLinkDirective(<ElementRef>{}, this.renderer); scrollNavLinkDirective._setDirectiveToNode(dynamicLink.linkElement); rtnLink = scrollNavLinkDirective; } return rtnLink; } ); this.linkList.reset(newLinkList); this.linkList.notifyOnChanges(); return; } } public _setActiveSectionById(id: string): void { const link = this.linkList.find(e => e.hcScrollLink === id); if (!link) { if (!this.tryRefresh) { this.tryRefresh = true; this.refreshScrollNavLinks(); this._setActiveSectionById(id); } else { this.tryRefresh = false; throw new Error(`Failed to mark active section. Could not find the element with the data target for id: ${id}.`); } } else { this.setActiveSection(link.nativeElement); } } private initializeLinks(isInit = false): void { this._links.forEach((link) => { this.setClassesForSubsection(link); }); if (this.linkList?.length > 0) { const firstScrollLink = this.linkList.first?.hcScrollLink; if (!firstScrollLink) { throw new Error( `Failed to mark active section. Could not find the element with the data target for id: ${firstScrollLink}.` ); } if (isInit) { this._setActiveSectionById(firstScrollLink); } } } private setActiveSection(element: HTMLElement): void { const focusedEl = document.activeElement; // inactivate all elements before activating the passed in element this._links.forEach(e => { // remove active styles and set inactive styles e.classList.remove(this.ACTIVE_CLASS); e.classList.add(this.INACTIVE_CLASS); this.handleActiveParentSections(e, false); // If a nav item on the scroll list currently has focus, remove it so a highlight border doesn't persist on scroll if ( focusedEl === e ) { e.blur(); } }); element.classList.remove(this.INACTIVE_CLASS); element.classList.add(this.ACTIVE_CLASS); this.handleActiveParentSections(element, true); if (this.scrollNavWithContent) { this.scrollToElement(element); } } private scrollToElement(element: HTMLElement): void { let currentElementPosition = 0; this._links.forEach((link, index) => { if (link.getAttribute(this.SCROLL_LINK_ATTRIBUTE) === element.getAttribute(this.SCROLL_LINK_ATTRIBUTE)) { currentElementPosition = index; } }); const container: HTMLElement = this._elementRef.nativeElement.querySelector(`.${this.LINKS_CONTAINER_CLASS}`); const offsetTop: number = element.offsetTop; const elementClientHeight: number = element.clientHeight; const scrollHeight: number = container.scrollHeight; const scrollTop: number = this._cdkScrollableElement.measureScrollOffset("top"); const clientHeight: number = container.clientHeight; if (!this.isScrolling) { if (this.previousElementPosition < currentElementPosition) { // scroll down if (offsetTop > clientHeight && scrollTop <= offsetTop) { this._cdkScrollableElement.scrollTo({ bottom: scrollHeight - offsetTop - elementClientHeight }); } } else if (this.previousElementPosition > currentElementPosition) { // scroll up element.scrollIntoView(); } } this.previousElementPosition = currentElementPosition; } private handleActiveParentSections(element: HTMLElement, isActive: boolean): void { if (element.parentElement) { element.className.includes(this.PARENT_SECTION_CLASS) ? this.setActiveParentSection(element, isActive) : this.setActiveParentSection(element.parentElement, isActive); } else if (element.className.includes(this.PARENT_SECTION_CLASS)) { this.setActiveParentSection(element, isActive); } } private setActiveParentSection(element: HTMLElement, isActive: boolean) { if (element.hasAttribute(this.SCROLL_LINK_ATTRIBUTE)) { if (isActive && !element.className.includes(this.ACTIVE_PARENT_SECTION_CLASS)) { element.classList.remove(this.INACTIVE_PARENT_SECTION_CLASS); element.classList.add(this.ACTIVE_PARENT_SECTION_CLASS); } else if (!isActive && !element.className.includes(this.INACTIVE_PARENT_SECTION_CLASS)) { element.classList.remove(this.ACTIVE_PARENT_SECTION_CLASS); element.classList.add(this.INACTIVE_PARENT_SECTION_CLASS); } } if (element.parentElement && !element.parentElement.className.includes(this.LINKS_CONTAINER_CLASS)) { this.setActiveParentSection(element.parentElement, isActive); } } private setClassesForSubsection(element: HTMLElement): void { const parentElement = element.parentElement ? element.parentElement.parentElement : undefined; if (parentElement && parentElement.tagName === this.LIST_TAG_NAME && parentElement.hasAttribute(this.SCROLL_LINK_ATTRIBUTE)) { element.classList.add(this.SUBSECTION_CLASS); if (!parentElement.className.includes(this.PARENT_SECTION_CLASS)) { parentElement.classList.add(this.PARENT_SECTION_CLASS); parentElement.classList.add(this.INACTIVE_PARENT_SECTION_CLASS); let parentHasContent = (parentElement.childNodes[0] && parentElement.childNodes[0].nodeValue) ? true : false; Array.from(parentElement.children).forEach((child) => { if (!(child.tagName === this.UNORDERED_LIST_TAG_NAME && child.children[0] && child.children[0].hasAttribute(this.SCROLL_LINK_ATTRIBUTE))) { parentHasContent = true; } }); if (parentHasContent && !parentElement.className.includes(this.PARENT_SECTION_CONTENT_CLASS)) { parentElement.classList.add(this.PARENT_SECTION_CONTENT_CLASS); } else { parentElement.classList.remove(this.PARENT_SECTION_CONTENT_CLASS); } } } } } export interface CombinedLinkList { hcScrollLink: string; linkElement: HTMLElement; }
the_stack
const SortedArray = require("sorted-array-type"); const WaitNotify = require("wait-notify"); const cliProgress = require("cli-progress"); const {BarFormat} = cliProgress.Format; const TimeoutError = require("puppeteer").errors.TimeoutError; import WebSocketListener from "./web_socket_listener"; import {TwitchDropsWatchdog} from "./watchdog"; import {StreamPage} from "./pages/stream"; import utils from './utils'; import logger from "./logger"; import {ElementHandle, Page} from "puppeteer"; import {Client} from "./twitch"; class NoStreamsError extends Error { } class NoProgressError extends Error { } class HighPriorityError extends Error { } class StreamLoadFailedError extends Error { } class StreamDownError extends Error { } interface Game { id: string, displayName: string } interface Campaign { id: string, status: string, game: Game, self: { isAccountConnected: boolean }, endAt: string, name: string } interface Drop { id: string self: { currentMinutesWatched: number }, benefitEdges: { benefit: { id: string, name: string } }[], startAt: string, requiredMinutesWatched: number } interface InventoryDrop { id: string self: { currentMinutesWatched: number, dropInstanceID: string } } interface CampaignDetails { id: string, status: string, game: Game, self: { isAccountConnected: boolean }, endAt: string, name: string, timeBasedDrops: Drop[], allow: { channels: { id: string, displayName: string }[], isEnabled: boolean } } export class TwitchDropsBot { /** * A list of game IDs to watch and claim drops for. * @private */ readonly #gameIds: string[] = []; /** * When true, the bot will attempt to watch and claim drops for all games, even if they are not in {@link #gameIds}. * The games in {@link #gameIds} still have priority. * @private */ readonly #watchUnlistedGames: boolean = false; /** * A list of game IDs that we should ignore. This is useful when {@link #watchUnlistedGames} is true, but we want to * ignore some games. * @private */ readonly #ignoredGameIds: string[] = []; /** * The number of minutes to wait in between refreshing the drop campaign list. * @private */ readonly #dropCampaignPollingInterval: number = 15; // When a stream fails #failedStreamRetryCount times (it went offline, or other reasons), it gets added to a // blacklist so we don't waste our time trying it. It is removed from the blacklist if we switch drop campaigns // or after #failedStreamBlacklistTimeout minutes. readonly #failedStreamRetryCount: number = 3; readonly #failedStreamBlacklistTimeout: number = 30; /** * The maximum number of seconds to wait for pages to load. * * When we use page.load(), the default timeout is 30 seconds, increasing this value can help when using low-end * devices (such as a Raspberry Pi) or when using a slower network connection. * @private */ readonly #loadTimeoutSeconds: number = 30; /** * When true, this will change the visibility of all video elements to "hidden". This can be used to lower CPU * usage on low-end devices. * @private */ readonly #hideVideo: boolean = false; /** * Show a warning if the Twitch account is not linked to the drop campaign. * @private */ readonly #showAccountNotLinkedWarning: boolean = true; // Twitch API client to use. readonly #twitchClient: Client; readonly #page: Page; #twitchDropsWatchdog: TwitchDropsWatchdog; #pendingDropCampaignIds = new SortedArray((a: string, b: string) => { if (a === b) { return 0; } const campaignA = this.#getDropCampaignById(a); const campaignB = this.#getDropCampaignById(b); // Sort campaigns based on order of game IDs specified in config const indexA = this.#gameIds.indexOf(campaignA['game']['id']); const indexB = this.#gameIds.indexOf(campaignB['game']['id']); if (indexA === -1 && indexB !== -1) { return 1; } else if (indexA !== -1 && indexB === -1) { return -1; } else if (indexA === indexB) { // Both games have the same priority. Give priority to the one that ends first. const endTimeA = Date.parse(campaignA['endAt']); const endTimeB = Date.parse(campaignB['endAt']); if (endTimeA === endTimeB) { return a < b ? -1 : 1; } return endTimeA < endTimeB ? -1 : 1; } return Math.sign(indexA - indexB); }); #pendingDropCampaignIdsNotifier = new WaitNotify(); #progressBar: any = null; #payload: any = null; #total: any = null; #currentProgress: any = null; #isFirstOutput: boolean = true; #hasWrittenNewLine: boolean = false; #webSocketListener = new WebSocketListener(); #currentDropCampaignId: string | null = null; #dropCampaignMap: { [key: string]: Campaign } = {}; #pendingHighPriority: boolean = false; /** * The drop that we are currently making progress towards. */ #currentDrop: Drop | null = null; /** * The drop that we are trying to make progress towards. Sometimes when watching a stream, we make progress towards * a different drop than we had intended. This can happen when a game has multiple drop campaigns and we try to * process one, but a different one is currently active. */ #targetDrop: Drop | null = null; #viewerCount: number = 0; #currentMinutesWatched: { [key: string]: number } = {}; #lastMinutesWatched: { [key: string]: number } = {}; #lastProgressTime: { [key: string]: number } = {}; #isDropReadyToClaim: boolean = false; #isStreamDown: boolean = false; constructor(page: Page, client: Client, options?: { gameIds?: string[], failedStreamBlacklistTimeout?: number, failedStreamRetryCount?: number, dropCampaignPollingInterval?: number, loadTimeoutSeconds?: number, hideVideo?: boolean, watchUnlistedGames?: boolean, showAccountNotLinkedWarning?: boolean, ignoredGameIds?: string[] }) { this.#page = page; this.#twitchClient = client; options?.gameIds?.forEach((id => { this.#gameIds.push(id); })); this.#dropCampaignPollingInterval = options?.dropCampaignPollingInterval ?? this.#dropCampaignPollingInterval; this.#failedStreamBlacklistTimeout = options?.failedStreamBlacklistTimeout ?? this.#failedStreamBlacklistTimeout; this.#failedStreamRetryCount = options?.failedStreamRetryCount ?? this.#failedStreamRetryCount; this.#hideVideo = options?.hideVideo ?? this.#hideVideo; this.#loadTimeoutSeconds = options?.loadTimeoutSeconds ?? this.#loadTimeoutSeconds; this.#page.setDefaultTimeout(this.#loadTimeoutSeconds * 1000); this.#watchUnlistedGames = options?.watchUnlistedGames ?? this.#watchUnlistedGames; this.#showAccountNotLinkedWarning = options?.showAccountNotLinkedWarning ?? this.#showAccountNotLinkedWarning; options?.ignoredGameIds?.forEach((id => { this.#ignoredGameIds.push(id); })); // Set up Twitch Drops Watchdog this.#twitchDropsWatchdog = new TwitchDropsWatchdog(this.#twitchClient, this.#dropCampaignPollingInterval); this.#twitchDropsWatchdog.on('before_update', () => { this.#stopProgressBar(); logger.info('Updating drop campaigns...'); }); this.#twitchDropsWatchdog.on('error', (error) => { this.#stopProgressBar() logger.error('Error checking twitch drops!'); logger.error(error); this.#startProgressBar() }) this.#twitchDropsWatchdog.on('update', async (campaigns: Campaign[]) => { logger.info('Found ' + campaigns.length + ' campaigns.'); while (this.#pendingDropCampaignIds.length > 0) { this.#pendingDropCampaignIds.pop(); } // Add to pending campaigns.forEach(campaign => { // Ignore drop campaigns that are not either active or upcoming const campaignStatus = campaign.status; if (campaignStatus !== 'ACTIVE' && campaignStatus !== 'UPCOMING') { return; } const dropCampaignId = campaign.id; this.#dropCampaignMap[dropCampaignId] = campaign; if (this.#gameIds.length === 0 || this.#gameIds.includes(campaign.game.id) || this.#watchUnlistedGames) { // Warn the user if a game is listed on both the `gameIds` list and the `ignoredGameIds` list if (this.#gameIds.includes(campaign.game.id) && this.#ignoredGameIds.includes(campaign.game.id)) { logger.warn('Game ID in both gameIds and ignoredGameIds!'); } // Ignore some games if (this.#ignoredGameIds.includes(campaign.game.id)) { return; } // Check if this campaign is finished already TODO: Find a reliable way of checking if we finished a campaign /*if (this.#completedCampaignIds.has(dropCampaignId)) { return; }*/ // Warn the user if the Twitch account is not linked. Users can still earn progress and claim // rewards from campaigns that are not linked to their Twitch account (they will still show up // in the twitch inventory), but they will not show up in-game until their account is linked. if (!campaign.self.isAccountConnected) { if (this.#showAccountNotLinkedWarning) { logger.warn('Twitch account not linked for drop campaign: ' + this.#getDropCampaignFullName(dropCampaignId)); } } this.#pendingDropCampaignIds.insert(dropCampaignId); } }); logger.info('Found ' + this.#pendingDropCampaignIds.length + ' pending campaigns.'); // Check if we are currently working on a drop campaign if (this.#currentDropCampaignId !== null) { // Check if there is a higher priority stream we should be watching this.#pendingHighPriority = false; for (let i = 0; i < this.#pendingDropCampaignIds.length; ++i) { const firstCampaignId = this.#pendingDropCampaignIds[i]; if (firstCampaignId === this.#currentDropCampaignId) { break; } // Find the first drop that we haven't claimed yet let firstUnclaimedDrop = null; try { firstUnclaimedDrop = await this.#getFirstUnclaimedDrop(firstCampaignId); if (firstUnclaimedDrop === null) { continue; } } catch (error) { logger.error('Failed to get first unclaimed drop!'); logger.debug(error); continue; } // Claim the drop if it is ready to be claimed let inventoryDrop = null; try { inventoryDrop = await this.#twitchClient.getInventoryDrop(firstUnclaimedDrop['id'], firstCampaignId); if (inventoryDrop === null) { continue; } } catch (error) { logger.error('Error getting inventory drop'); logger.debug(error); } if (inventoryDrop['self']['currentMinutesWatched'] >= inventoryDrop['requiredMinutesWatched']) { try { await this.#claimDropReward(inventoryDrop); } catch (error) { logger.error('Error claiming drop'); logger.debug(error); } continue; } // Make sure there are active streams before switching try { const details = await this.#twitchClient.getDropCampaignDetails(firstCampaignId); if ((await this.#getActiveStreams(firstCampaignId, details)).length > 0) { logger.info('Higher priority campaign found: ' + this.#getDropCampaignFullName(firstCampaignId) + ' id: ' + firstCampaignId + ' time: ' + new Date().getTime()); this.#pendingHighPriority = true; break; } } catch (error) { logger.error('Failed to check stream count'); logger.debug(error); } } } this.#pendingDropCampaignIdsNotifier.notifyAll(); this.#startProgressBar(); }); this.#twitchDropsWatchdog.start(); // Set up web socket listener this.#webSocketListener.on('viewcount', count => { this.#viewerCount = count; }); this.#webSocketListener.on('drop-progress', async data => { // Check if we are making progress towards the expected drop. This is not always the case since a game may // have multiple drop campaigns, but only one is active at a time. If this happens, then we will just set // the current drop to the one we are making progress on. const dropId = data['drop_id']; if (dropId !== this.#currentDrop?.id) { logger.debug('Drop progress message does not match expected drop: ' + this.#currentDrop?.id + ' vs ' + dropId); if (!(dropId in this.#currentMinutesWatched)) { this.#currentMinutesWatched[dropId] = data['current_progress_min']; this.#lastMinutesWatched[dropId] = data['current_progress_min']; } } // Check if we are making progress this.#currentMinutesWatched[dropId] = data['current_progress_min']; if (this.#currentMinutesWatched[dropId] > this.#lastMinutesWatched[dropId]) { this.#lastProgressTime[dropId] = new Date().getTime(); this.#lastMinutesWatched[dropId] = this.#currentMinutesWatched[dropId]; if (dropId !== this.#currentDrop?.id) { this.#stopProgressBar(true); logger.info('Drop progress does not match expected drop: ' + this.#currentDrop?.id + ' vs ' + dropId); // If we made progress for a different drop, switch to it this.#currentDrop = await this.#twitchClient.getInventoryDrop(dropId); if (!this.#currentDrop) { throw new Error('Made progress towards a drop but did not find it in inventory!'); } if (!(this.#currentDrop.id in this.#currentMinutesWatched)) { this.#currentMinutesWatched[this.#currentDrop?.id] = this.#currentDrop?.self.currentMinutesWatched; this.#lastMinutesWatched[this.#currentDrop?.id] = this.#currentDrop?.self.currentMinutesWatched; this.#lastProgressTime[this.#currentDrop.id] = new Date().getTime(); } // Restart the progress bar this.#createProgressBar(); this.#startProgressBar(data['required_progress_min'], {'viewers': this.#viewerCount, 'uptime': 0, drop_name: this.#getDropName(this.#currentDrop)}); } } }); this.#webSocketListener.on('drop-claim', message => { this.#isDropReadyToClaim = true; }); this.#webSocketListener.on('stream-down', message => { this.#isStreamDown = true; }); } /** * Starts the bot. */ async start() { // The last time we attempted to make progress towards each drop campaign const lastDropCampaignAttemptTimes: { [key: string]: number } = {}; // Amount of time to wait after failing to make progress towards a drop campaign before trying it again const SLEEP_TIME_MS = 1000 * 60 * 5; // noinspection InfiniteLoopJS while (true) { // Get the first pending drop campaign ID inner: while (true) { logger.debug('Finding next drop campaign...'); if (this.#pendingDropCampaignIds.length > 0) { // Find the first pending drop campaign that we haven't checked in the past 5 minutes let minLastDropCampaignCheckTime = new Date().getTime(); for (const pendingDropCampaignId of this.#pendingDropCampaignIds) { const lastCheckTime = lastDropCampaignAttemptTimes[pendingDropCampaignId]; if (lastCheckTime) { minLastDropCampaignCheckTime = Math.min(minLastDropCampaignCheckTime ?? lastCheckTime, lastCheckTime); if (new Date().getTime() - lastCheckTime < SLEEP_TIME_MS) { continue; } } this.#currentDropCampaignId = pendingDropCampaignId; logger.debug('currentDropCampaignId=' + this.#currentDropCampaignId); break inner; } // If no campaigns active/streams online, then set the page to "about:blank" await this.#page.goto("about:blank"); // We already checked all pending drop campaigns in the past 5 minutes, lets wait for the oldest one logger.debug('final minlastdropcampaignchecktime: ' + minLastDropCampaignCheckTime + ' time: ' + new Date().getTime()); const sleepTime = Math.max(0, SLEEP_TIME_MS - (new Date().getTime() - minLastDropCampaignCheckTime)); logger.info('No campaigns active/streams online. Checking again in ' + (sleepTime / 1000 / 60).toFixed(1) + ' min.'); setTimeout(() => { logger.debug('notify all!'); this.#pendingDropCampaignIdsNotifier.notifyAll(); }, sleepTime); } logger.debug('waiting for waitNotify'); await this.#pendingDropCampaignIdsNotifier.wait(); logger.debug('done'); } if (!this.#currentDropCampaignId) { continue; // This should never happen. Its here to make Typescript happy. } // Attempt to make progress towards the current drop campaign logger.info('Processing campaign: ' + this.#getDropCampaignFullName(this.#currentDropCampaignId)); lastDropCampaignAttemptTimes[this.#currentDropCampaignId] = new Date().getTime(); // Check if this drop campaign is active if (this.#dropCampaignMap[this.#currentDropCampaignId]['status'] !== 'ACTIVE') { logger.info('campaign not active'); this.#currentDropCampaignId = null; continue; } try { await this.#processDropCampaign(this.#currentDropCampaignId); //completedCampaignIds.add(currentDropCampaignId); logger.info('campaign completed'); } catch (error) { if (error instanceof NoStreamsError) { logger.info('No streams!'); } else if (error instanceof HighPriorityError) { // Ignore } else { logger.error(error); } } finally { this.#currentDropCampaignId = null; } } } /*stop() { // TODO: Implement this }*/ /** * Attempt to make progress towards the specified drop campaign. * @param dropCampaignId * @returns {Promise<void>} */ async #processDropCampaign(dropCampaignId: string) { const details = await this.#twitchClient.getDropCampaignDetails(dropCampaignId); while (true) { const drop = await this.#getFirstUnclaimedDrop(dropCampaignId); if (drop === null) { logger.debug('no more drops'); break; } logger.debug('working on drop ' + drop['id']); // Check if this drop is ready to be claimed const inventoryDrop = await this.#twitchClient.getInventoryDrop(drop['id'], dropCampaignId); if (inventoryDrop != null) { if (inventoryDrop['self']['currentMinutesWatched'] >= inventoryDrop['requiredMinutesWatched']) { await this.#claimDropReward(inventoryDrop); continue; } } // A mapping of stream URLs to an integer representing the number of times the stream failed while we were trying to watch it const failedStreamUrlCounts: { [key: string]: number } = {}; const failedStreamUrlExpireTime: { [key: string]: number } = {}; const failedStreamUrls = new Set(); while (true) { // Get a list of active streams that have drops enabled let streams = await this.#getActiveStreams(dropCampaignId, details); logger.info('Found ' + streams.length + ' active streams'); // Remove streams from the blacklist if they have been there long enough for (const x of streams) { const streamUrl = x.url; if (failedStreamUrls.has(streamUrl)) { if (new Date().getTime() >= failedStreamUrlExpireTime[streamUrl]) { failedStreamUrls.delete(streamUrl); failedStreamUrlCounts[streamUrl] = 0; } } } // Filter out streams that failed too many times streams = streams.filter(stream => { return !failedStreamUrls.has(stream.url); }); logger.info('Found ' + streams.length + ' good streams'); for (const x of Object.keys(failedStreamUrlCounts)) { logger.debug('failed: ' + failedStreamUrlCounts[x] + ' ' + x); } if (streams.length === 0) { throw new NoStreamsError(); } // Watch first stream const streamUrl = streams[0]['url']; logger.info('Watching stream: ' + streamUrl); try { await this.#watchStreamUntilCampaignCompleted(streamUrl, drop); } catch (error) { if (error instanceof NoProgressError) { logger.warn(error.message); } else if (error instanceof HighPriorityError) { throw error; } else if (error instanceof StreamLoadFailedError) { logger.warn('Stream failed to load!'); } else if (error instanceof StreamDownError) { logger.info('Stream went down'); /* If the stream goes down, add it to the failed stream urls immediately so we don't try it again. This is needed because getActiveStreams() can return streams that are down if they went down very recently. */ failedStreamUrls.add(streamUrl); // Schedule removal from block list! failedStreamUrlExpireTime[streamUrl] = new Date().getTime() + 1000 * 60 * this.#failedStreamBlacklistTimeout; } else { logger.error(error); if (process.env.SAVE_ERROR_SCREENSHOTS?.toLowerCase() === 'true') { await utils.saveScreenshotAndHtml(this.#page, 'error'); } } // Increment failure counter if (!(streamUrl in failedStreamUrlCounts)) { failedStreamUrlCounts[streamUrl] = 0; } failedStreamUrlCounts[streamUrl]++; // Move on if this stream failed too many times if (failedStreamUrlCounts[streamUrl] >= this.#failedStreamRetryCount) { logger.error('Stream failed too many times. Giving up for ' + this.#failedStreamBlacklistTimeout + ' minutes...'); failedStreamUrls.add(streamUrl); // Schedule removal from block list! failedStreamUrlExpireTime[streamUrl] = new Date().getTime() + 1000 * 60 * this.#failedStreamBlacklistTimeout; } continue; } finally { await this.#webSocketListener.detach(); } break; } } } async #claimDropReward(drop: InventoryDrop) { logger.info('Claiming drop!'); await this.#twitchClient.claimDropReward(drop.self.dropInstanceID); } // If user specified an increased timeout, use it, otherwise use the default 30 seconds async #waitUntilElementRendered(page: Page, element: ElementHandle, timeout: number = 1000 * this.#loadTimeoutSeconds) { const checkDurationMsecs = 1000; const maxChecks = timeout / checkDurationMsecs; let lastHTMLSize = 0; let checkCounts = 1; let countStableSizeIterations = 0; const minStableSizeIterations = 3; while (checkCounts++ <= maxChecks) { let html: string | undefined = await (await element.getProperty('outerHTML'))?.jsonValue(); if (!html) { throw new Error('HTML was undefined!'); } let currentHTMLSize = html.length; if (lastHTMLSize !== 0 && currentHTMLSize === lastHTMLSize) { countStableSizeIterations++; } else { countStableSizeIterations = 0; } if (countStableSizeIterations >= minStableSizeIterations) { break; } lastHTMLSize = currentHTMLSize; await page.waitForTimeout(checkDurationMsecs); } } #ansiEscape(code: string) { return '\x1B[' + code; } #startProgressBar(t = this.#total, p = this.#payload) { this.#isFirstOutput = true; this.#total = t; this.#payload = p; if (this.#progressBar !== null) { this.#progressBar.start(t, 0, p); this.#hasWrittenNewLine = false; } } #updateProgressBar(c = this.#currentProgress, p = this.#payload) { this.#currentProgress = c; this.#payload = p; if (this.#progressBar !== null) { this.#progressBar.update(c, p); } } #stopProgressBar(clear: boolean = false) { if (this.#progressBar !== null) { this.#progressBar.stop(); // The progress bar is a bit buggy since im using it for 2 lines but its only // intended to be used for 1 line. Also the logger does not play nice with it. // This is a workaround to try and avoid overwriting some lines in the terminal. // For more reliable logs, just look at the log file instead of the console. if (!this.#hasWrittenNewLine) { process.stdout.write('\n'); this.#hasWrittenNewLine = true; } } if (clear) { this.#progressBar = null; this.#payload = null; this.#total = null; this.#currentProgress = null; } } #createProgressBar() { // Create progress bar this.#progressBar = new cliProgress.SingleBar( { barsize: 20, stream: process.stdout, format: (options: any, params: any, payload: any) => { let result = 'Watching ' + payload['stream_url'] + ` | Viewers: ${payload['viewers']} | Uptime: ${payload['uptime']}` + this.#ansiEscape('0K') + '\n' + `${payload['drop_name']} ${BarFormat(params.progress, options)} ${params.value} / ${params.total} minutes` + this.#ansiEscape('0K') + '\n'; if (this.#isFirstOutput) { return result; } return this.#ansiEscape('2A') + result; } }, cliProgress.Presets.shades_classic ); this.#progressBar.on('redraw-post', () => { this.#isFirstOutput = false; }); } async #watchStreamUntilCampaignCompleted(streamUrl: string, targetDrop: Drop) { this.#targetDrop = targetDrop; this.#currentDrop = targetDrop; logger.debug('target: ' + targetDrop['id']); // Reset variables this.#viewerCount = 0; this.#currentMinutesWatched = {}; this.#currentMinutesWatched[targetDrop['id']] = 0; this.#lastMinutesWatched = {}; this.#lastMinutesWatched[targetDrop['id']] = -1; this.#lastProgressTime = {}; this.#lastProgressTime[targetDrop['id']] = new Date().getTime(); this.#isDropReadyToClaim = false; this.#isStreamDown = false; // Get initial drop progress const inventoryDrop = await this.#twitchClient.getInventoryDrop(targetDrop.id); if (inventoryDrop) { this.#currentMinutesWatched[targetDrop['id']] = inventoryDrop['self']['currentMinutesWatched']; this.#lastMinutesWatched[targetDrop['id']] = this.#currentMinutesWatched[targetDrop['id']]; logger.debug('Initial drop progress: ' + this.#currentMinutesWatched[targetDrop['id']] + ' minutes'); } else { logger.debug('Initial drop progress: none'); } // Create a "Chrome Devtools Protocol" session to listen to websocket events await this.#webSocketListener.attach(this.#page) await this.#page.goto(streamUrl); // Wait for the page to load completely (hopefully). This checks the video player container for any DOM changes and waits until there haven't been any changes for a few seconds. logger.info('Waiting for page to load...'); const element = (await this.#page.$x('//div[@data-a-player-state]'))[0] await this.#waitUntilElementRendered(this.#page, element); const streamPage = new StreamPage(this.#page); try { await streamPage.waitForLoad(); } catch (error) { if (error instanceof TimeoutError) { throw new StreamLoadFailedError(); } } try { // Click "Accept mature content" button await streamPage.acceptMatureContent(); logger.info('Accepted mature content'); } catch (error) { // Ignore errors, the button is probably not there } try { await streamPage.setLowestStreamQuality(); logger.info('Set stream to lowest quality'); } catch (error) { logger.error('Failed to set stream to lowest quality!'); throw error; } // This does not affect the drops, so if the user requests lets hide the videos if (this.#hideVideo) { try { await streamPage.hideVideoElements(); logger.info('Set stream visibility to hidden'); } catch (error) { logger.error('Failed to set stream visibility to hidden!'); throw error; } } const requiredMinutesWatched = targetDrop['requiredMinutesWatched']; this.#createProgressBar(); this.#viewerCount = await streamPage.getViewersCount(); this.#startProgressBar(requiredMinutesWatched, {'viewers': this.#viewerCount, 'uptime': await streamPage.getUptime(), drop_name: this.#getDropName(targetDrop), stream_url: streamUrl}); // The maximum amount of time to allow no progress const maxNoProgressTime = 1000 * 60 * 5; while (true) { if (this.#isStreamDown) { this.#isStreamDown = false; this.#stopProgressBar(true); await this.#page.goto("about:blank"); throw new StreamDownError('Stream went down!'); } this.#updateProgressBar(this.#currentMinutesWatched[this.#currentDrop['id']], {'viewers': this.#viewerCount, 'uptime': await streamPage.getUptime(), drop_name: this.#getDropName(this.#currentDrop), stream_url: streamUrl}); // Check if there are community points that we can claim const claimCommunityPointsSelector = 'div[data-test-selector="community-points-summary"] div.GTGMR button'; const claimCommunityPointsButton = await this.#page.$(claimCommunityPointsSelector); if (claimCommunityPointsButton) { try { await utils.click(this.#page, 'div[data-test-selector="community-points-summary"] div.GTGMR button'); logger.debug('Claimed community points!'); } catch (error) { logger.error('Failed to claim community points!'); logger.error(error); } } // Check if we have made progress towards the current drop if (new Date().getTime() - this.#lastProgressTime[this.#currentDrop['id']] >= maxNoProgressTime) { // Maybe we haven't got any updates from the web socket, lets check our inventory const currentDropId = this.#currentDrop['id']; const inventoryDrop = await this.#twitchClient.getInventoryDrop(currentDropId); if (inventoryDrop) { this.#currentMinutesWatched[currentDropId] = inventoryDrop['self']['currentMinutesWatched']; if (this.#currentMinutesWatched[currentDropId] > this.#lastMinutesWatched[currentDropId]) { this.#lastProgressTime[currentDropId] = new Date().getTime(); this.#lastMinutesWatched[currentDropId] = this.#currentMinutesWatched[currentDropId]; logger.debug('No progress from web socket! using inventory progress: ' + this.#currentMinutesWatched[currentDropId] + ' minutes'); } else { this.#stopProgressBar(true); await this.#page.goto("about:blank"); throw new NoProgressError("No progress was detected in the last " + (maxNoProgressTime / 1000 / 60) + " minutes!"); } } else { this.#stopProgressBar(true); await this.#page.goto("about:blank"); throw new NoProgressError("No progress was detected in the last " + (maxNoProgressTime / 1000 / 60) + " minutes!"); } } // Check if there is a higher priority stream we should be watching if (this.#pendingHighPriority) { this.#pendingHighPriority = false; this.#stopProgressBar(true); logger.info('Switching to higher priority stream'); throw new HighPriorityError(); } if (this.#isDropReadyToClaim) { this.#isDropReadyToClaim = false; this.#stopProgressBar(true); const inventoryDrop = await this.#twitchClient.getInventoryDrop(this.#currentDrop['id']); // Claim the drop await this.#claimDropReward(inventoryDrop); // After the reward was claimed set streamUrl to "about:blank". await this.#page.goto("about:blank"); // TODO: dont return, check for more drops return; } await this.#page.waitForTimeout(1000); } } async #getFirstUnclaimedDrop(campaignId: string) { // Get all drops for this campaign const details = await this.#twitchClient.getDropCampaignDetails(campaignId); for (const drop of details['timeBasedDrops']) { // TODO: Not all campaigns have time based drops // Check if we already claimed this drop if (await this.#isDropClaimed(drop)) { continue; } // Check if this drop has ended if (new Date() > new Date(Date.parse(drop['endAt']))) { continue; } // Check if this drop has started if (new Date() < new Date(Date.parse(drop['startAt']))) { continue; } return drop; } return null; } async #isDropClaimed(drop: Drop) { const inventory = await this.#twitchClient.getInventory(); // Check campaigns in progress const dropCampaignsInProgress = inventory['dropCampaignsInProgress']; if (dropCampaignsInProgress != null) { for (const campaign of dropCampaignsInProgress) { for (const d of campaign['timeBasedDrops']) { if (d['id'] === drop['id']) { return d['self']['isClaimed']; } } } } // Check claimed drops const gameEventDrops = inventory['gameEventDrops']; if (gameEventDrops != null) { for (const d of gameEventDrops) { if (d['id'] === drop['benefitEdges'][0]['benefit']['id']) { // I haven't found a way to confirm that this specific drop was claimed, but if we get to this point it // means one of two things: (1) We haven't made any progress towards the campaign so it does not show up // in the "dropCampaignsInProgress" section. (2) We have already claimed everything from this campaign. // In the first case, the drop won't show up here either so we can just return false. In the second case // I assume that if we received a drop reward of the same type after this campaign started, that it has // been claimed. return Date.parse(d['lastAwardedAt']) > Date.parse(drop['startAt']); } } } return false; } async #getActiveStreams(campaignId: string, details: CampaignDetails) { // Get a list of active streams that have drops enabled let streams = await this.#twitchClient.getDropEnabledStreams(this.#getDropCampaignById(campaignId)['game']['displayName']); // Filter out streams that are not in the allowed channels list, if any if (details.allow.isEnabled) { const channels = details.allow.channels; if (channels != null) { const channelIds = new Set(); for (const channel of channels) { channelIds.add(channel.id); } streams = streams.filter(stream => { return channelIds.has(stream.broadcaster_id); }); } } return streams; } #getDropCampaignFullName(campaignId: string) { const campaign = this.#getDropCampaignById(campaignId); return campaign['game']['displayName'] + ' ' + campaign['name']; } #getDropCampaignById(campaignId: string) { return this.#dropCampaignMap[campaignId]; } #getDropName(drop: Drop) { return drop['benefitEdges'][0]['benefit']['name']; } }
the_stack
import { CommandData } from "../module.base"; import { AIBackend, AIDagExecuteParameters, AIDevice, AIModelExecute, AIModelSetParameters, AIScriptExecuteParameters, AIScriptSetParameters, TensorType } from "./redis-ai.types"; export class RedisAICommander { /** * Setting a tensor * @param key The tensor's key name * @param type The tensor's data type can be one of: FLOAT , DOUBLE , INT8 , INT16 , INT32 , INT64 , UINT8 or UINT16 * @param data The tensor's data (binary/numberic) * @param shape One or more dimensions, or the number of elements per axis, for the tensor */ tensorset(key: string, type: TensorType, shapes: number[], data?: number[] | Buffer[]): CommandData { const args: (number | string | Buffer)[] = [key, type]; shapes.forEach(shape => {args.push(shape.toString())}); if(data !== undefined) { args.push(data instanceof Buffer ? 'BLOB': 'VALUES'); data.forEach((value: (number | string | Buffer)) => {args.push(value.toString())}); } return { command: 'AI.TENSORSET', args: args } } /** * Retrieving a tensor * @param key The tensor's key name * @param meta Returns the tensor's metadata * @param format The tensor's reply format can be one of the following (BLOB/VALUES) */ tensorget(key: string, format?: 'BLOB' | 'VALUES', meta?: boolean): CommandData { const args = [key]; if(meta === true){ args.push('META'); } if(format !== undefined){ args.push(format); } return { command: 'AI.TENSORGET', args: args } } /** * Setting a model * @param key The model's key name * @param backend The backend of the model * @param device The devide of the model * @param model The Protobuf-serialized model. Since Redis supports strings up to 512MB, blobs for very large * @param options Additional optional parameters */ modelstore(key: string, backend: AIBackend, device: AIDevice, model: Buffer, options?: AIModelSetParameters): CommandData { let args: (string | Buffer | number)[] = [key, backend, device]; if(options !== undefined && options.tag !== undefined){ args = args.concat(['TAG', options.tag]); } if(options !== undefined && options.batch !== undefined) { args = args.concat(['BATCHSIZE', options.batch.size]); if(options.batch.minSize !== undefined){ args = args.concat(['MINBATCHSIZE', options.batch.minSize]); } } if(options !== undefined && options.inputs !== undefined && options.inputs.length > 0){ args = args.concat(['INPUTS', options.inputsCount].concat(options.inputs)); } if(options !== undefined && options.outputs !== undefined && options.outputs.length > 0){ args = args.concat(['OUTPUTS', options.outputsCount].concat(options.outputs)); } args = args.concat(['BLOB', model]); return { command: 'AI.MODELSTORE', args: args } } /** * Retrieving a model * @param key The model's key name * @param meta Will return the model's meta information on backend, device and tag * @param blob Will return the model's blob containing the serialized model */ modelget(key: string, meta?: boolean, blob?: boolean): CommandData { const args = [key]; if(meta === true){ args.push('META'); } if(blob === true){ args.push('BLOB'); } return { command: 'AI.MODELGET', args: args } } /** * Deleting a model * @param key The model's key name */ modeldel(key: string): CommandData { return { command: 'AI.MODELDEL', args: [key] } } /** * Running a model * @param key The model's key name * @param parameters The parameters of 'AI.MODELEXECUTE' */ modelexecute(key: string, parameters: AIModelExecute): CommandData { let args = [key, 'INPUTS', parameters.inputsCount]; args = args.concat(parameters.inputs); args = args.concat(['OUTPUTS', parameters.outputsCount]); args = args.concat(parameters.outputs); if(parameters.timeout){ args = args.concat(['TIMEOUT', parameters.timeout]); } return { command: 'AI.MODELEXECUTE', args: args } } /** * Scanning a model */ modelscan(): CommandData { return { command: 'AI._MODELSCAN', args: [] } } /** * Setting a script * @param key The script's key name * @param parameters Additional optional parameters */ scriptset(key: string, parameters: AIScriptSetParameters): CommandData { let args = [key, parameters.device]; if(parameters.tag !== undefined){ args = args.concat(['TAG', parameters.tag]); } args = args.concat(['SOURCE', parameters.script]); return { command: 'AI.SCRIPTSET', args: args } } /** * Retrieving a script * @param key The script's key name * @param meta The script's device as a String * @param source The script's source code as a String */ scriptget(key: string, meta?: boolean, source?: boolean): CommandData { const args = [key]; if(meta === true){ args.push('META'); } if(source === true){ args.push('SOURCE'); } return { command: 'AI.SCRIPTGET', args: args } } /** * Deleting a script * @param key The script's key name */ scriptdel(key: string): CommandData { return { command: 'AI.SCRIPTDEL', args: [key] } } /** * Running a script * @param key The script's key nameb * @param functionName The name of the function to run * @param parameters The parameters of the 'AI.SCRIPTEXECUTE' command */ scriptexecute(key: string, functionName: string, parameters: AIScriptExecuteParameters): CommandData { let args = [key, functionName, 'KEYS', parameters.numberOfKeys].concat(parameters.keys) if(parameters.inputs && parameters.numberOfInputs && parameters.inputs.length > 0){ args = args.concat(['INPUTS', parameters.numberOfInputs]).concat(parameters.inputs) } else if(parameters.listInputs && parameters.numberOfListInputs && parameters.listInputs.length > 0){ args = args.concat('LIST_INPUTS', parameters.numberOfListInputs).concat(parameters.listInputs) } args = args.concat('OUTPUTS', parameters.numberOfOutputs).concat(parameters.outputs) if(parameters.timeout){ args.concat('TIMEOUT', parameters.timeout) } return { command: 'AI.SCRIPTEXECUTE', args: args } } /** * Scanning a script */ scriptscan(): CommandData { return { command: 'AI._SCRIPTSCAN', args: [] } } /** * Running a DAG * @param parameters Additional parameters required for the 'AI.DAGEXECUTE' command * @param commands The commands sent to the 'AI.DAGEXECUTE' command */ dagexecute(parameters: AIDagExecuteParameters, commands: string[]): CommandData { return { command: 'AI.DAGEXECUTE', args: this.generateDagRunArguments(parameters, commands) } } /** * Running a readonly DAG * @param parameters Additional parameters required for the 'AI.DAGEXECUTE_RO' command * @param commands The commands sent to the 'AI.DAGEXECUTE_RO' command */ dagexecuteRO(parameters: AIDagExecuteParameters, commands: string[]): CommandData { return { command: 'AI.DAGEXECUTE_RO', args: this.generateDagRunArguments(parameters, commands) } } /** * Generating the dagexecute CLI arguments * @param parameters Additional parameters required for the DAG command * @param commands The given commands */ private generateDagRunArguments(parameters: AIDagExecuteParameters, commands: string[]): string[] { let args: string[] = []; args = args.concat([parameters.type.toUpperCase(), `${parameters.numberOfKeys}`].concat(parameters.keys)); if(parameters.timeout) { args = args.concat(['TIMEOUT', `${parameters.timeout}`]) } commands.forEach(command => { args = args.concat(['|>'].concat(command.split(' '))) }); return args; } /** * Retrieving script/model info * @param key The key name of a model or script * @param RESETSTAT Resets all statistics associated with the key */ info(key: string, RESETSTAT?: boolean): CommandData { const args = [key] if(RESETSTAT === true) args.push('RESETSTAT') return { command: 'AI.INFO', args: args } } /** * Restrieving configuration * @param path Specifies the default base backends path to path . The backends path is used when dynamically loading a backend (default: '{module_path}/backends', where module_path is the module's path). * @param backend Loads the DL/ML backend specified by the backend identifier from path . If path is relative, it is resolved by prefixing the BACKENDSPATH to it. If path is absolute then it is used as is. */ config(path: string, backend?: AIBackend): CommandData { let args: string[] = [] if(backend !== undefined) args = args.concat(['LOADBACKEND', backend, path]) else args = args.concat(['BACKENDSPATH', path]) return { command: 'AI.CONFIG', args: args } } }
the_stack
import Adapt, { AdaptElement, BuiltinProps, GoalStatus, PrimitiveComponent, SFCBuildProps, SFCDeclProps, useDeployedWhen, waiting, } from "@adpt/core"; import { mapMap } from "@adpt/utils"; import { ReplaceT } from "type-ops"; import { Container as AbsContainer, ContainerProps as AbsContainerProps, useLatestImageFrom, } from "../Container"; import { mergeEnvPairs } from "../env"; import { PodSecurityContext } from "./Pod"; /** @public */ export interface VolumeMount { /** * Path within the container at which the volume should be mounted. * * Must not contain ':'. */ mountPath: string; /** * mountPropagation determines how mounts are propagated from the host to container and the other way around. * * When not set, MountPropagationNone is used. This field is beta in 1.10. * * @defaultValue MountPropagationNone */ mountPropagation?: string; /** This must match the Name of a Volume. */ name: string; /** * Mounted read-only if true, read-write otherwise (false or unspecified). * * @defaultValue false */ readOnly?: boolean; /** * Path within the volume from which the container's volume should be mounted. * * Defaults to "" (volume's root). * * @defaultValue "" */ subPath?: string; /** * Expanded path within the volume from which the container's volume should be mounted. * * Behaves similarly to SubPath but environment variable references $(VAR_NAME) * are expanded using the container's environment. * * Defaults to "" (volume's root). * * SubPathExpr and SubPath are mutually exclusive. * * @defaultValue "" */ subPathExpr?: string; } /** @public */ export interface ConfigMapEnvSource { /** * Name of the referent. * * More info: {@link https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names} */ name?: string; /** * Specify whether the ConfigMap must be defined */ optional?: boolean; } /** @public */ export interface SecretEnvSource { /** * Name of the referent. * * More info: {@link https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names} */ name?: string; /** * Specify whether the Secret must be defined */ optional?: boolean; } /** @public */ export interface EnvFromSource { /** The ConfigMap to select from */ configMapRef?: ConfigMapEnvSource; /** An optional identifier to prepend to each key in the ConfigMap. Must be a C_IDENTIFIER. */ prefix?: string; /** SecretEnvSource The Secret to select from */ secretRef?: SecretEnvSource; } /** @public */ export interface ExecAction { /** * Command is the command line to execute inside the container. * * The working directory for the command is root ('/') in the container's filesystem. * The command is simply exec'd, it is not run inside a shell, * so traditional shell instructions ('|', etc) won't work. * To use a shell, you need to explicitly call out to that shell. * * Exit status of 0 is treated as live/healthy and non-zero is unhealthy. */ command: string[]; } /** @public */ export interface HTTPGetAction { /** * Host name to connect to, defaults to the pod IP. * * You probably want to set "Host" in httpHeaders instead. */ host?: string; /** Custom headers to set in the request. HTTP allows repeated headers. */ httpHeaders?: { name: string; value: string; }[]; /** Path to access on the HTTP server. */ path: string; /** * Name or number of the port to access on the container. * * Number must be in the range 1 to 65535. Name must be an IANA_SVC_NAME. */ port: number | string; /** * Scheme to use for connecting to the host. * * @defaultValue HTTP. */ scheme?: string; } /** @public */ export interface TCPSocketAction { /** Host name to connect to, defaults to the pod IP. */ host?: string; /** * Number or name of the port to access on the container. * * Number must be in the range 1 to 65535. * Name must be an IANA_SVC_NAME. */ port: string | number; } /** @public */ export interface Probe { /** * Exec specifies the action to take. * * Only one of exec, httpGet, or tcpSocket should be specified */ exec?: ExecAction; /** * Minimum consecutive failures for the probe to be considered failed after having succeeded. * * Defaults to 3. Minimum value is 1. * * @defaultValue 3 */ failureThreshold?: number; /** Specifies the http request to perform. */ httpGet?: HTTPGetAction; /** * Seconds after the container has started before liveness probes are initiated. * More info: {@link https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes} */ initialDelaySeconds?: number; /** How often (in seconds) to perform the probe. Default to 10 seconds. Minimum value is 1. */ periodSeconds?: number; /** * Minimum consecutive successes for the probe to be considered successful after having failed. * * Must be 1 for liveness and startup. Minimum value is 1. * * @defaultValue 1 */ successThreshold?: number; /** * Specifies an action involving a TCP port. * * TCP hooks not yet supported */ tcpSocket?: TCPSocketAction; /** * Number of seconds after which the probe times out. * * Defaults to 1 second. Minimum value is 1. * * More info: {@link https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes} * * @defaultValue 1 */ timeoutSeconds?: number; } /** @public */ export interface ResourceRequirements { /** * Limits describes the maximum amount of compute resources allowed. * * More info: {@link https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/} */ limits?: { [key: string]: any }; /** * Describes the minimum amount of compute resources required. * * If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, * otherwise to an implementation-defined value. * * More info: {@link https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/} */ requests?: { [key: string]: any }; } /** @public */ export type Handler = { exec: ExecAction; } | { httpGet: HTTPGetAction; } | { tcpSocket: TCPSocketAction; }; /** @public */ export interface Lifecycle { /** * PostStart is called immediately after a container is created. * * If the handler fails, the container is terminated and restarted according to its restart policy. * Other management of the container blocks until the hook completes. * * More info: {@link https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks} */ postStart: Handler; //tslint:disable max-line-length /** * Called immediately before a container is terminated due to an API request or management event such as liveness/startup probe failure, preemption, resource contention, etc. * * The handler is not called if the container crashes or exits. * The reason for termination is passed to the handler. * The Pod's termination grace period countdown begins before the PreStop hooked is executed. * Regardless of the outcome of the handler, the container will eventually terminate within the Pod's termination grace period. * Other management of the container blocks until the hook completes or until the termination grace period is reached. * * More info: {@link https://kubernetes.io/docs/concepts/containers/container-lifecycle-hooks/#container-hooks} */ //tslint:enable max-line-length preStop: Handler; } /** @public */ export interface VolumeDevice { /** The path inside of the container that the device will be mapped to. */ devicePath: string; /** name must match the name of a persistentVolumeClaim in the pod */ name: string; } /** * Resource spec for a Kubernetes container. * See the Kubernetes * {@link https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.18/#container-v1-core | API docs } * for more details. * @public */ export interface ContainerSpec { //tslint:disable max-line-length /** * Arguments to the entrypoint. * * The docker image's CMD is used if this is not provided. * Variable references $(VAR_NAME) are expanded using the container's environment. * If a variable cannot be resolved, the reference in the input string will be unchanged. * The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). * Escaped references will never be expanded, regardless of whether the variable exists or not. * Cannot be updated. * More info: {@link https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell} */ //tslint:enable max-line-length args?: string[]; //tslint:disable max-line-length /** * Entrypoint array. * * Not executed within a shell. * The docker image's ENTRYPOINT is used if this is not provided. * Variable references $(VAR_NAME) are expanded using the container's environment. * If a variable cannot be resolved, the reference in the input string will be unchanged. * The $(VAR_NAME) syntax can be escaped with a double $$, ie: $$(VAR_NAME). * Escaped references will never be expanded, regardless of whether the variable exists or not. * Cannot be updated. * More info: {@link https://kubernetes.io/docs/tasks/inject-data-application/define-command-argument-container/#running-a-command-in-a-shell} */ //tslint:enable max-line-length command?: string[]; /** * List of environment variables to set in the container. Cannot be updated. */ env?: EnvVar[]; /** * List of sources to populate environment variables in the container. * * The keys defined within a source must be a C_IDENTIFIER. * All invalid keys will be reported as an event when the container is starting. * When a key exists in multiple sources, the value associated with the last source will take precedence. * Values defined by an Env with a duplicate key will take precedence. Cannot be updated. */ envFrom?: EnvFromSource[]; /** * Docker image name. * * More info: {@link https://kubernetes.io/docs/concepts/containers/images} * * This field is optional to allow higher level config management to default or override container * images in workload controllers like Deployments and StatefulSets. */ image?: string; /** * Image pull policy. * * One of Always, Never, IfNotPresent. * Defaults to Always if :latest tag is specified, * or IfNotPresent otherwise. * Cannot be updated. * * More info: {@link https://kubernetes.io/docs/concepts/containers/images#updating-images} */ imagePullPolicy?: "Always" | "Never" | "IfNotPresent"; /** * List of sources to populate environment variables in the container. * * The keys defined within a source must be a C_IDENTIFIER. * All invalid keys will be reported as an event when the container is starting. * When a key exists in multiple sources, the value associated with the last source will take precedence. * Values defined by an Env with a duplicate key will take precedence. Cannot be updated. */ lifecycle?: Lifecycle; /** * Periodic probe of container liveness. * * Container will be restarted if the probe fails. * Cannot be updated. * More info: {@link https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes} */ livenessProbe?: Probe; /** * Name of the container specified as a DNS_LABEL. * * Each container in a pod must have a unique name (DNS_LABEL). Cannot be updated. */ name: string; //Must be unique within pod /** * List of ports to expose from the container. * * Exposing a port here gives the system additional information about the network connections a container uses, * but is primarily informational. * Not specifying a port here DOES NOT prevent that port from being exposed. * Any port which is listening on the default "0.0.0.0" address inside a container will be accessible from * the network. * Cannot be updated. */ ports?: ContainerPort[]; /** * Periodic probe of container service readiness. * * Container will be removed from service endpoints if the probe fails. * Cannot be updated. * * More info: {@link https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes} */ readinessProbe?: Probe; /** * Compute Resources required by this container. * * Cannot be updated. * * More info: {@link https://kubernetes.io/docs/concepts/configuration/manage-compute-resources-container/} */ resources?: ResourceRequirements; /** * Security options the pod should run with. * * More info: {@link https://kubernetes.io/docs/concepts/policy/security-context/} * More info: {@link https://kubernetes.io/docs/tasks/configure-pod-container/security-context/} */ securityContext?: PodSecurityContext; /** * Indicates that the Pod has successfully initialized. * * If specified, no other probes are executed until this completes successfully. * If this probe fails, the Pod will be restarted, just as if the livenessProbe failed. * This can be used to provide different probe parameters at the beginning of a Pod's lifecycle, * when it might take a long time to load data or warm a cache, than during steady-state operation. * * This cannot be updated. * This is a beta feature enabled by the StartupProbe feature flag. * More info: {@link https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle#container-probes} */ startupProbe?: Probe; /** * Whether this container should allocate a buffer for stdin in the container runtime. * * If this is not set, reads from stdin in the container will always result in EOF. Default is false. */ stdin?: boolean; /** * Whether the container runtime should close the stdin channel after it has been opened by a single attach. * * When stdin is true the stdin stream will remain open across multiple attach sessions. * If stdinOnce is set to true, stdin is opened on container start, * is empty until the first client attaches to stdin, * and then remains open and accepts data until the client disconnects, * at which time stdin is closed and remains closed until the container is restarted. * If this flag is false, a container processes that reads from stdin will never receive an EOF. Default is false */ stdinOnce?: boolean; // tslint:disable max-line-length /** * Path at which the file to which the container's termination message will be written is mounted into the container's filesystem. * * Message written is intended to be brief final status, such as an assertion failure message. * Will be truncated by the node if greater than 4096 bytes. * The total message length across all containers will be limited to 12kb. * Defaults to /dev/termination-log. Cannot be updated. */ // tslint:enable max-line-length terminationMessagePath?: string; /** * Indicate how the termination message should be populated. * * File will use the contents of terminationMessagePath to populate the container status * message on both success and failure. FallbackToLogsOnError will use the last chunk of * container log output if the termination message file is empty and the container exited * with an error. * The log output is limited to 2048 bytes or 80 lines, whichever is smaller. * Defaults to File. * Cannot be updated. * * @defaultValue File */ terminationMessagePolicy?: "File" | "FallbackToLogsOnError"; /** * Whether this container should allocate a TTY for itself, also requires 'stdin' to be true. * * @defaultValue false */ tty?: boolean; /** * volumeDevices is the list of block devices to be used by the container. */ volumeDevices?: VolumeDevice[]; /** volumeDevices is the list of block devices to be used by the container. */ volumeMounts?: VolumeMount[]; /** * Container's working directory. * * If not specified, the container runtime's default will be used, * which might be configured in the container image. * Cannot be updated. */ workingDir?: string; } /** * Props for the Kubernetes-specific {@link k8s.K8sContainer} component. * @public */ export interface K8sContainerProps extends ContainerSpec { } /** @public */ export interface ContainerPort { /** * Number of port to expose on the pod's IP address. * @remarks * This must be a valid integer port number, `0 < x < 65536`. */ containerPort: number; /** What host IP to bind the external port to. */ hostIP?: string; /** * Number of port to expose on the host. * @remarks * If specified, this must be a valid integer port number, * `0 < x < 65536`. If HostNetwork is specified, * this must match ContainerPort. Most containers do not need this. */ hostPort?: number; /** * A unique-within-pod name for the container * @remarks * If specified, this must be an IANA_SVC_NAME and unique within the pod. * Each named port in a pod must have a unique name. Name for the port * that can be referred to by services. */ name?: string; /** Protocol for port. Must be UDP or TCP. Defaults to "TCP". */ protocol?: string; } /** @public */ export type EnvVar = EnvVarSimple | EnvVarFrom; /** @public */ export interface EnvVarSimple { /** Name of the environment variable. Must be a C_IDENTIFIER. */ name: string; /** * Variable references $(VAR_NAME) are expanded using the previous defined * environment variables in the container and any service environment * variables. If a variable cannot be resolved, the reference in the input * string will be unchanged. The $(VAR_NAME) syntax can be escaped with a * double $$, ie: $$(VAR_NAME). Escaped references will never be expanded, * regardless of whether the variable exists or not. Defaults to "". */ value: string; } /** @public */ export interface EnvVarFrom { /** Source for the environment variable's value. Cannot be used if value is not empty. */ valueFrom?: any; //EnvVarSource; // NOTE(mansihv): EnvVarSource needs implementation } const toK8sEnv = mergeEnvPairs; const defaultProtocol = "tcp"; class PortInfo { portMap = new Map<string, ContainerPort>(); get containerPorts(): ContainerPort[] | undefined { if (this.portMap.size === 0) return undefined; return mapMap(this.portMap, (_, p) => p); } addPortMapping(ctrPort: number | string, hostPort?: number) { ctrPort = Number(ctrPort); if (isNaN(ctrPort)) { throw new Error(`Non-numeric port description not implemented`); } const e = this.entry(ctrPort); if (hostPort !== undefined) e.hostPort = hostPort; } entry(containerPort: number) { const key = this.makeKey(containerPort); let e = this.portMap.get(key); if (e === undefined) { e = { containerPort }; this.portMap.set(key, e); } return e; } makeKey(ctrPort: number, protocol = defaultProtocol): string { return `${protocol}/${ctrPort}`; } } function toK8sPorts(abstractProps: AbsContainerProps): ContainerPort[] | undefined { const { ports, portBindings } = abstractProps; const pInfo = new PortInfo(); if (ports != null) ports.forEach((p) => pInfo.addPortMapping(p)); if (portBindings != null) { Object.keys(portBindings).forEach((ctrPort) => pInfo.addPortMapping(ctrPort, portBindings[ctrPort])); } return pInfo.containerPorts; } /** * See {@link k8s.k8sContainerProps}. * @public */ export type FromContainerProps = ReplaceT<AbsContainerProps, { image: string }> & BuiltinProps; /** * Low level utility function to translate from the abstract {@link Container} * component props ({@link ContainerProps}) to {@link k8s.K8sContainerProps} * to be used in a {@link k8s.K8sContainer}. * @remarks * Note: The `image` property in the passed in {@link ContainerProps} must * be a `string`, not a `Handle`. * In most cases, it is preferable to use the {@link k8s.Container} component * instead, which is designed specifically to deal with this issue. * * @param abstractProps - The abstract {@link ContainerProps} to translate from. * @param k8sProps - Props that are specific to the {@link k8s.K8sContainer} * component that should be merged into the resulting returned * {@link k8s.K8sContainerProps} object. * @public */ export function k8sContainerProps(abstractProps: FromContainerProps, k8sProps?: Partial<K8sContainerProps>): K8sContainerProps { const { command, entrypoint, environment, tty, workingDir } = abstractProps; const ret: K8sContainerProps & Partial<BuiltinProps> = { key: abstractProps.key, name: abstractProps.name, image: abstractProps.image, ...(k8sProps || {}), }; if (entrypoint != null) { ret.args = Array.isArray(entrypoint) ? entrypoint : [entrypoint]; } if (command != null) { ret.command = Array.isArray(command) ? command : [command]; } ret.env = toK8sEnv(environment); ret.ports = toK8sPorts(abstractProps); if (tty != null) ret.tty = tty; if (workingDir != null) ret.workingDir = workingDir; return ret; } /** * Tests whether an element is a {@link k8s.K8sContainer} element * @param x - element to test * @returns `true` if element is a {@link k8s.K8sContainer}, `false` otherwise * * @remarks * Acts as a TypeScript type assertion that will assert that `x` is `AdaptElement<K8sContainerProps>` * * @public */ export function isK8sContainerElement(x: AdaptElement): x is AdaptElement<K8sContainerProps> { return x.componentType === K8sContainer; } /** * Kubernetes-specific container. * @public */ export class K8sContainer extends PrimitiveComponent<K8sContainerProps> { static defaultProps = { imagePullPolicy: "IfNotPresent" }; validate() { if (this.props.image == null || this.props.image === "") { throw new Error("K8sContainer: image is a required value"); } return undefined; //FIXME(manishv) check if name is legal in k8s //FIXME(manishv) check if image string is valid URL //FIXME(manishv) check if workDir is valid path } } /** * Props for {@link k8s.Container}. * @public */ export interface ContainerProps extends SFCDeclProps<AbsContainerProps> { /** * Additional {@link k8s.K8sContainerProps}-specific props that should be * added to the instantiated {@link k8s.K8sContainer}. */ k8sContainerProps?: Partial<K8sContainerProps>; } /** * Component that implements the abstract {@link Container} interface and * translates to a Kubernetes-specific {@link k8s.K8sContainer}. * @public */ export function Container(props: ContainerProps) { const { image: imgOrHandle, k8sContainerProps: addlProps, ...rest } = props as SFCBuildProps<ContainerProps>; const image = useLatestImageFrom(imgOrHandle); useDeployedWhen((gs) => { if (gs === GoalStatus.Destroyed || image) return true; return waiting("Waiting for Docker image"); }); if (!image) return null; const kProps = k8sContainerProps({ ...rest, image }, addlProps); return <K8sContainer {...kProps} />; } // TODO: The "as any" is a workaround for an api-extractor bug. See issue #185. (Container as any).displayName = "k8s.Container"; (Container as any).defaultProps = AbsContainer.defaultProps;
the_stack
import type {Mutable, ObserverType} from "@swim/util"; import type {FastenerOwner} from "@swim/component"; import type {Trait} from "@swim/model"; import type {View} from "@swim/view"; import type {Controller} from "../controller/Controller"; import {ControllerSetInit, ControllerSetClass, ControllerSet} from "../controller/ControllerSet"; import type {TraitViewRef} from "./TraitViewRef"; /** @internal */ export type TraitViewControllerSetType<F extends TraitViewControllerSet<any, any, any, any>> = F extends TraitViewControllerSet<any, any, any, infer C> ? C : never; /** @public */ export interface TraitViewControllerSetInit<T extends Trait = Trait, V extends View = View, C extends Controller = Controller> extends ControllerSetInit<C> { extends?: {prototype: TraitViewControllerSet<any, any, any, any>} | string | boolean | null; getTraitViewRef?(controller: C): TraitViewRef<any, T, V>; willAttachControllerTrait?(controller: C, trait: T, targetTrait: Trait | null): void; didAttachControllerTrait?(controller: C, trait: T, targetTrait: Trait | null): void; willDetachControllerTrait?(controller: C, trait: T): void; didDetachControllerTrait?(controller: C, trait: T): void; createController?(trait?: T): C; parentView?: View | null; } /** @public */ export type TraitViewControllerSetDescriptor<O = unknown, T extends Trait = Trait, V extends View = View, C extends Controller = Controller, I = {}> = ThisType<TraitViewControllerSet<O, T, V, C> & I> & TraitViewControllerSetInit<T, V, C> & Partial<I>; /** @public */ export interface TraitViewControllerSetClass<F extends TraitViewControllerSet<any, any, any, any> = TraitViewControllerSet<any, any, any, any>> extends ControllerSetClass<F> { } /** @public */ export interface TraitViewControllerSetFactory<F extends TraitViewControllerSet<any, any, any, any> = TraitViewControllerSet<any, any, any, any>> extends TraitViewControllerSetClass<F> { extend<I = {}>(className: string, classMembers?: Partial<I> | null): TraitViewControllerSetFactory<F> & I; define<O, T extends Trait = Trait, V extends View = View, C extends Controller = Controller>(className: string, descriptor: TraitViewControllerSetDescriptor<O, T, V, C>): TraitViewControllerSetFactory<TraitViewControllerSet<any, T, V, C>>; define<O, T extends Trait = Trait, V extends View = View, C extends Controller = Controller>(className: string, descriptor: {observes: boolean} & TraitViewControllerSetDescriptor<O, T, V, C, ObserverType<C>>): TraitViewControllerSetFactory<TraitViewControllerSet<any, T, V, C>>; define<O, T extends Trait = Trait, V extends View = View, C extends Controller = Controller, I = {}>(className: string, descriptor: {implements: unknown} & TraitViewControllerSetDescriptor<O, T, V, C, I>): TraitViewControllerSetFactory<TraitViewControllerSet<any, T, V, C> & I>; define<O, T extends Trait = Trait, V extends View = View, C extends Controller = Controller, I = {}>(className: string, descriptor: {implements: unknown; observes: boolean} & TraitViewControllerSetDescriptor<O, T, V, C, I & ObserverType<C>>): TraitViewControllerSetFactory<TraitViewControllerSet<any, T, V, C> & I>; <O, T extends Trait = Trait, V extends View = View, C extends Controller = Controller>(descriptor: TraitViewControllerSetDescriptor<O, T, V, C>): PropertyDecorator; <O, T extends Trait = Trait, V extends View = View, C extends Controller = Controller>(descriptor: {observes: boolean} & TraitViewControllerSetDescriptor<O, T, V, C, ObserverType<C>>): PropertyDecorator; <O, T extends Trait = Trait, V extends View = View, C extends Controller = Controller, I = {}>(descriptor: {implements: unknown} & TraitViewControllerSetDescriptor<O, T, V, C, I>): PropertyDecorator; <O, T extends Trait = Trait, V extends View = View, C extends Controller = Controller, I = {}>(descriptor: {implements: unknown; observes: boolean} & TraitViewControllerSetDescriptor<O, T, V, C, I & ObserverType<C>>): PropertyDecorator; } /** @public */ export interface TraitViewControllerSet<O = unknown, T extends Trait = Trait, V extends View = View, C extends Controller = Controller> extends ControllerSet<O, C> { /** @internal */ readonly traitControllers: {readonly [traitId: number]: C | undefined}; /** @internal */ getTraitViewRef(controller: C): TraitViewRef<unknown, T, V>; hasTraitController(trait: Trait): boolean; addTraitController(trait: T, targetTrait?: Trait | null, key?: string): C; removeTraitController(trait: T): C | null; deleteTraitController(trait: T): C | null; attachControllerTrait(controller: C, trait: T, targetTrait?: Trait | null): C; /** @protected */ initControllerTrait(controller: C, trait: T): void; /** @protected */ willAttachControllerTrait(controller: C, trait: T, targetTrait: Trait | null): void; /** @protected */ onAttachControllerTrait(controller: C, trait: T, targetTrait: Trait | null): void; /** @protected */ didAttachControllerTrait(controller: C, trait: T, targetTrait: Trait | null): void; detachControllerTrait(controller: C, trait: T): C | null; /** @protected */ deinitControllerTrait(controller: C, trait: T): void; /** @protected */ willDetachControllerTrait(controller: C, trait: T): void; /** @protected */ onDetachControllerTrait(controller: C, trait: T): void; /** @protected */ didDetachControllerTrait(controller: C, trait: T): void; /** @protected @override */ onAttachController(controller: C, targetController: Controller | null): void; /** @protected @override */ onDetachController(controller: C): void; createController(trait?: T): C; /** @internal @protected */ get parentView(): View | null; // optional prototype property } /** @public */ export const TraitViewControllerSet = (function (_super: typeof ControllerSet) { const TraitViewControllerSet: TraitViewControllerSetFactory = _super.extend("TraitViewControllerSet"); TraitViewControllerSet.prototype.getTraitViewRef = function <T extends Trait, V extends View, C extends Controller>(controller: C): TraitViewRef<unknown, T, V> { throw new Error("missing implementation"); }; TraitViewControllerSet.prototype.hasTraitController = function (this: TraitViewControllerSet, trait: Trait): boolean { return this.traitControllers[trait.uid] !== void 0; }; TraitViewControllerSet.prototype.addTraitController = function <T extends Trait, V extends View, C extends Controller>(this: TraitViewControllerSet<unknown, T, V, C>, trait: T, targetTrait?: Trait | null, key?: string): C { const traitControllers = this.traitControllers as {[traitId: number]: C | undefined}; let controller = traitControllers[trait.uid]; if (controller === void 0) { controller = this.createController(trait); const traitViewRef = this.getTraitViewRef(controller); traitViewRef.setTrait(trait, targetTrait, key); const targetController = targetTrait !== void 0 && targetTrait !== null ? traitControllers[targetTrait.uid] : void 0; this.addController(controller, targetController, key); if (traitViewRef.view === null) { const view = traitViewRef.createView(); const targetView = targetController !== void 0 ? this.getTraitViewRef(targetController).view : null; traitViewRef.insertView(this.parentView, view, targetView, key); } } return controller; }; TraitViewControllerSet.prototype.removeTraitController = function <T extends Trait, C extends Controller>(this: TraitViewControllerSet<unknown, T, View, C>, trait: T): C | null { const controllers = this.controllers; for (const controllerId in controllers) { const controller = controllers[controllerId]!; const traitViewRef = this.getTraitViewRef(controller); if (traitViewRef.trait === trait) { this.removeController(controller); return controller; } } return null; }; TraitViewControllerSet.prototype.deleteTraitController = function <T extends Trait, C extends Controller>(this: TraitViewControllerSet<unknown, T, View, C>, trait: T): C | null { const controllers = this.controllers; for (const controllerId in controllers) { const controller = controllers[controllerId]!; const traitViewRef = this.getTraitViewRef(controller); if (traitViewRef.trait === trait) { this.deleteController(controller); return controller; } } return null; }; TraitViewControllerSet.prototype.attachControllerTrait = function <T extends Trait, C extends Controller>(this: TraitViewControllerSet<unknown, T, View, C>, controller: C, trait: T, targetTrait?: Trait | null): C { const traitControllers = this.traitControllers as {[traitId: number]: C | undefined}; let traitController = traitControllers[trait.uid]; if (traitController === void 0) { traitController = controller; if (targetTrait === void 0) { targetTrait = null; } this.willAttachControllerTrait(traitController, trait, targetTrait); traitControllers[trait.uid] = traitController; (this as Mutable<typeof this>).controllerCount += 1; this.onAttachControllerTrait(traitController, trait, targetTrait); this.initControllerTrait(traitController, trait); this.didAttachControllerTrait(traitController, trait, targetTrait); } return traitController; }; TraitViewControllerSet.prototype.detachControllerTrait = function <T extends Trait, C extends Controller>(this: TraitViewControllerSet<unknown, T, View, C>, controller: C, trait: T): C | null { const traitControllers = this.traitControllers as {[comtroltraitIdltraitIderId: number]: C | undefined}; const traitController = traitControllers[trait.uid]; if (traitController !== void 0) { this.willDetachControllerTrait(traitController, trait); (this as Mutable<typeof this>).controllerCount -= 1; delete traitControllers[trait.uid]; this.onDetachControllerTrait(traitController, trait); this.deinitControllerTrait(traitController, trait); this.didDetachControllerTrait(traitController, trait); return traitController; } return null; }; TraitViewControllerSet.prototype.initControllerTrait = function <T extends Trait, C extends Controller>(this: TraitViewControllerSet<unknown, T, View, C>, controller: C, trait: T): void { // hook }; TraitViewControllerSet.prototype.willAttachControllerTrait = function <T extends Trait, C extends Controller>(this: TraitViewControllerSet<unknown, T, View, C>, controller: C, trait: T, targetTrait: Trait | null): void { // hook }; TraitViewControllerSet.prototype.onAttachControllerTrait = function <T extends Trait, C extends Controller>(this: TraitViewControllerSet<unknown, T, View, C>, controller: C, trait: T, targetTrait: Trait | null): void { // hook }; TraitViewControllerSet.prototype.didAttachControllerTrait = function <T extends Trait, C extends Controller>(this: TraitViewControllerSet<unknown, T, View, C>, controller: C, trait: T, targetTrait: Trait | null): void { // hook }; TraitViewControllerSet.prototype.deinitControllerTrait = function <T extends Trait, C extends Controller>(this: TraitViewControllerSet<unknown, T, View, C>, controller: C, trait: T): void { // hook }; TraitViewControllerSet.prototype.willDetachControllerTrait = function <T extends Trait, C extends Controller>(this: TraitViewControllerSet<unknown, T, View, C>, controller: C, trait: T): void { // hook }; TraitViewControllerSet.prototype.onDetachControllerTrait = function <T extends Trait, C extends Controller>(this: TraitViewControllerSet<unknown, T, View, C>, controller: C, trait: T): void { // hook }; TraitViewControllerSet.prototype.didDetachControllerTrait = function <T extends Trait, C extends Controller>(this: TraitViewControllerSet<unknown, T, View, C>, controller: C, trait: T): void { // hook }; TraitViewControllerSet.prototype.onAttachController = function <T extends Trait, C extends Controller>(this: TraitViewControllerSet<unknown, T, View, C>, controller: C, targetController: Controller | null): void { const trait = this.getTraitViewRef(controller).trait; if (trait !== null) { const targetTrait = targetController !== null && this.hasController(targetController) ? this.getTraitViewRef(targetController as C).trait : null; this.attachControllerTrait(controller, trait, targetTrait); } ControllerSet.prototype.onAttachController.call(this, controller, targetController); }; TraitViewControllerSet.prototype.onDetachController = function <T extends Trait, C extends Controller>(this: TraitViewControllerSet<unknown, T, View, C>, controller: C): void { ControllerSet.prototype.onDetachController.call(this, controller); const trait = this.getTraitViewRef(controller).trait; if (trait !== null) { this.detachControllerTrait(controller, trait); } }; Object.defineProperty(TraitViewControllerSet.prototype, "parentView", { get: function (this: TraitViewControllerSet): View | null { return null; }, configurable: true, }); TraitViewControllerSet.construct = function <F extends TraitViewControllerSet<any, any, any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F { fastener = _super.construct(fastenerClass, fastener, owner) as F; (fastener as Mutable<typeof fastener>).traitControllers = {}; return fastener; }; TraitViewControllerSet.define = function <O, T extends Trait, V extends View, C extends Controller>(className: string, descriptor: TraitViewControllerSetDescriptor<O, T, V, C>): TraitViewControllerSetFactory<TraitViewControllerSet<any, T, V, C>> { let superClass = descriptor.extends as TraitViewControllerSetFactory | null | undefined; const affinity = descriptor.affinity; const inherits = descriptor.inherits; const sorted = descriptor.sorted; delete descriptor.extends; delete descriptor.implements; delete descriptor.affinity; delete descriptor.inherits; delete descriptor.sorted; if (superClass === void 0 || superClass === null) { superClass = this; } const fastenerClass = superClass.extend(className, descriptor); fastenerClass.construct = function (fastenerClass: {prototype: TraitViewControllerSet<any, any, any, any>}, fastener: TraitViewControllerSet<O, T, V, C> | null, owner: O): TraitViewControllerSet<O, T, V, C> { fastener = superClass!.construct(fastenerClass, fastener, owner); if (affinity !== void 0) { fastener.initAffinity(affinity); } if (inherits !== void 0) { fastener.initInherits(inherits); } if (sorted !== void 0) { fastener.initSorted(sorted); } return fastener; }; return fastenerClass; }; return TraitViewControllerSet; })(ControllerSet);
the_stack
import React, { FC, useEffect, useMemo, useRef, useState } from 'react' import { useRouter } from 'next/router' import NextLink from 'next/link' import { BLOCKS } from '@contentful/rich-text-types' import slugify from '@sindresorhus/slugify' import { Slice as SliceType, ProcessEntry, richText, } from '@island.is/island-ui/contentful' import { Box, Text, Stack, Breadcrumbs, GridColumn, GridRow, Link, Navigation, TableOfContents, Button, Tag, LinkContext, } from '@island.is/island-ui/core' import { HeadWithSocialSharing, InstitutionPanel, InstitutionsPanel, OrganizationFooter, OrganizationChatPanel, Sticky, Webreader, AppendedArticleComponents, } from '@island.is/web/components' import { withMainLayout } from '@island.is/web/layouts/main' import { GET_ARTICLE_QUERY, GET_NAMESPACE_QUERY } from './queries' import { Screen } from '@island.is/web/types' import { useNamespace } from '@island.is/web/hooks' import { useI18n } from '@island.is/web/i18n' import { CustomNextError } from '@island.is/web/units/errors' import { QueryGetNamespaceArgs, GetNamespaceQuery, AllSlicesFragment as Slice, GetSingleArticleQuery, QueryGetSingleArticleArgs, Organization, } from '@island.is/web/graphql/schema' import { createNavigation } from '@island.is/web/utils/navigation' import useContentfulId from '@island.is/web/hooks/useContentfulId' import { SidebarLayout } from './Layouts/SidebarLayout' import { createPortal } from 'react-dom' import { LinkResolverResponse, LinkType, useLinkResolver, } from '../hooks/useLinkResolver' import { Locale } from '@island.is/shared/types' import { useScrollPosition } from '../hooks/useScrollPosition' import { scrollTo } from '../hooks/useScrollSpy' type Article = GetSingleArticleQuery['getSingleArticle'] type SubArticle = GetSingleArticleQuery['getSingleArticle']['subArticles'][0] const createSubArticleNavigation = (body: Slice[]) => { // on sub-article page the main article title is h1, sub-article title is h2 // and navigation is generated from h3 const navigation = createNavigation(body, { htmlTags: [BLOCKS.HEADING_3], }) // we'll hide sub-article navigation if it's only one item return navigation.length > 1 ? navigation : [] } const createArticleNavigation = ( article: Article, selectedSubArticle: SubArticle, linkResolver: ( linkType: LinkType, slugs?: string[], locale?: Locale, ) => LinkResolverResponse, ): Array<{ url: string; title: string }> => { if (article.subArticles.length === 0) { return createNavigation(article.body, { title: article.shortTitle || article.title, }).map(({ id, text }) => ({ title: text, url: article.slug + '#' + id, })) } let nav = [] nav.push({ title: article.title, url: linkResolver('article', [article.slug]).href, }) for (const subArticle of article.subArticles) { nav.push({ title: subArticle.title, url: linkResolver('article', subArticle.slug.split('/')).href, }) // expand sub-article navigation for selected sub-article // TODO: we need to style these differently in the mobile drawer if (subArticle === selectedSubArticle) { nav = nav.concat( createSubArticleNavigation(subArticle.body).map(({ id, text }) => ({ title: text, url: article.slug + '#' + id, })), ) } } return nav } const RelatedContent: FC<{ title: string articles: Array<{ title: string; slug: string }> otherContent: Array<{ text: string; url: string }> }> = ({ title, articles, otherContent }) => { const { linkResolver } = useLinkResolver() if (articles.length < 1 && otherContent.length < 1) return null const relatedLinks = (articles ?? []) .map((article) => ({ title: article.title, url: linkResolver('article', [article.slug]).href, })) .concat( (otherContent ?? []).map((article) => ({ title: article.text, url: article.url, })), ) return ( <Box background="purple100" borderRadius="large" padding={[3, 3, 4]}> <Stack space={[1, 1, 2]}> <Text variant="eyebrow" as="h2"> {title} </Text> {relatedLinks.map((link) => ( <Link key={link.url} href={link.url} underline="normal"> <Text key={link.url} as="span"> {link.title} </Text> </Link> ))} </Stack> </Box> ) } const TOC: FC<{ body: SubArticle['body'] title: string }> = ({ body, title }) => { const navigation = useMemo(() => { return createSubArticleNavigation(body ?? []) }, [body]) if (navigation.length === 0) { return null } return ( <Box marginTop={3}> <TableOfContents tableOfContentsTitle={title} headings={navigation.map(({ id, text }) => ({ headingTitle: text, headingId: id, }))} onClick={(id) => scrollTo(id, { smooth: true })} /> </Box> ) } const ArticleNavigation: FC< ArticleSidebarProps & { isMenuDialog?: boolean } > = ({ article, activeSlug, n, isMenuDialog }) => { const { linkResolver } = useLinkResolver() return ( article.subArticles.length > 0 && ( <Navigation baseId="articleNav" title={n('sidebarHeader')} activeItemTitle={ !activeSlug ? article.shortTitle || article.title : article.subArticles.find( (sub) => activeSlug === sub.slug.split('/').pop(), ).title } isMenuDialog={isMenuDialog} renderLink={(link, { typename, slug }) => { return ( <NextLink {...linkResolver(typename as LinkType, slug)} passHref> {link} </NextLink> ) }} items={[ { title: article.shortTitle || article.title, typename: article.__typename, slug: [article.slug], active: !activeSlug, }, ...article.subArticles.map((item) => ({ title: item.title, typename: item.__typename, slug: item.slug.split('/'), active: activeSlug === item.slug.split('/').pop(), })), ]} /> ) ) } interface ArticleSidebarProps { article: Article activeSlug?: string | string[] n: (s: string) => string } const ArticleSidebar: FC<ArticleSidebarProps> = ({ article, activeSlug, n, }) => { const { linkResolver } = useLinkResolver() const { activeLocale } = useI18n() return ( <Stack space={3}> {!!article.category && ( <Box display={['none', 'none', 'block']} printHidden> <Link {...linkResolver('articlecategory', [article.category.slug])}> <Button preTextIcon="arrowBack" preTextIconType="filled" size="small" type="button" variant="text" > {article.category.title} </Button> </Link> </Box> )} {article.organization.length > 0 && ( <InstitutionPanel img={article.organization[0].logo?.url} institutionTitle={n('organization')} institution={article.organization[0].title} locale={activeLocale} linkProps={{ href: article.organization[0].link }} imgContainerDisplay={['block', 'block', 'none', 'block']} /> )} {article.subArticles.length > 0 && ( <ArticleNavigation article={article} activeSlug={activeSlug} n={n} /> )} <RelatedContent title={n('relatedMaterial')} articles={article.relatedArticles} otherContent={article.relatedContent} /> </Stack> ) } export interface ArticleProps { article: Article namespace: GetNamespaceQuery['getNamespace'] } const ArticleScreen: Screen<ArticleProps> = ({ article, namespace }) => { const { activeLocale } = useI18n() const portalRef = useRef() const processEntryRef = useRef(null) const [mounted, setMounted] = useState(false) const [isVisible, setIsVisible] = useState(true) useEffect(() => { portalRef.current = document.querySelector('#__next') processEntryRef.current = document.querySelector('#processRef') setMounted(true) }, []) useContentfulId(article.id) const n = useNamespace(namespace) const { query } = useRouter() const { linkResolver } = useLinkResolver() useScrollPosition( ({ currPos }) => { let px = -600 if (typeof window !== `undefined`) { px = window.innerHeight * -1 } const elementPosition = processEntryRef && processEntryRef.current ? processEntryRef?.current.getBoundingClientRect().bottom + (px - currPos.y) : 0 const canShow = elementPosition + currPos.y >= 0 setIsVisible(canShow) }, [setIsVisible], null, false, 150, ) const subArticle = article.subArticles.find((sub) => { return sub.slug.split('/').pop() === query.subSlug }) const contentOverviewOptions = useMemo(() => { return createArticleNavigation(article, subArticle, linkResolver) }, [article, subArticle, linkResolver]) const relatedLinks = (article.relatedArticles ?? []).map((article) => ({ title: article.title, url: linkResolver('article', [article.slug]).href, })) const combinedMobileNavigation = [ { title: n('categoryOverview', 'Efnisyfirlit'), items: contentOverviewOptions, }, ] if (relatedLinks.length) { combinedMobileNavigation.push({ title: n('relatedMaterial'), items: relatedLinks, }) } const metaTitle = `${article.title} | Ísland.is` const processEntry = article.processEntry const categoryHref = linkResolver('articlecategory', [article.category.slug]) .href const organizationTitle = article.organization[0]?.title const organizationShortTitle = article.organization[0]?.shortTitle return ( <> <HeadWithSocialSharing title={metaTitle} description={article.intro} imageUrl={article.featuredImage?.url} imageWidth={article.featuredImage?.width.toString()} imageHeight={article.featuredImage?.height.toString()} /> <SidebarLayout isSticky={false} sidebarContent={ <Sticky> <ArticleSidebar article={article} n={n} activeSlug={query.subSlug} /> </Sticky> } > <Box paddingBottom={[2, 2, 4]} display={['none', 'none', 'block']} printHidden > <Breadcrumbs items={[ { title: 'Ísland.is', typename: 'homepage', href: '/', }, !!article.category && { title: article.category.title, typename: 'articlecategory', slug: [article.category.slug], }, !!article.group && { isTag: true, title: article.group.title, typename: 'articlecategory', slug: [ article.category.slug + (article.group?.slug ? `#${article.group.slug}` : ''), ], }, ]} renderLink={(link, { typename, slug }) => { return ( <NextLink {...linkResolver(typename as LinkType, slug)} passHref > {link} </NextLink> ) }} /> </Box> <Box paddingBottom={[2, 2, 4]} display={['flex', 'flex', 'none']} justifyContent="spaceBetween" alignItems="center" printHidden > {!!article.category && ( <Box flexGrow={1} marginRight={6} overflow={'hidden'}> <LinkContext.Provider value={{ linkRenderer: (href, children) => ( <Link href={href} pureChildren skipTab> {children} </Link> ), }} > <Text truncate> <a href={categoryHref}> <Button preTextIcon="arrowBack" preTextIconType="filled" size="small" type="button" variant="text" > {article.category.title} </Button> </a> </Text> </LinkContext.Provider> </Box> )} {article.organization.length > 0 && ( <Box minWidth={0}> {article.organization[0].link ? ( <Link href={article.organization[0].link} skipTab> <Tag variant="purple" truncate> {organizationShortTitle || organizationTitle} </Tag> </Link> ) : ( <Tag variant="purple" truncate disabled> {organizationShortTitle || organizationTitle} </Tag> )} </Box> )} </Box> <Box> <Text variant="h1" as="h1"> <span id={slugify(article.title)} className="rs_read"> {article.title} </span> </Text> <Webreader readId={null} readClass="rs_read" /> <Box marginTop={3} display={['block', 'block', 'none']} printHidden> <ArticleNavigation article={article} n={n} activeSlug={query.subSlug} isMenuDialog /> </Box> {!!processEntry && ( <Box marginTop={3} display={['none', 'none', 'block']} printHidden className="rs_read" > <ProcessEntry {...processEntry} /> </Box> )} {(subArticle ? subArticle.showTableOfContents : article.showTableOfContents) && ( <GridRow> <GridColumn span={[null, '4/7', '5/7', '4/7', '3/7']}> <TOC title={n('tableOfContentTitle')} body={subArticle ? subArticle.body : article.body} /> </GridColumn> </GridRow> )} {subArticle && ( <Text variant="h2" as="h2" paddingTop={7}> <span id={slugify(subArticle.title)} className="rs_read"> {subArticle.title} </span> </Text> )} </Box> <Box paddingTop={subArticle ? 2 : 4}> <Box className="rs_read"> {richText( (subArticle ?? article).body as SliceType[], undefined, activeLocale, )} <AppendedArticleComponents article={article} /> </Box> <Box id="processRef" display={['block', 'block', 'none']} marginTop={7} printHidden > {!!processEntry && <ProcessEntry {...processEntry} />} </Box> {article.organization.length > 0 && ( <Box marginTop={[3, 3, 3, 10, 20]} marginBottom={[3, 3, 3, 10, 20]} printHidden > <InstitutionsPanel img={article.organization[0].logo?.url ?? ''} institution={{ title: article.organization[0].title, label: n('organization'), href: article.organization[0].link, }} responsibleParty={article.responsibleParty.map( (responsibleParty) => ({ title: responsibleParty.title, label: n('responsibleParty'), href: responsibleParty.link, }), )} relatedInstitution={article.relatedOrganization.map( (relatedOrganization) => ({ title: relatedOrganization.title, label: n('relatedOrganization'), href: relatedOrganization.link, }), )} locale={activeLocale} contactText="Hafa samband" /> </Box> )} <Box display={['block', 'block', 'none']} printHidden> {article.relatedArticles.length > 0 && ( <RelatedContent title={n('relatedMaterial')} articles={article.relatedArticles} otherContent={article.relatedContent} /> )} </Box> </Box> {!!processEntry && mounted && isVisible && createPortal( <Box marginTop={5} display={['block', 'block', 'none']} printHidden> <ProcessEntry fixed {...processEntry} /> </Box>, portalRef.current, )} </SidebarLayout> <OrganizationChatPanel slugs={article.organization.map((x) => x.slug)} pushUp={isVisible} /> <OrganizationFooter organizations={article.organization as Organization[]} /> </> ) } ArticleScreen.getInitialProps = async ({ apolloClient, query, locale }) => { const slug = query.slug as string const [article, namespace] = await Promise.all([ apolloClient .query<GetSingleArticleQuery, QueryGetSingleArticleArgs>({ query: GET_ARTICLE_QUERY, variables: { input: { slug, lang: locale as string, }, }, }) .then((response) => response.data.getSingleArticle), apolloClient .query<GetNamespaceQuery, QueryGetNamespaceArgs>({ query: GET_NAMESPACE_QUERY, variables: { input: { namespace: 'Articles', lang: locale, }, }, }) .then((content) => { // map data here to reduce data processing in component return JSON.parse(content.data.getNamespace.fields) }), ]) // we assume 404 if no article/sub-article is found const subArticle = article?.subArticles.find( (a) => a.slug.split('/').pop() === query.subSlug, ) if (!article || (query.subSlug && !subArticle)) { throw new CustomNextError(404, 'Article not found') } return { article, namespace, } } export default withMainLayout(ArticleScreen)
the_stack
import Options from '../interfaces/ads/options'; import Source from '../interfaces/source'; import Media from '../media'; import Player from '../player'; import { EVENT_OPTIONS, IS_ANDROID, IS_IOS, IS_IPHONE } from '../utils/constants'; import { addEvent } from '../utils/events'; import { isVideo, isXml, loadScript, removeElement } from '../utils/general'; declare const google: any; /** * Ads Media. * * @description This class implements Google IMA SDK v3.0 to display VAST and VPAID advertisements * @see https://developers.google.com/interactive-media-ads/ * @class Ads */ class Ads { /** * Flag to indicate when player has finished playing all Ads. * * Type of Ads could be: pre-roll, mid-roll, post-roll or combination of them. * @type boolean * @memberof Ads */ #adsEnded = false; /** * Flag to indicate that individual Ad has been played. * * @type boolean * @memberof Ads */ #adsDone = false; /** * Flag to indicate that current Ad is being played. * * @type boolean * @memberof Ads */ #adsActive = false; /** * Flag to indicate that Ads are ready to being played. * * @type boolean * @memberof Ads */ #adsStarted = false; /** * Element to present changes in current time while Ad is being played. * * @type number * @memberof Ads */ #intervalTimer = 0; /** * Store the current Ad's volume level. * * @type number * @memberof Ads */ #adsVolume: number; /** * Flag to indicate if Ad is currently muted or not. * * @type boolean * @memberof Ads */ #adsMuted = false; /** * Store the current Ad's duration. * * @type number * @memberof Ads */ #adsDuration = 0; /** * Store the current Ad's current time position to be passed in the `timeupdate` event. * * @type number * @memberof Ads */ #adsCurrentTime = 0; /** * Object which handles playing ads after they've been received from the server. * * @see https://tinyurl.com/ybjas4ut * @type google.ima.AdsManager * @memberof Ads */ #adsManager: any = null; /** * Instance of OpenPlayer. * * @private * @type Player * @memberof Captions */ #player: Player; /** * Instance of Media object to execute actions once Ad has ended/skipped. * * @type Media * @memberof Ads */ #media: Media; /** * Native video/audio tag to execute native events. * * @type HTMLMediaElement * @memberof Ads */ #element: HTMLMediaElement; /** * List of IMA SDK events to be executed. * * @type string[] * @memberof Ads */ #events: string[] = []; /** * The VAST/VPAID URL to play Ads. * * @type string|string[] * @memberof Ads */ #ads: string | string[]; /** * Promise to start all IMA SDK elements, once the library has been loaded. * * @type Promise<any> * @memberof Ads */ #promise: Promise<any>; /** * Object which allows to request ads from ad servers or a dynamic ad insertion stream. * * @see https://tinyurl.com/ycwp4ufd * @type google.ima.AdsLoader * @memberof Ads */ #adsLoader: any; /** * Element in which Ads will be created. * * @type HTMLDivElement * @memberof Ads */ #adsContainer?: HTMLDivElement; /** * Element in which Ads will render a custom click handler to track clicks. * This overrides the default `Learn More` button from IMA SDK * * @type HTMLDivElement * @memberof Ads */ #adsCustomClickContainer?: HTMLDivElement; /** * Container to display Ads. * * @see https://tinyurl.com/ya3zksso * @type google.ima.adDisplayContainer * @memberof Ads */ #adDisplayContainer: any; /** * Object containing the data used to request ads from the server. * * @see https://tinyurl.com/ya8bxjf4 * @type google.ima.adsRequest * @memberof Ads */ #adsRequest: any; /** * Flag to indicate if Ad should be played automatically with sound * * @type boolean * @memberof Ads */ #autoStart = false; /** * Flag to indicate if Ad should be played automatically without sound * * @private * @type {boolean} * @memberof Ads */ #autoStartMuted = false; /** * Flag to indicate if player requested play. * * This will help if the play was triggered before Ads were ready. * @private * @type boolean * @memberof Ads */ #playTriggered = false; /** * Configuration elements passed to Ads, including IMA SDK location * * @private * @type Options * @memberof Ads */ #adsOptions: Options; /** * Current Ad; used when passing a list of Ads * * @private * @type number * @memberof Ads */ #currentAdsIndex = 0; /** * Store original volume from media. * * @private * @type number * @memberof Ads */ #originalVolume: number; /** * * * @private * @type {*} * @memberof Ads */ #preloadContent: any; /** * Timer to update media's `currentTime` * * @private * @type number * @memberof Ads */ #lastTimePaused = 0; /** * List of media sources from the `media` element. * * @private * @type Source[] * @memberof Ads */ #mediaSources: Source[] = []; /** * Flag to execute `loadedmetadata` and `resize` once. * * @private * @type boolean * @memberof Ads */ #mediaStarted = false; loadPromise: unknown; loadedAd = false; /** * Create an instance of Ads. * * @param {Player} player * @param {string|string[]} ads * @param {any} labels * @param {boolean} autoStart * @param {Options} options * @returns {Ads} * @memberof Ads */ constructor(player: Player, ads: string | string[], autoStart?: boolean, autoStartMuted?: boolean, options?: Options) { const defaultOpts: Options = { autoPlayAdBreaks: true, customClick: { enabled: false, label: 'Click here for more info', }, debug: false, enablePreloading: false, language: 'en', loop: false, numRedirects: 4, publisherId: null, sdkPath: 'https://imasdk.googleapis.com/js/sdkloader/ima3.js', sessionId: null, src: [], vpaidMode: 'enabled', }; this.#player = player; this.#ads = ads; this.#media = player.getMedia(); this.#element = player.getElement(); this.#autoStart = autoStart || false; this.#adsMuted = player.getElement().muted; this.#autoStartMuted = autoStartMuted || false; this.#adsOptions = { ...defaultOpts, ...options }; if (options) { const objectElements = ['customClick']; objectElements.forEach(item => { this.#adsOptions[item] = options[item] && Object.keys(options[item]).length ? { ...defaultOpts[item], ...options[item] } : defaultOpts[item]; }); } this.#playTriggered = false; this.#originalVolume = this.#element.volume; this.#adsVolume = this.#originalVolume; const path = this.#adsOptions.debug && this.#adsOptions.sdkPath ? this.#adsOptions.sdkPath.replace(/(\.js$)/, '_debug.js') : this.#adsOptions.sdkPath; this._handleClickInContainer = this._handleClickInContainer.bind(this); this.load = this.load.bind(this); this._loaded = this._loaded.bind(this); this._error = this._error.bind(this); this._assign = this._assign.bind(this); this._contentLoadedAction = this._contentLoadedAction.bind(this); this._loadedMetadataHandler = this._loadedMetadataHandler.bind(this); this._contentEndedListener = this._contentEndedListener.bind(this); this.resizeAds = this.resizeAds.bind(this); this._handleResizeAds = this._handleResizeAds.bind(this); this._onContentPauseRequested = this._onContentPauseRequested.bind(this); this._onContentResumeRequested = this._onContentResumeRequested.bind(this); this.#promise = path && (typeof google === 'undefined' || typeof google.ima === 'undefined') ? loadScript(path) : new Promise(resolve => { resolve({}); }); this.#promise.then(() => { this.load(); }).catch(error => { let message = 'Ad script could not be loaded; please check if you have an AdBlock '; message += 'turned on, or if you provided a valid URL is correct'; console.error(`Ad error: ${message}.`); const details = { detail: { data: error, message, type: 'Ads', }, }; const errorEvent = addEvent('playererror', details); this.#element.dispatchEvent(errorEvent); }); return this; } /** * Create the Ads container and loader to process the Ads URL provided. * * @param {bool} force * @memberof Ads */ public load(force = false): void { if (typeof google === 'undefined' || !google.ima || (!force && this.loadedAd && this.#adsOptions.autoPlayAdBreaks)) { return; } /** * If we have set `autoPlayAdBreaks` to false and haven't set the * force flag, don't load ads yet */ if (!this.#adsOptions.autoPlayAdBreaks && !force) { return; } this.loadedAd = true; /** * Check for an existing ad container div and destroy it to avoid * clickable areas of subsequent ads being blocked by old DIVs */ const existingContainer = this.#player.getContainer().querySelector('.op-ads'); if (existingContainer && existingContainer.parentNode) { existingContainer.parentNode.removeChild(existingContainer); } this.#adsStarted = true; this.#adsContainer = document.createElement('div'); this.#adsContainer.className = 'op-ads'; this.#adsContainer.tabIndex = -1; if (this.#element.parentElement) { this.#element.parentElement.insertBefore(this.#adsContainer, this.#element.nextSibling); } this.#adsContainer.addEventListener('click', this._handleClickInContainer); if (this.#adsOptions.customClick.enabled) { this.#adsCustomClickContainer = document.createElement('div'); this.#adsCustomClickContainer.className = 'op-ads__click-container'; this.#adsCustomClickContainer.innerHTML = `<div class="op-ads__click-label">${this.#adsOptions.customClick.label}</div>`; if (this.#element.parentElement) { this.#element.parentElement.insertBefore(this.#adsCustomClickContainer, this.#element.nextSibling); } } this.#mediaSources = this.#media.src; const vpaidModeMap: Record<string, unknown> = { disabled: google.ima.ImaSdkSettings.VpaidMode.DISABLED, enabled: google.ima.ImaSdkSettings.VpaidMode.ENABLED, insecure: google.ima.ImaSdkSettings.VpaidMode.INSECURE, }; google.ima.settings.setVpaidMode(vpaidModeMap[this.#adsOptions.vpaidMode]); google.ima.settings.setDisableCustomPlaybackForIOS10Plus(true); google.ima.settings.setAutoPlayAdBreaks(this.#adsOptions.autoPlayAdBreaks); google.ima.settings.setNumRedirects(this.#adsOptions.numRedirects); google.ima.settings.setLocale(this.#adsOptions.language); if (this.#adsOptions.sessionId) { google.ima.settings.setSessionId(this.#adsOptions.sessionId); } if (this.#adsOptions.publisherId) { google.ima.settings.setPpid(this.#adsOptions.publisherId); } google.ima.settings.setPlayerType('openplayerjs'); google.ima.settings.setPlayerVersion('2.9.3'); this.#adDisplayContainer = new google.ima.AdDisplayContainer(this.#adsContainer, this.#element, this.#adsCustomClickContainer); this.#adsLoader = new google.ima.AdsLoader(this.#adDisplayContainer); this.#adsLoader.addEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, this._loaded, EVENT_OPTIONS); this.#adsLoader.addEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, this._error, EVENT_OPTIONS); // Create responsive ad if (typeof window !== 'undefined') { window.addEventListener('resize', this._handleResizeAds, EVENT_OPTIONS); } this.#element.addEventListener('loadedmetadata', this._handleResizeAds, EVENT_OPTIONS); // Request Ads automatically if `autoplay` was set if ( this.#autoStart === true || this.#autoStartMuted === true || force === true || this.#adsOptions.enablePreloading === true || this.#playTriggered === true ) { if (!this.#adsDone) { this.#adsDone = true; this.#adDisplayContainer.initialize(); } this._requestAds(); } } /** * Start playing/resume Ad if `adsManager` is active. * * @memberof Ads */ public async play(): Promise<void> { if (!this.#adsDone) { this.#playTriggered = true; this._initNotDoneAds(); return; } if (this.#adsManager) { try { // No timer interval and no adsActive mean it's a potential initial ad play if (!this.#intervalTimer && this.#adsActive === false) { this.#adsManager.start(); } else { this.#adsManager.resume(); } this.#adsActive = true; const e = addEvent('play'); this.#element.dispatchEvent(e); } catch (err) { this._resumeMedia(); } } } /** * Pause Ad if `adsManager` is active. * * @memberof Ads */ public pause(): void { if (this.#adsManager) { this.#adsActive = false; this.#adsManager.pause(); const e = addEvent('pause'); this.#element.dispatchEvent(e); } } /** * Execute any callbacks to destroy Ads. * * @memberof Ads */ public destroy(): void { if (this.#adsManager) { this.#adsManager.removeEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, this._error); if (this.#events) { this.#events.forEach(event => { this.#adsManager.removeEventListener(event, this._assign); }); } } this.#events = []; const controls = this.#player.getControls(); const mouseEvents = controls ? controls.events.mouse : {}; Object.keys(mouseEvents).forEach((event: string) => { if (this.#adsContainer) { this.#adsContainer.removeEventListener(event, mouseEvents[event]); } }); if (this.#adsLoader) { this.#adsLoader.removeEventListener(google.ima.AdErrorEvent.Type.AD_ERROR, this._error); this.#adsLoader.removeEventListener(google.ima.AdsManagerLoadedEvent.Type.ADS_MANAGER_LOADED, this._loaded); } const destroy = !Array.isArray(this.#ads) || this.#currentAdsIndex > this.#ads.length; if (this.#adsManager && destroy) { this.#adsManager.destroy(); } if (this.#adsOptions.customClick.enabled) { removeElement(this.#adsCustomClickContainer); } if (IS_IOS || IS_ANDROID) { this.#element.removeEventListener('loadedmetadata', this._contentLoadedAction); } this.#element.removeEventListener('loadedmetadata', this._handleResizeAds); this.#element.removeEventListener('loadedmetadata', this._loadedMetadataHandler); this.#element.removeEventListener('ended', this._contentEndedListener); if (typeof window !== 'undefined') { window.removeEventListener('resize', this._handleResizeAds); } if (this.#adsContainer) { this.#adsContainer.removeEventListener('click', this._handleClickInContainer); } removeElement(this.#adsContainer); this.loadPromise = null; this.loadedAd = false; this.#adsDone = false; this.#playTriggered = false; this.#adsDuration = 0; this.#adsCurrentTime = 0; } /** * Change dimensions of Ad. * * @param {?number} width * @param {?number} height * @memberof Ads */ public resizeAds(width?: number, height?: number): void { if (this.#adsManager) { const target = this.#element; const mode = target.getAttribute('data-fullscreen') === 'true' ? google.ima.ViewMode.FULLSCREEN : google.ima.ViewMode.NORMAL; let formattedWidth = width; const percentageWidth = width ? width.toString() : ''; if (width && percentageWidth.indexOf('%') > -1) { if (this.#element.parentElement) { formattedWidth = this.#element.parentElement.offsetWidth * (parseInt(percentageWidth, 10) / 100); } } let formattedHeight = height; const percentageHeight = height ? height.toString() : ''; if (height && percentageHeight.indexOf('%') > -1) { if (this.#element.parentElement) { formattedHeight = this.#element.parentElement.offsetHeight * (parseInt(percentageHeight, 10) / 100); } } let timeout; if (timeout && typeof window !== 'undefined') { window.cancelAnimationFrame(timeout); } if (typeof window !== 'undefined') { timeout = window.requestAnimationFrame(() => { this.#adsManager.resize(formattedWidth || target.offsetWidth, formattedHeight || target.offsetHeight, mode); }); } } } /** * Obtain an instance of the IMA adsManager. * * @returns {google.ima.AdsManager} * @memberof Ads */ public getAdsManager(): any { return this.#adsManager; } /** * Flag if the ad has started or not. * * @returns {boolean} * @memberof Ads */ public started(): boolean { return this.#adsStarted; } set src(source: string | string[]) { this.#ads = source; } set isDone(value: boolean) { this.#adsDone = value; } /** * Update the `playTriggered` flag * * @param {boolean} value * @memberof Ads */ set playRequested(value: boolean) { this.#playTriggered = value; } /** * Set the current Ad's volume level. * * @memberof Ads */ set volume(value: number) { if (this.#adsManager) { this.#adsVolume = value; this.#adsManager.setVolume(value); this._setMediaVolume(value); this.#adsMuted = value === 0; } } /** * Retrieve current Ad's volume level. * * @returns {number} * @memberof Ads */ get volume(): number { return this.#adsManager ? this.#adsManager.getVolume() : this.#originalVolume; } /** * Set the current Ad's muted status. * * @memberof Ads */ set muted(value: boolean) { if (this.#adsManager) { if (value) { this.#adsManager.setVolume(0); this.#adsMuted = true; this._setMediaVolume(0); } else { this.#adsManager.setVolume(this.#adsVolume); this.#adsMuted = false; this._setMediaVolume(this.#adsVolume); } } } /** * Retrieve the current Ad's muted status. * * @returns {boolean} * @memberof Ads */ get muted(): boolean { return this.#adsMuted; } /** * Set the current Ad's current time position. * * @memberof Ads */ set currentTime(value: number) { this.#adsCurrentTime = value; } /** * Retrieve the current Ad's current time position. * * @returns {number} * @memberof Ads */ get currentTime(): number { return this.#adsCurrentTime; } /** * Retrieve the current Ad's duration. * * @returns {number} * @memberof Ads */ get duration(): number { return this.#adsDuration; } /** * Retrieve the current Ad's paused status. * * @returns {boolean} * @memberof Ads */ get paused(): boolean { return !this.#adsActive; } /** * Retrieve the current Ad's ended status. * * @returns {boolean} * @memberof Ads */ get ended(): boolean { return this.#adsEnded; } /** * Dispatch IMA SDK's events via OpenPlayer. * * @param {any} event * @memberof Ads */ private _assign(event: any): void { const ad = event.getAd(); switch (event.type) { case google.ima.AdEvent.Type.LOADED: if (!ad.isLinear()) { this._onContentResumeRequested(); } else { if (IS_IPHONE && isVideo(this.#element)) { this.#element.controls = false; } this.#adsDuration = ad.getDuration(); this.#adsCurrentTime = ad.getDuration(); if (!this.#mediaStarted && !IS_IOS && !IS_ANDROID) { const waitingEvent = addEvent('waiting'); this.#element.dispatchEvent(waitingEvent); const loadedEvent = addEvent('loadedmetadata'); this.#element.dispatchEvent(loadedEvent); this.resizeAds(); } } break; case google.ima.AdEvent.Type.STARTED: if (ad.isLinear()) { if (this.#element.parentElement && !this.#element.parentElement.classList.contains('op-ads--active')) { this.#element.parentElement.classList.add('op-ads--active'); } if (!this.#media.paused) { this.#media.pause(); } this.#adsActive = true; const playEvent = addEvent('play'); this.#element.dispatchEvent(playEvent); let resized; if (!resized) { this.resizeAds(); resized = true; } if (this.#media.ended) { this.#adsEnded = false; const endEvent = addEvent('adsmediaended'); this.#element.dispatchEvent(endEvent); } if (typeof window !== 'undefined') { this.#intervalTimer = window.setInterval(() => { if (this.#adsActive === true) { this.#adsCurrentTime = Math.round(this.#adsManager.getRemainingTime()); const timeEvent = addEvent('timeupdate'); this.#element.dispatchEvent(timeEvent); } }, 350); } } break; case google.ima.AdEvent.Type.COMPLETE: case google.ima.AdEvent.Type.SKIPPED: if (ad.isLinear()) { if (event.type === google.ima.AdEvent.Type.SKIPPED) { const skipEvent = addEvent('adsskipped'); this.#element.dispatchEvent(skipEvent); } if (this.#element.parentElement) { this.#element.parentElement.classList.remove('op-ads--active'); } this.#adsActive = false; clearInterval(this.#intervalTimer); } break; case google.ima.AdEvent.Type.VOLUME_CHANGED: this._setMediaVolume(this.volume); break; case google.ima.AdEvent.Type.VOLUME_MUTED: if (ad.isLinear()) { const volumeEvent = addEvent('volumechange'); this.#element.dispatchEvent(volumeEvent); } break; case google.ima.AdEvent.Type.ALL_ADS_COMPLETED: if (ad.isLinear()) { this.#adsActive = false; this.#adsEnded = true; this.#intervalTimer = 0; this.#adsMuted = false; this.#adsStarted = false; if (this.#element.parentElement) { this.#element.parentElement.classList.remove('op-ads--active'); } this.destroy(); if (this.#element.currentTime >= this.#element.duration) { const endedEvent = addEvent('ended'); this.#element.dispatchEvent(endedEvent); } } break; case google.ima.AdEvent.Type.CLICK: const pauseEvent = addEvent('pause'); this.#element.dispatchEvent(pauseEvent); break; case google.ima.AdEvent.Type.AD_BREAK_READY: if (!this.#adsOptions.autoPlayAdBreaks) { this.play(); } break; default: break; } // Assign events prefixed with `ads` to main element so user // can listen to these events, except if the system detects a non-fatal error if (event.type === google.ima.AdEvent.Type.LOG) { const adData = event.getAdData(); if (adData.adError) { const message = adData.adError.getMessage(); console.warn(`Ad warning: Non-fatal error occurred: ${message}`); const details = { detail: { data: adData.adError, message, type: 'Ads', }, }; const errorEvent = addEvent('playererror', details); this.#element.dispatchEvent(errorEvent); } } else { const e = addEvent(`ads${event.type}`); this.#element.dispatchEvent(e); } } /** * Dispatch an IMA SDK error that will destroy the Ads instance and resume original media. * * If more than one URL for Ads was found, attempt to play it. * * @see https://developers.google.com/interactive-media-ads/docs/sdks/html5/v3/apis#ima.AdError.ErrorCode * @param {any} event * @memberof Ads */ private _error(event: any): void { const error = event.getError(); const details = { detail: { data: error, message: error.toString(), type: 'Ads', }, }; const errorEvent = addEvent('playererror', details); this.#element.dispatchEvent(errorEvent); // @see https://support.google.com/admanager/answer/4442429?hl=en const fatalErrorCodes = [ 100, 101, 102, 300, 301, 302, 303, 400, 401, 402, 403, 405, 406, 407, 408, 409, 410, 500, 501, 502, 503, 900, 901, 1005, ]; if (Array.isArray(this.#ads) && this.#ads.length > 1 && this.#currentAdsIndex < this.#ads.length - 1) { this.#currentAdsIndex++; this.destroy(); this.#adsStarted = true; this.#playTriggered = true; this.load(true); console.warn(`Ad warning: ${error.toString()}`); } else { // Unless there's a fatal error, do not destroy the Ads manager if (fatalErrorCodes.indexOf(error.getErrorCode()) > -1) { if (this.#adsManager) { this.#adsManager.destroy(); } console.error(`Ad error: ${error.toString()}`); } else { console.warn(`Ad warning: ${error.toString()}`); } if (this.#autoStart === true || this.#autoStartMuted === true || this.#adsStarted === true) { this.#adsActive = false; // Sometimes, due to pre-fetch issues, Ads could report an error, but the SDK is able to // play Ads, so check if src was set to determine what action to take this._resumeMedia(); } } } /** * Callback to be executed once IMA SDK manager is loaded. * * @param {any} adsManagerLoadedEvent * @memberof Ads */ private _loaded(adsManagerLoadedEvent: any): void { const adsRenderingSettings = new google.ima.AdsRenderingSettings(); adsRenderingSettings.restoreCustomPlaybackStateOnAdBreakComplete = false; adsRenderingSettings.enablePreloading = this.#adsOptions.enablePreloading; // Get the ads manager. this.#adsManager = adsManagerLoadedEvent.getAdsManager(this.#element, adsRenderingSettings); this._start(this.#adsManager); this.loadPromise = new Promise(resolve => resolve); } /** * Callback to be executed to start playing Ad. * * @param {any} manager * @memberof Ads */ private _start(manager: any): void { if (this.#adsCustomClickContainer && manager.isCustomClickTrackingUsed()) { this.#adsCustomClickContainer.classList.add('op-ads__click-container--visible'); } // Add listeners to the required events. manager.addEventListener(google.ima.AdEvent.Type.CONTENT_PAUSE_REQUESTED, this._onContentPauseRequested, EVENT_OPTIONS); manager.addEventListener(google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED, this._onContentResumeRequested, EVENT_OPTIONS); this.#events = [ google.ima.AdEvent.Type.ALL_ADS_COMPLETED, google.ima.AdEvent.Type.CLICK, google.ima.AdEvent.Type.VIDEO_CLICKED, google.ima.AdEvent.Type.VIDEO_ICON_CLICKED, google.ima.AdEvent.Type.AD_PROGRESS, google.ima.AdEvent.Type.AD_BUFFERING, google.ima.AdEvent.Type.IMPRESSION, google.ima.AdEvent.Type.DURATION_CHANGE, google.ima.AdEvent.Type.USER_CLOSE, google.ima.AdEvent.Type.LINEAR_CHANGED, google.ima.AdEvent.Type.SKIPPABLE_STATE_CHANGED, google.ima.AdEvent.Type.AD_METADATA, google.ima.AdEvent.Type.INTERACTION, google.ima.AdEvent.Type.COMPLETE, google.ima.AdEvent.Type.FIRST_QUARTILE, google.ima.AdEvent.Type.LOADED, google.ima.AdEvent.Type.MIDPOINT, google.ima.AdEvent.Type.PAUSED, google.ima.AdEvent.Type.RESUMED, google.ima.AdEvent.Type.USER_CLOSE, google.ima.AdEvent.Type.STARTED, google.ima.AdEvent.Type.THIRD_QUARTILE, google.ima.AdEvent.Type.SKIPPED, google.ima.AdEvent.Type.VOLUME_CHANGED, google.ima.AdEvent.Type.VOLUME_MUTED, google.ima.AdEvent.Type.LOG, ]; if (!this.#adsOptions.autoPlayAdBreaks) { // Add it to the events array so it gets removed onDestroy this.#events.push(google.ima.AdEvent.Type.AD_BREAK_READY); } const controls = this.#player.getControls(); const mouseEvents = controls ? controls.events.mouse : {}; Object.keys(mouseEvents).forEach((event: string) => { if (this.#adsContainer) { this.#adsContainer.addEventListener(event, mouseEvents[event], EVENT_OPTIONS); } }); this.#events.forEach(event => { manager.addEventListener(event, this._assign, EVENT_OPTIONS); }); if (this.#autoStart === true || this.#autoStartMuted === true || this.#playTriggered === true) { this.#playTriggered = false; if (!this.#adsDone) { this._initNotDoneAds(); return; } manager.init( this.#element.offsetWidth, this.#element.offsetHeight, this.#element.parentElement && this.#element.parentElement.getAttribute('data-fullscreen') === 'true' ? google.ima.ViewMode.FULLSCREEN : google.ima.ViewMode.NORMAL ); manager.start(); const e = addEvent('play'); this.#element.dispatchEvent(e); } else if (this.#adsOptions.enablePreloading === true) { manager.init( this.#element.offsetWidth, this.#element.offsetHeight, this.#element.parentElement && this.#element.parentElement.getAttribute('data-fullscreen') === 'true' ? google.ima.ViewMode.FULLSCREEN : google.ima.ViewMode.NORMAL ); } } /** * Resume Ads if not done * * @memberof Ads */ private _initNotDoneAds(): void { if (this.#adDisplayContainer) { this.#adsDone = true; this.#adDisplayContainer.initialize(); if (IS_IOS || IS_ANDROID) { this.#preloadContent = this._contentLoadedAction; this.#element.addEventListener('loadedmetadata', this._contentLoadedAction, EVENT_OPTIONS); this.#element.load(); } else { this._contentLoadedAction(); } } else { this.load(); this.loadedAd = false; } } /** * Callback to be executed once the Ad has ended. * * @memberof Ads */ private _contentEndedListener(): void { this.#adsEnded = true; this.#adsActive = false; this.#adsStarted = false; this.#adsLoader.contentComplete(); } /** * Callback to be executed once the Ad has been paused. * * @memberof Ads */ private _onContentPauseRequested(): void { this.#element.removeEventListener('ended', this._contentEndedListener); this.#lastTimePaused = this.#media.currentTime; if (this.#adsStarted) { this.#media.pause(); } else { this.#adsStarted = true; } const e = addEvent('play'); this.#element.dispatchEvent(e); } /** * Callback to be executed once the Ad has been resumed. * * @private * @memberof Ads */ private _onContentResumeRequested(): void { if (this.#adsOptions.loop) { if (Array.isArray(this.#ads)) { if (this.#currentAdsIndex === this.#ads.length - 1) { this.#currentAdsIndex = 0; } else { this.#currentAdsIndex++; } } this.destroy(); this.#adsLoader.contentComplete(); this.#playTriggered = true; this.#adsStarted = true; this.load(true); } else { this.#element.addEventListener('ended', this._contentEndedListener, EVENT_OPTIONS); this.#element.addEventListener('loadedmetadata', this._loadedMetadataHandler, EVENT_OPTIONS); if (IS_IOS || IS_ANDROID) { this.#media.src = this.#mediaSources; this.#media.load(); this._prepareMedia(); if (this.#element.parentElement) { this.#element.parentElement.classList.add('op-ads--active'); } } else { const event = addEvent('loadedmetadata'); this.#element.dispatchEvent(event); } } } /** * Update the current time to mimic the default Ad Playback. * * @private * @memberof Ads */ private _loadedMetadataHandler() { if (Array.isArray(this.#ads)) { this.#currentAdsIndex++; if (this.#currentAdsIndex <= this.#ads.length - 1) { if (this.#adsManager) { this.#adsManager.destroy(); } this.#adsLoader.contentComplete(); this.#playTriggered = true; this.#adsStarted = true; this.#adsDone = false; this._requestAds(); } else { if (!this.#adsOptions.autoPlayAdBreaks) { this._resetAdsAfterManualBreak(); } this._prepareMedia(); } } else if (this.#element.seekable.length) { if (this.#element.seekable.end(0) > this.#lastTimePaused) { if (!this.#adsOptions.autoPlayAdBreaks) { this._resetAdsAfterManualBreak(); } this._prepareMedia(); } } else { setTimeout(this._loadedMetadataHandler, 100); } } /** * Callback to resume original media. * * This can happen when Ad is being skipped or has ended. * @memberof Ads */ private _resumeMedia(): void { this.#intervalTimer = 0; this.#adsMuted = false; this.#adsStarted = false; this.#adsDuration = 0; this.#adsCurrentTime = 0; if (this.#element.parentElement) { this.#element.parentElement.classList.remove('op-ads--active'); } if (this.#media.ended) { const e = addEvent('ended'); this.#element.dispatchEvent(e); } else { try { this.#media.play(); setTimeout(() => { const e = addEvent('play'); this.#element.dispatchEvent(e); }, 50); } catch (err) {} } } /** * Setup final attributes to the Ad before playing it, which include initial dimensions and capabilities * to autoplay Ad or not. * * @memberof Ads */ private _requestAds(): void { this.#adsRequest = new google.ima.AdsRequest(); const ads = Array.isArray(this.#ads) ? this.#ads[this.#currentAdsIndex] : this.#ads; if (isXml(ads)) { this.#adsRequest.adsResponse = ads; } else { this.#adsRequest.adTagUrl = ads; } const width = this.#element.parentElement ? this.#element.parentElement.offsetWidth : 0; const height = this.#element.parentElement ? this.#element.parentElement.offsetHeight : 0; this.#adsRequest.linearAdSlotWidth = width; this.#adsRequest.linearAdSlotHeight = height; this.#adsRequest.nonLinearAdSlotWidth = width; this.#adsRequest.nonLinearAdSlotHeight = height / 3; this.#adsRequest.setAdWillAutoPlay(this.#autoStart); this.#adsRequest.setAdWillPlayMuted(this.#autoStartMuted); this.#adsLoader.requestAds(this.#adsRequest); } /** * Internal callback to request Ads. * * @memberof Ads */ private _contentLoadedAction() { if (this.#preloadContent) { this.#element.removeEventListener('loadedmetadata', this.#preloadContent); this.#preloadContent = null; } this._requestAds(); } /** * Reset Ads Player after manual ad break. * * If we have set `autoPlayAdBreaks` to `false`, destroy the adsManager to prevent post rolls * and reset the SDK. * https://developers.google.com/interactive-media-ads/docs/sdks/html5/faq#8 * * @memberof Ads */ private _resetAdsAfterManualBreak() { if (this.#adsManager) { this.#adsManager.destroy(); } this.#adsLoader.contentComplete(); this.#adsDone = false; this.#playTriggered = true; } /** * Remove event for `loadedmetadata` and set the player to resume regular media. * * @memberof Ads */ private _prepareMedia() { this.#media.currentTime = this.#lastTimePaused; this.#element.removeEventListener('loadedmetadata', this._loadedMetadataHandler); this._resumeMedia(); } private _setMediaVolume(volume: number) { this.#media.volume = volume; this.#media.muted = volume === 0; } private _handleClickInContainer() { if (this.#media.paused) { const e = addEvent('paused'); this.#element.dispatchEvent(e); this.pause(); } } private _handleResizeAds() { this.resizeAds(); } } export default Ads;
the_stack
import "ariakit-test/mock-get-client-rects"; import { sleep } from "ariakit-test"; import { disableFocus, disableFocusIn, ensureFocus, focusIfNeeded, getAllFocusable, getAllFocusableIn, getAllTabbable, getAllTabbableIn, getClosestFocusable, getFirstFocusable, getFirstFocusableIn, getFirstTabbable, getFirstTabbableIn, getLastTabbable, getLastTabbableIn, getNextTabbable, getNextTabbableIn, getPreviousTabbable, getPreviousTabbableIn, hasFocus, hasFocusWithin, isFocusable, isTabbable, restoreFocusIn, } from "../focus"; function getById<T extends HTMLElement = HTMLElement>(id: string) { return document.getElementById(id) as T; } test("isFocusable", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div id='div' /> <input id="input" /> <input id="inputNegativeTabIndex" tabindex="-1" /> <input id="inputHidden" hidden /> <input id="inputDisabled" disabled /> `; const div = getById("div"); const input = getById("input"); const inputNegativeTabIndex = getById("inputNegativeTabIndex"); const inputHidden = getById("inputHidden"); const inputDisabled = getById("inputDisabled"); expect(isFocusable(div)).toBe(false); expect(isFocusable(input)).toBe(true); expect(isFocusable(inputNegativeTabIndex)).toBe(true); expect(isFocusable(inputHidden)).toBe(false); expect(isFocusable(inputDisabled)).toBe(false); document.body.innerHTML = initialInnerHTML; }); test("isTabbable", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <input id="input" /> <input id="inputNegativeTabIndex" tabindex="-1" /> <input id="inputZeroTabIndex" tabindex="0" /> <input id="inputPositiveTabIndex" tabindex="1" /> `; const input = getById("input"); const inputNegativeTabIndex = getById("inputNegativeTabIndex"); const inputZeroTabIndex = getById("inputZeroTabIndex"); const inputPositiveTabIndex = getById("inputPositiveTabIndex"); expect(isTabbable(input)).toBe(true); expect(isTabbable(inputNegativeTabIndex)).toBe(false); expect(isTabbable(inputZeroTabIndex)).toBe(true); expect(isTabbable(inputPositiveTabIndex)).toBe(true); document.body.innerHTML = initialInnerHTML; }); test("getAllFocusableIn", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div id="container" tabindex="0"> <div id='subContainer'> <input id="input" /> <input id="inputNegativeTabIndex" tabindex="-1" /> <input id="inputZeroTabIndex" tabindex="0" /> <input id="inputPositiveTabIndex" tabindex="1" /> </div> </div> `; const container = getById("container"); const subContainer = getById("subContainer"); const input = getById("input"); const inputNegativeTabIndex = getById("inputNegativeTabIndex"); const inputZeroTabIndex = getById("inputZeroTabIndex"); const inputPositiveTabIndex = getById("inputPositiveTabIndex"); expect(getAllFocusableIn(container)).toEqual([ input, inputNegativeTabIndex, inputZeroTabIndex, inputPositiveTabIndex, ]); expect(getAllFocusableIn(container, true)).toEqual([ container, input, inputNegativeTabIndex, inputZeroTabIndex, inputPositiveTabIndex, ]); expect(getAllFocusableIn(subContainer, true)).toEqual([ input, inputNegativeTabIndex, inputZeroTabIndex, inputPositiveTabIndex, ]); document.body.innerHTML = initialInnerHTML; }); test("getAllFocusable", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div id="container" tabindex="0"> <div id='subContainer'> <input id="input" /> <input id="inputNegativeTabIndex" tabindex="-1" /> <input id="inputZeroTabIndex" tabindex="0" /> <input id="inputPositiveTabIndex" tabindex="1" /> </div> </div> `; const container = getById("container"); const input = getById("input"); const inputNegativeTabIndex = getById("inputNegativeTabIndex"); const inputZeroTabIndex = getById("inputZeroTabIndex"); const inputPositiveTabIndex = getById("inputPositiveTabIndex"); expect(getAllFocusable()).toEqual([ container, input, inputNegativeTabIndex, inputZeroTabIndex, inputPositiveTabIndex, ]); expect(getAllFocusable(true)).toEqual([ container, input, inputNegativeTabIndex, inputZeroTabIndex, inputPositiveTabIndex, ]); document.body.innerHTML = initialInnerHTML; }); test("getFirstFocusableIn", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div id="container" tabindex="0"> <div id='subContainer'> <input id="input" /> <input id="inputNegativeTabIndex" tabindex="-1" /> <input id="inputZeroTabIndex" tabindex="0" /> <input id="inputPositiveTabIndex" tabindex="1" /> </div> </div> `; const container = getById("container"); const input = getById("input"); expect(getFirstFocusableIn(container)).toBe(input); expect(getFirstFocusableIn(container, true)).toBe(container); document.body.innerHTML = initialInnerHTML; }); test("getFirstFocusable", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div id="container" tabindex="0"> <div id='subContainer'> <input id="input" /> <input id="inputNegativeTabIndex" tabindex="-1" /> <input id="inputZeroTabIndex" tabindex="0" /> <input id="inputPositiveTabIndex" tabindex="1" /> </div> </div> `; const container = getById("container"); expect(getFirstFocusable()).toBe(container); expect(getFirstFocusable(true)).toBe(container); document.body.innerHTML = initialInnerHTML; }); test("getAllTabbableIn", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div id="container"> <input id="input" /> <input id="inputNegativeTabIndex" tabindex="-1" /> <input id="inputZeroTabIndex" tabindex="0" /> <input id="inputPositiveTabIndex" tabindex="1" /> </div> <div id="container2" tabindex="0" /> `; const container = getById("container"); const input = getById("input"); const inputZeroTabIndex = getById("inputZeroTabIndex"); const inputPositiveTabIndex = getById("inputPositiveTabIndex"); const container2 = getById("container2"); expect(getAllTabbableIn(container)).toEqual([ input, inputZeroTabIndex, inputPositiveTabIndex, ]); expect(getAllTabbableIn(container, true)).toEqual([ input, inputZeroTabIndex, inputPositiveTabIndex, ]); expect(getAllTabbableIn(container, true, true)).toEqual([ input, inputZeroTabIndex, inputPositiveTabIndex, ]); expect(getAllTabbableIn(container2)).toEqual([]); expect(getAllTabbableIn(container2, true)).toEqual([container2]); expect(getAllTabbableIn(container2, false, true)).toEqual([]); document.body.innerHTML = initialInnerHTML; }); test("getAllTabbable", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div id="container" tabindex="0"> <input id="input" /> <input id="inputNegativeTabIndex" tabindex="-1" /> <input id="inputZeroTabIndex" tabindex="0" /> <input id="inputPositiveTabIndex" tabindex="1" /> </div> `; const container = getById("container"); const input = getById("input"); const inputZeroTabIndex = getById("inputZeroTabIndex"); const inputPositiveTabIndex = getById("inputPositiveTabIndex"); expect(getAllTabbable()).toEqual([ container, input, inputZeroTabIndex, inputPositiveTabIndex, ]); expect(getAllTabbable(true)).toEqual([ container, input, inputZeroTabIndex, inputPositiveTabIndex, ]); document.body.innerHTML = initialInnerHTML; }); test("getFirstTabbableIn", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div id="container" tabindex="0"> <input id="input" /> <input id="inputNegativeTabIndex" tabindex="-1" /> <input id="inputZeroTabIndex" tabindex="0" /> <input id="inputPositiveTabIndex" tabindex="1" /> </div> `; const container = getById("container"); const input = getById("input"); expect(getFirstTabbableIn(container)).toBe(input); expect(getFirstTabbableIn(container, true)).toBe(container); expect(getFirstTabbableIn(container, true, true)).toBe(container); expect(getFirstTabbableIn(container, false, true)).toBe(input); document.body.innerHTML = initialInnerHTML; }); test("getFirstTabbable", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div id="container" tabindex="0"> <input id="input" /> <input id="inputNegativeTabIndex" tabindex="-1" /> <input id="inputZeroTabIndex" tabindex="0" /> <input id="inputPositiveTabIndex" tabindex="1" /> </div> `; const container = getById("container"); expect(getFirstTabbable()).toBe(container); expect(getFirstTabbable(true)).toBe(container); document.body.innerHTML = initialInnerHTML; }); test("getLastTabbableIn", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div id="container" tabindex="0"> <input id="input" /> <input id="inputNegativeTabIndex" tabindex="-1" /> <input id="inputZeroTabIndex" tabindex="0" /> <input id="inputPositiveTabIndex" tabindex="1" /> </div> `; const container = getById("container"); const inputPositiveTabIndex = getById("inputPositiveTabIndex"); expect(getLastTabbableIn(container)).toBe(inputPositiveTabIndex); expect(getLastTabbableIn(container, true)).toBe(inputPositiveTabIndex); expect(getLastTabbableIn(container, true, true)).toBe(inputPositiveTabIndex); expect(getLastTabbableIn(container, false, true)).toBe(inputPositiveTabIndex); expect(getLastTabbableIn(container, true, false)).toBe(inputPositiveTabIndex); document.body.innerHTML = initialInnerHTML; }); test("getLastTabbable", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div id="container"> <input id="input" /> <input id="inputNegativeTabIndex" tabindex="-1" /> <input id="inputZeroTabIndex" tabindex="0" /> <input id="inputPositiveTabIndex" tabindex="1" /> </div> `; const inputPositiveTabIndex = getById("inputPositiveTabIndex"); expect(getLastTabbable()).toBe(inputPositiveTabIndex); expect(getLastTabbable(true)).toBe(inputPositiveTabIndex); document.body.innerHTML = initialInnerHTML; }); test("getNextTabbableIn", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div id="container" tabindex="0"> <input id="input" /> <input id="inputNegativeTabIndex" tabindex="-1" /> <input id="inputZeroTabIndex" tabindex="0" /> <input id="inputPositiveTabIndex" tabindex="1" /> </div> `; const container = getById("container"); const input = getById("input"); expect(getNextTabbableIn(container)).toBe(input); expect(getNextTabbableIn(container, true)).toBe(container); expect(getNextTabbableIn(container, true, true)).toBe(container); expect(getNextTabbableIn(container, true, true, true)).toBe(container); expect(getNextTabbableIn(container, false, true)).toBe(input); expect(getNextTabbableIn(container, false, true, true)).toBe(input); expect(getNextTabbableIn(input)).toBe(null); document.body.innerHTML = initialInnerHTML; }); test("getNextTabbable", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div id="container"> <input id="input" /> <input id="inputNegativeTabIndex" tabindex="-1" /> <input id="inputZeroTabIndex" tabindex="0" /> <input id="inputPositiveTabIndex" tabindex="1" /> </div> `; const input = getById("input"); expect(getNextTabbable()).toBe(input); expect(getNextTabbable(true)).toBe(input); document.body.innerHTML = initialInnerHTML; }); test("getPreviousTabbableIn", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div id="container"> <input id="input" /> <input id="inputNegativeTabIndex" tabindex="-1" /> <input id="inputZeroTabIndex" tabindex="0" /> <input id="inputPositiveTabIndex" tabindex="1" /> </div> `; const container = getById("container"); const inputPositiveTabIndex = getById("inputPositiveTabIndex"); expect(getPreviousTabbableIn(container)).toBe(inputPositiveTabIndex); expect(getPreviousTabbableIn(container, true)).toBe(inputPositiveTabIndex); expect(getPreviousTabbableIn(container, true, true)).toBe( inputPositiveTabIndex ); expect(getPreviousTabbableIn(container, true, true, true)).toBe( inputPositiveTabIndex ); expect(getPreviousTabbableIn(container, false, true)).toBe( inputPositiveTabIndex ); expect(getPreviousTabbableIn(container, false, true, true)).toBe( inputPositiveTabIndex ); document.body.innerHTML = initialInnerHTML; }); test("getPreviousTabbable", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div id="container"> <input id="input" /> <input id="inputNegativeTabIndex" tabindex="-1" /> <input id="inputZeroTabIndex" tabindex="0" /> <input id="inputPositiveTabIndex" tabindex="1" /> </div> `; const inputPositiveTabIndex = getById("inputPositiveTabIndex"); expect(getPreviousTabbable()).toBe(inputPositiveTabIndex); expect(getPreviousTabbable(true)).toBe(inputPositiveTabIndex); document.body.innerHTML = initialInnerHTML; }); test("getClosestFocusable", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div id="container" tabindex="0"> <input id="input" /> <input id="inputDisabled" disabled /> </div> `; const container = getById("container"); const input = getById("input"); const inputDisabled = getById("inputDisabled"); expect(getClosestFocusable(container)).toBe(container); expect(getClosestFocusable(input)).toBe(input); expect(getClosestFocusable(inputDisabled)).toBe(container); document.body.innerHTML = initialInnerHTML; }); test("hasFocus", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div id="testNode"> <input id="testInput" /> <input type="text" aria-activedescendant="cb1-opt6" aria-readonly="true" aria-owns="cb1-list" aria-autocomplete="list" role="combobox" id="cb1-edit"/> <ul aria-expanded="true" role="listbox" id="cb1-list"> <li role="option" id="cb1-opt1">Alabama</li> <li role="option" id="cb1-opt2">Alaska</li> <li role="option" id="cb1-opt3">American Samoa</li> <li role="option" id="cb1-opt4">Arizona</li> <li role="option" id="cb1-opt5">Arkansas</li> <li role="option" id="cb1-opt6">California</li> <li role="option" id="cb1-opt7">Colorado</li> </ul> </div> `; const node = getById("testNode"); // Test before any elemeted is focused expect(hasFocus(node)).toBe(false); // Test with an element focused const input = getById("testInput"); input.focus(); expect(hasFocus(node)).toBe(false); expect(hasFocus(input)).toBe(true); const input2 = getById("cb1-edit"); const focusedLi = getById("cb1-opt6"); input2.focus(); expect(hasFocus(node)).toBe(false); expect(hasFocus(input)).toBe(false); expect(hasFocus(input2)).toBe(true); expect(hasFocus(focusedLi)).toBe(true); document.body.innerHTML = initialInnerHTML; }); test("hasFocusWithin", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div class="testDivClass"> <div id="testNode"> <input id="testInput" /> <input type="text" aria-activedescendant="cb1-opt6" aria-readonly="true" aria-owns="cb1-list" aria-autocomplete="list" role="combobox" id="cb1-edit"/> <ul aria-expanded="true" role="listbox" id="cb1-list"> <li role="option" id="cb1-opt1">Alabama</li> <li role="option" id="cb1-opt2">Alaska</li> <li role="option" id="cb1-opt3">American Samoa</li> <li role="option" id="cb1-opt4">Arizona</li> <li role="option" id="cb1-opt5">Arkansas</li> <li role="option" id="cb1-opt6">California</li> <li role="option" id="cb1-opt7">Colorado</li> </ul> </div> <div id="testNode2" /> </div> `; const node = getById("testNode"); // No active element expect(hasFocusWithin(node)).toBe(false); // Input as active element and node containing the input const input = getById("testInput"); input.focus(); expect(hasFocusWithin(node)).toBe(true); // Input without aria-activedescendant as active element and node not containing the input const input2 = getById("cb1-edit"); input2.focus(); const node2 = getById("testNode2"); expect(hasFocusWithin(node2)).toBe(false); // Input with aria-activedescendant as active element and node not containing the input // and element doens't have an id const divWithTestId = document.getElementsByClassName("testDivClass")[0]!; expect(hasFocusWithin(divWithTestId)).toBe(true); document.body.innerHTML = initialInnerHTML; }); test("focusIfNeeded", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <input id="testInput" /> `; const input = getById("testInput"); // Test with no element focused expect(document.activeElement === input).toBe(false); focusIfNeeded(input); expect(document.activeElement === input).toBe(true); document.body.innerHTML = initialInnerHTML; }); test("disableFocus", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <input id="testInput" tabindex="1" /> `; const input = getById("testInput"); expect(input.getAttribute("data-tabindex")).toBe(null); expect(input.getAttribute("tabindex")).toBe("1"); disableFocus(input); expect(input.getAttribute("data-tabindex")).toBe("1"); expect(input.getAttribute("tabindex")).toBe("-1"); document.body.innerHTML = initialInnerHTML; }); test("disableFocusIn", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div id="testDiv"> <input id="testInput" tabindex="1" /> </div> `; const div = getById("testDiv"); const input = getById("testInput"); expect(input.getAttribute("data-tabindex")).toBe(null); expect(input.getAttribute("tabindex")).toBe("1"); disableFocusIn(div); expect(input.getAttribute("data-tabindex")).toBe("1"); expect(input.getAttribute("tabindex")).toBe("-1"); document.body.innerHTML = initialInnerHTML; }); test("restoreFocusIn", () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <div id="testDiv"> <input id="testInput" tabindex="1" /> <input id="testInput2" /> </div> `; const div = getById("testDiv"); const input = getById("testInput"); const input2 = getById("testInput2"); // No container data tab index expect(input.getAttribute("data-tabindex")).toBe(null); expect(input.getAttribute("tabindex")).toBe("1"); expect(input2.getAttribute("data-tabindex")).toBe(null); expect(input2.getAttribute("tabindex")).toBe(null); disableFocus(input); disableFocus(input2); expect(input.getAttribute("data-tabindex")).toBe("1"); expect(input.getAttribute("tabindex")).toBe("-1"); expect(input2.getAttribute("data-tabindex")).toBe(""); expect(input2.getAttribute("tabindex")).toBe("-1"); restoreFocusIn(div); expect(input.getAttribute("data-tabindex")).toBe(null); expect(input.getAttribute("tabindex")).toBe("1"); expect(input2.getAttribute("data-tabindex")).toBe(null); expect(input2.getAttribute("tabindex")).toBe(null); // Container data tab index div.setAttribute("data-tabindex", "2"); restoreFocusIn(div); expect(div.getAttribute("tabindex")).toBe("2"); document.body.innerHTML = initialInnerHTML; }); test("ensureFocus", async () => { const initialInnerHTML = document.body.innerHTML; document.body.innerHTML = ` <input id="testInput" /> `; const input = getById("testInput"); const rafSpy = jest .spyOn(window, "requestAnimationFrame") .mockImplementation((cb) => { setTimeout(() => cb(0)); return 0; }); expect(document.activeElement === input).toBe(false); ensureFocus(input); expect(document.activeElement === input).toBe(true); input.blur(); // isActive -> false const focusSpy = jest.spyOn(input, "focus"); expect(document.activeElement === input).toBe(false); ensureFocus(input, { isActive: () => false }); expect(document.activeElement === input).toBe(true); expect(focusSpy).toHaveBeenCalledTimes(1); await sleep(); expect(focusSpy).toHaveBeenCalledTimes(2); document.body.innerHTML = initialInnerHTML; rafSpy.mockRestore(); focusSpy.mockRestore(); });
the_stack
import * as React from 'react'; import { Button, Select, Icon, DatePicker, InputNumber } from 'antd'; import { DataGrid, IDataGrid } from 'axui-datagrid'; import { Wrapper, Segment } from 'components'; import styled from 'styled-components'; import moment = require('moment'); import { debounce, isObject } from 'axui-datagrid/utils'; const DatagridContainer = styled.div` border: 1px solid #ccc; .ant-input { height: 23px; padding: 2px 5px; } .ant-select { height: 23px; } .ant-select-selection--single { height: 23px; } .ant-select-selection__rendered { line-height: 23px; } .ant-input-number { height: 23px; } .ant-input-number-input { height: 23px; } .axui-datagrid { &:focus { outline: #ff3300 solid 1px !important; } } `; const inputNumberEditor: IDataGrid.cellEditorFunction = ({ value, update, cancel, keyAction, }) => { return ( <InputNumber style={{ width: '100%' }} autoFocus defaultValue={value} onBlur={e => { console.log('onBlur'); cancel(); }} onKeyDown={e => { if (e.which === 9) { e.preventDefault(); keyAction('EDIT_NEXT', e.currentTarget.value, { e }); } else if (e.which === 27) { e.preventDefault(); cancel({ keepEditing: true }); } else if (e.which === 13) { e.preventDefault(); update(e.currentTarget.value, { focus: true }); } }} /> ); }; const searchSelectEditor: IDataGrid.cellEditorFunction = ({ value, update, focus, blur, cancel, keyAction, }) => { return ( <Select<string> style={{ width: '100%' }} showSearch optionFilterProp="children" defaultOpen={true} autoFocus={true} defaultValue={value} dropdownClassName="axui-datagrid-select-dropdown" onSelect={val => { console.log('onSelect', val); if (value !== val) { update(val, { focus: true }); } else { cancel({ keepEditing: true }); } }} onInputKeyDown={e => { console.log('onInputKeyDown', e.currentTarget.value); if (e.which === 9) { e.preventDefault(); keyAction('EDIT_NEXT', value, { e }); } else if (e.which === 27 || e.which === 13) { e.preventDefault(); cancel({ keepEditing: true }); } }} onBlur={() => { console.log('onBlur'); cancel(); }} onDropdownVisibleChange={open => { if (open) { focus(); } }} > <Select.Option value="Jack">Jack</Select.Option> <Select.Option value="Sofia">Sofia</Select.Option> <Select.Option value="Thomas">Thomas</Select.Option> </Select> ); }; const inputDateEditor: IDataGrid.cellEditorFunction = ({ value, update, focus, keyAction, }) => { return ( <DatePicker value={value ? moment(value, 'YYYY/MM/DD') : moment()} onChange={(date, dateString) => { update(dateString, { focus: true }); // keyAction('EDIT_NEXT', dateString); }} open={true} /> ); }; interface IState { width: number; height: number; scrollTop: number; scrollLeft: number; columns: IDataGrid.IColumn[]; data: IDataGrid.IData; selection: IDataGrid.ISelection; } class InlineEdit extends React.Component<any, IState> { dataGridContainerRef: React.RefObject<HTMLDivElement>; scrollTop: number = 0; scrollContentContainerHeight: number = 0; scrollContentHeight: number = 0; bodyTrHeight: number = 24; selectedIndexes: number[] = []; debouncedOnScroll: any; constructor(props: any) { super(props); const columns: IDataGrid.IColumn[] = [ { key: 'id', width: 60, label: 'ID', editor: { activeType: 'click', type: 'text' }, }, { key: 'writer', label: 'Writer', width: 120, editor: { activeType: 'click', render: searchSelectEditor, // disable: ({ item }) => item.value['type'] === 'A', }, }, { key: 'check', label: 'checkbox', align: 'center', formatter: ({ value }) => value + '', editor: { type: 'checkbox', disable: ({ item }) => item.value['type'] === 'A', }, }, { key: 'title', width: 200, label: 'Title', editor: { activeType: 'click', type: 'text', }, }, { key: 'money', label: 'Money', formatter: 'money', align: 'right', editor: { activeType: 'click', render: inputNumberEditor, disable: ({ item }) => item.value['type'] === 'A', }, }, { key: 'date', label: 'Date', formatter: 'date', width: 105, editor: { activeType: 'click', width: 105, // need when autofitColumns render: inputDateEditor, }, }, ]; const selection: IDataGrid.ISelection = { rows: [], cols: [], focusedRow: -1, focusedCol: -1, isEditing: false, }; this.state = { width: 300, height: 300, scrollTop: 0, scrollLeft: 0, columns, data: [ { value: { id: 1, title: 'Think like a man of action and act like man of thought.', writer: 'Thomas', date: '2017/12/05', money: 120000, type: 'A', subType: 'A-1', check: true, }, }, { value: { id: 2, title: 'Courage is very important. Like a muscle, it is strengthened by use.', writer: 'Sofia', date: new Date(), money: 18000, type: 'B', subType: 'B-1', check: false, }, }, { value: { id: 3, title: 'TEST', writer: 'Jack', date: '2018/01/01', money: 9000, type: 'C', subType: 'C-1', check: false, }, }, { value: { id: 4, title: 'Think like a man of action and act like man of thought.', writer: 'Thomas', date: '2017/12/05', money: 120000, type: 'A', subType: 'A-2', check: true, }, }, { value: { id: 5, title: 'Courage is very important. Like a muscle, it is strengthened by use.', writer: 'Sofia', date: new Date(), money: 18000, type: 'B', subType: 'B-2', check: false, }, }, { value: { id: 6, title: 'TEST', writer: 'Jack', date: '2018/01/01', money: 9000, type: 'C', subType: 'C-2', check: false, }, }, ], selection, }; this.dataGridContainerRef = React.createRef(); } addItem = () => { const { data } = this.state; const dataLength = Object.keys(data).length; const newItem: IDataGrid.IData = { [dataLength]: { type: 'C', value: { id: 999, title: '', writer: '', date: '', money: 0, type: 'B', check: true, }, }, }; // 그리드의 스크롤을 변경하기 위한 스크롤 포지션 구하기 const scrollTop = this.scrollContentContainerHeight < this.scrollContentHeight ? -this.scrollContentHeight : 0; this.setState({ data: { ...data, ...newItem }, scrollTop, selection: { rows: [dataLength], cols: [0], focusedRow: dataLength, focusedCol: 0, isEditing: true, }, }); }; removeItem = () => { // console.log(this.selectedIndexes); if (this.selectedIndexes.length) { // const data: any[] = this.state.data; // const _data = data.filter((n, i) => { // return !this.selectedIndexes.includes(i); // }); // this.setState({ data: _data }); } }; // onScroll = (param: IDataGrid.IonScrollFunctionParam) => { // // console.log(param); // this.debouncedOnScroll(param.scrollTop); // }; onScroll = debounce((param: IDataGrid.IonScrollFunctionParam) => { console.log('debounce'); this.setState({ scrollTop: param.scrollTop, scrollLeft: param.scrollLeft, }); }, 300); onChangeScrollSize = (param: IDataGrid.IonChangeScrollSizeFunctionParam) => { // console.log(param); this.scrollContentHeight = param.scrollContentHeight || 0; this.bodyTrHeight = param.bodyTrHeight || 0; }; onChangeSelection = (param: IDataGrid.IonChangeSelectionParam) => { // this.setState({ selection: param }); }; onEditItem = (param: IDataGrid.IonEditParam) => { console.log(`onEditItem`, param); const { li, col: { key: colKey = '' } = {}, value } = param; const { data } = this.state; const editDataItem: IDataGrid.IDataItem = { ...data[li] }; if (isObject(value)) { editDataItem.value = { ...editDataItem.value, ...value }; } else { editDataItem.value[colKey] = value; } this.setState({ data: { ...data, [li]: editDataItem }, }); }; onKeyDown = (e: KeyboardEvent) => { // if ( // this.dataGridContainerRef.current && // e.target && // e.target instanceof Node // ) { // console.log( // this.dataGridContainerRef.current.contains(e.target), // this.dataGridContainerRef.current, // e.target, // e.currentTarget, // ); // // console.log(e.target, e.currentTarget); // } }; componentDidMount() { this.getDataGridContainerRect(); window.addEventListener('resize', this.getDataGridContainerRect, false); window.addEventListener('keydown', this.onKeyDown, false); } componentWillUnmount() { window.removeEventListener('resize', this.getDataGridContainerRect); window.removeEventListener('keydown', this.onKeyDown); } render() { const { width, height, columns, data, scrollTop, scrollLeft, selection, } = this.state; return ( <Wrapper> <Segment padded> <h1>Inline Edit</h1> <p> One column is consists of the attributes which are defined in '&#123; &#125;' context. <br /> So if you want to edit contents of columns, you have to add the editor attribute like 'editor: &#123;type: 'text' &#125;' within '&#123; &#125;' what you want to add editor mode. <br /> After this, you can activate editor mode using double-click or return key. </p> <div ref={this.dataGridContainerRef}> <DatagridContainer> <DataGrid style={{ fontSize: '12px' }} width={width - 2} height={height - 2} columns={columns} data={data} dataLength={Object.keys(data).length} options={{ rowSelectorColumnWidth: 26, showRowSelector: true, header: { align: 'center', }, }} selection={selection} onChangeSelection={this.onChangeSelection} onScroll={this.onScroll} scrollTop={scrollTop} scrollLeft={scrollLeft} onChangeScrollSize={this.onChangeScrollSize} onEdit={this.onEditItem} /> </DatagridContainer> </div> <div style={{ height: 10 }} /> <Button size="small" onClick={() => this.addItem()}> <Icon type="plus" /> Add item </Button> <Button size="small" onClick={() => this.removeItem()}> <Icon type="minus" /> Remove item </Button> <Button size="small" onClick={() => this.setState({ scrollTop: 0 })}> scroll top (0) </Button> </Segment> </Wrapper> ); } getDataGridContainerRect = (e?: Event) => { if (this.dataGridContainerRef.current) { const { width, } = this.dataGridContainerRef.current.getBoundingClientRect(); this.setState({ width }); } }; } export default InlineEdit;
the_stack
import { Component } from '@angular/core'; import { NavController, ModalController, NavParams } from 'ionic-angular'; // app pages import { PickTransactionTypePage } from '../../mypicklists/picktransactiontype/picktransactiontype'; import { PickAccountFromPage } from '../../mypicklists/pickaccountfrom/pickaccountfrom'; import { PickAccountToPage } from '../../mypicklists/pickaccountto/pickaccountto'; import { PickPayeePage } from '../../mypicklists/pickpayee/pickpayee'; import { PickCategoryPage } from '../../mypicklists/pickcategory/pickcategory'; import { PickAmountPage } from '../../mypicklists/pickamount/pickamount'; import { PickNotesPage } from '../../mypicklists/picknotes/picknotes'; import { PickPhotoPage } from '../../mypicklists/pickphoto/pickphoto'; // services import { AuthService } from '../../../providers/auth-service'; import { TransactionData } from '../../../providers/transaction-data'; // models import { IAccount } from '../../../models/account.model'; import { Transaction } from '../../../models/transaction.model'; import * as moment from 'moment'; @Component({ selector: 'page-transaction', templateUrl: 'transaction.html' }) export class TransactionPage { validationMessage: string; showValidationMessage: boolean = false; hasDataTransactionType: boolean = false; hasDataAccountFrom: boolean = false; hasDataAccountTo: boolean = false; hasDataPayee: boolean = false; hasDataCategory: boolean = false; hasDataAmount: boolean = false; hasDataDate: boolean = false; hasDataNotes: boolean = false; hasDataPhoto: boolean = false; title: string; transaction: Transaction; account: IAccount; displaydate; displaytime; mode; constructor( public nav: NavController, public modalController: ModalController, public navParams: NavParams, public auth: AuthService, public transactionData: TransactionData) { this.account = this.navParams.data.paramAccount; this.mode = this.navParams.data.paramMode; if (this.mode === 'New') { this.transaction = new Transaction(); this.title = 'Create Transaction'; this.hasDataTransactionType = false; this.hasDataAccountFrom = false; this.hasDataAccountTo = false; this.hasDataPayee = false; this.hasDataCategory = false; this.hasDataAmount = false; this.hasDataDate = false; this.hasDataNotes = false; this.hasDataPhoto = false; this.transactionData.reset(); } else { this.transaction = new Transaction(); this.transaction.fromData(this.navParams.data.paramTransaction); this.title = this.transaction.payee; this.hasDataTransactionType = true; this.hasDataAccountFrom = (this.transaction.accountFrom !== "") ? true : false; this.hasDataAccountTo = (this.transaction.accountTo !== "") ? true : false; this.hasDataPayee = true; this.hasDataCategory = true; this.hasDataAmount = true; this.hasDataDate = true; this.hasDataNotes = true; this.hasDataPhoto = true; // Format date let dtDB = this.transaction.date / 1000; this.displaydate = moment.unix(dtDB).format(); this.displaytime = moment.unix(dtDB).format(); // Determine typedisplay if missing: Income / Expense if (this.transaction.typedisplay === '') { this.transaction.typedisplay = this.transaction.type } // Prepare services this.transactionData.setTransactionType(this.transaction.type); this.transactionData.setPayeeName(this.transaction.payee); this.transactionData.setPayeeID(this.transaction.payeeid); this.transactionData.setCategoryName(this.transaction.category); this.transactionData.setCategoryID(this.transaction.categoryid); this.transactionData.setAmount(this.transaction.amount); this.transactionData.setNotes(this.transaction.notes); } } ionViewWillEnter() { let referrer = this.transactionData.getReferrer(); switch (referrer) { case 'TransactionsPage': { break; } case 'PickTransactionTypePage': { // Transaction Type this.transaction.typedisplay = this.transactionData.getTransactionType(); this.transaction.istransfer = (this.transaction.typedisplay === "Transfer") ? true : false; this.hasDataTransactionType = (this.transaction.typedisplay !== "") ? true : false; break; } case 'PickAccountFromPage': { // Account to transfer from this.transaction.accountFrom = this.transactionData.getAccountFrom(); this.transaction.accountFromId = this.transactionData.getAccountFromId(); this.hasDataAccountFrom = (this.transaction.accountFrom !== "") ? true : false; break; } case 'PickAccountToPage': { // Account to transfer to this.transaction.accountTo = this.transactionData.getAccountTo(); this.transaction.accountToId = this.transactionData.getAccountToId(); this.hasDataAccountTo = (this.transaction.accountTo !== "") ? true : false; break; } case 'PickPayeePage': { // Payee this.transaction.payee = this.transactionData.getPayeeName(); this.transaction.payeeid = this.transactionData.getPayeeID(); this.hasDataPayee = (this.transaction.payee !== "") ? true : false; break; } case 'PickCategoryPage': { // Payee this.transaction.category = this.transactionData.getCategoryName(); this.transaction.categoryid = this.transactionData.getCategoryID(); this.hasDataCategory = (this.transaction.category !== "") ? true : false; break; } case 'PickAmountPage': { // Payee this.transaction.amount = this.transactionData.getAmount(); this.hasDataAmount = (this.transaction.amount !== "") ? true : false; break; } case 'PickNotesPage': { // Payee this.transaction.notes = this.transactionData.getNotes(); if (this.transaction.notes !== '') { this.hasDataNotes = true; } break; } case 'PickPhotoPage': { // Payee this.transaction.notes = this.transactionData.getPhoto(); this.hasDataPhoto = (this.transaction.photo !== "") ? true : false; break; } } } save() { // Validate form data if (this.transaction.typedisplay === 'undefined' || this.transaction.typedisplay === '') { this.showValidationMessage = true; this.validationMessage = "Please select Transaction Type" return; } if (this.transaction.category === 'undefined' || this.transaction.category === '') { this.showValidationMessage = false; this.validationMessage = "Please select a Category" return; } if (this.transaction.payee === 'undefined' || this.transaction.payee === '') { this.showValidationMessage = false; this.validationMessage = "Please select a Payee" return; } if (this.transaction.amount === 'undefined' || this.transaction.amount === '') { this.showValidationMessage = false; this.validationMessage = "Please enter an amount for this transaction" return; } // Format date and time in epoch time let dtDateISO = moment(this.displaydate, moment.ISO_8601); let dtHour; let dtMinutes; if (this.mode === 'New') { dtHour = moment(this.displaytime, 'HH:mm').format("HH"); dtMinutes = moment(this.displaytime, 'HH:mm').format("mm"); } else { dtHour = moment(this.displaytime, moment.ISO_8601).format("HH"); dtMinutes = moment(this.displaytime, moment.ISO_8601).format("mm"); } let iHour = parseInt(dtHour); let iMinute = parseInt(dtMinutes); let dt = dtDateISO.hour(iHour).minutes(iMinute); let dtTran = moment(dt, 'MMMM D, YYYY hh:mm a').valueOf(); this.transaction.date = dtTran; //console.log(this.displaydate); //console.log(this.displaytime); //console.log(dtDateISO); //console.log(dtHour, dtMinutes); //console.log(dtTran); // Handle Who this.transaction.addedby = this.auth.user.nickname; // // Handle transaction type for Transfers // if (this.transaction.typedisplay === "Transfer" && this.account.$key === this.transaction.accountToId) { this.transaction.type = 'Income'; this.transaction.istransfer = true; } else if (this.transaction.typedisplay === "Transfer" && this.account.$key !== this.transaction.accountToId) { this.transaction.type = 'Expense'; this.transaction.istransfer = true; } else { this.transaction.accountFrom = ''; this.transaction.accountFromId = ''; this.transaction.accountTo = ''; this.transaction.accountToId = ''; this.transaction.type = this.transaction.typedisplay; this.transaction.istransfer = false; } if (this.mode === 'New') { // // Create New Transaction // this.auth.addTransaction(this.transaction, this.account); } else { // // Update Existing Transaction // this.auth.updateTransaction(this.transaction, this.account); } this.transactionData.setReferrer('TransactionPage'); this.transactionData.ismodified = true; this.nav.pop(); } pickTransactionType() { this.showValidationMessage = false; this.nav.push(PickTransactionTypePage); } pickTransactionAccountFrom() { this.showValidationMessage = false; this.nav.push(PickAccountFromPage); } pickTransactionAccountTo() { this.showValidationMessage = false; this.nav.push(PickAccountToPage); } pickPayee() { if (!this.hasDataTransactionType) { // Make sure a transaction type has been selected this.showValidationMessage = true; this.validationMessage = "Please select Transaction Type"; return; } this.auth.LoadingControllerShow(); this.nav.push(PickPayeePage); } pickCategory() { if (!this.hasDataTransactionType) { // Make sure a transaction type has been selected this.showValidationMessage = true; this.validationMessage = "Please select Transaction Type"; return; } this.auth.LoadingControllerShow(); this.nav.push(PickCategoryPage); } pickAmount() { if (!this.hasDataTransactionType) { // Make sure a transaction type has been selected this.showValidationMessage = true; this.validationMessage = "Please select Transaction Type"; return; } this.nav.push(PickAmountPage); } pickNotes() { if (!this.hasDataTransactionType) { // Make sure a transaction type has been selected this.showValidationMessage = true; this.validationMessage = "Please select Transaction Type"; return; } this.nav.push(PickNotesPage); } pickPhoto() { if (!this.hasDataTransactionType) { // Make sure a transaction type has been selected this.showValidationMessage = true; this.validationMessage = "Please select Transaction Type"; return; } this.nav.push(PickPhotoPage); } }
the_stack
class Main extends eui.UILayer { /** * 加载进度界面 * loading process interface */ private loadingView: LoadingUI; protected createChildren(): void { super.createChildren(); //inject the custom material parser //注入自定义的素材解析器 let assetAdapter = new AssetAdapter(); egret.registerImplementation("eui.IAssetAdapter", assetAdapter); egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter()); //Config loading process interface //设置加载进度界面 this.loadingView = new LoadingUI(); this.stage.addChild(this.loadingView); // initialize the Resource loading library //初始化Resource资源加载库 RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this); RES.loadConfig("resource/default.res.json", "resource/"); } /** * 配置文件加载完成,开始预加载皮肤主题资源和preload资源组。 * Loading of configuration file is complete, start to pre-load the theme configuration file and the preload resource group */ private onConfigComplete(event: RES.ResourceEvent): void { RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this); // load skin theme configuration file, you can manually modify the file. And replace the default skin. //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。 let theme = new eui.Theme("resource/default.thm.json", this.stage); theme.addEventListener(eui.UIEvent.COMPLETE, this.onThemeLoadComplete, this); RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this); RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this); RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this); RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this); RES.loadGroup("preload"); } private isThemeLoadEnd: boolean = false; /** * 主题文件加载完成,开始预加载 * Loading of theme configuration file is complete, start to pre-load the */ private onThemeLoadComplete(): void { this.isThemeLoadEnd = true; this.createScene(); } private isResourceLoadEnd: boolean = false; /** * preload资源组加载完成 * preload resource group is loaded */ private onResourceLoadComplete(event: RES.ResourceEvent): void { if (event.groupName == "preload") { this.stage.removeChild(this.loadingView); RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this); RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this); RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this); RES.removeEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, this.onItemLoadError, this); this.isResourceLoadEnd = true; this.createScene(); } } private createScene() { if (this.isThemeLoadEnd && this.isResourceLoadEnd) { this.startCreateScene(); } } /** * 资源组加载出错 * The resource group loading failed */ private onItemLoadError(event: RES.ResourceEvent): void { console.warn("Url:" + event.resItem.url + " has failed to load"); } /** * 资源组加载出错 * Resource group loading failed */ private onResourceLoadError(event: RES.ResourceEvent): void { //TODO console.warn("Group:" + event.groupName + " has failed to load"); //忽略加载失败的项目 //ignore loading failed projects this.onResourceLoadComplete(event); } /** * preload资源组加载进度 * loading process of preload resource */ private onResourceProgress(event: RES.ResourceEvent): void { if (event.groupName == "preload") { this.loadingView.setProgress(event.itemsLoaded, event.itemsTotal); } } private textfield: egret.TextField; /** * 创建场景界面 * Create scene interface */ protected startCreateScene(): void { //创建主布局 var scroller = new eui.Scroller(); scroller.percentWidth = 100; scroller.percentHeight = 100; this.addChild(scroller); var mainGroup = new eui.Group(); let mainLayout: eui.VerticalLayout = new eui.VerticalLayout(); mainLayout.gap = 8; mainGroup.layout = mainLayout; scroller.viewport = mainGroup; scroller.addChild(mainGroup); //创建文本 let label: eui.Label = new eui.Label(); label.text = "测试文本,今天天气真不错啊,不是吗?Yes, what a great day."; label.width = 600; label.height = 300; label.fontFamily = "Microsoft Yahei, Tahama"; label.textColor = 0xffeeaa; label.size = 36; label.bold = false; label.italic = false; label.textAlign = egret.HorizontalAlign.CENTER; label.verticalAlign = egret.VerticalAlign.MIDDLE; label.lineSpacing = 8; mainGroup.addChild(label); //自定义styley以及创建按钮 var button = new eui.Button(); EXML.load("resource/skins/MyLabelSkin.exml", (clazz: any, url: string) => { button.skinName = clazz; button.labelDisplay.text = "Good"; (<eui.Label>button.labelDisplay).size = 49; button.enabled = true; }, this); mainGroup.addChild(button); //创建图片 let image: eui.Image = new eui.Image(); image.source = "resource/assets/egret_icon.png"; //九宫格的四个参数分别是:区域1的宽高,区域5的宽高 image.scale9Grid = new egret.Rectangle(10, 10, 80, 80); // image.width = 200; // image.height = 200; mainGroup.addChild(image); // 创建复选框 let cbx = new eui.CheckBox(); cbx.label = "选择1"; mainGroup.addChild(cbx); cbx.addEventListener(eui.UIEvent.CHANGE, (e: eui.UIEvent) => { egret.log(e.target.selected); }, this); let cbx2 = new eui.CheckBox(); cbx2.label = "选择2"; mainGroup.addChild(cbx2); let cbx3 = new eui.CheckBox(); cbx3.label = "选择3"; mainGroup.addChild(cbx3); cbx3.enabled = false; //创建单选框 // let rdb: eui.RadioButton = new eui.RadioButton(); // rdb.label = "单选1"; // rdb.value = 1; // rdb.groupName = "group1"; // rdb.addEventListener(eui.UIEvent.CHANGE, this.radioChangeHandler, this); // this.addChild(rdb); // let rdb2: eui.RadioButton = new eui.RadioButton(); // rdb2.label = "单选2"; // rdb2.value = 2; // rdb2.groupName = "group1"; // rdb2.addEventListener(eui.UIEvent.CHANGE, this.radioChangeHandler, this); // this.addChild(rdb2); // let rdb3: eui.RadioButton = new eui.RadioButton(); // rdb3.label = "单选3"; // rdb3.value = 3; // rdb3.groupName = "group1"; // rdb3.addEventListener(eui.UIEvent.CHANGE, this.radioChangeHandler, this); // this.addChild(rdb3); //使用RadioGroup let rdbGroup: eui.RadioButtonGroup = new eui.RadioButtonGroup(); rdbGroup.addEventListener(eui.UIEvent.CHANGE, (e: eui.UIEvent) => { let rdbGroup: eui.RadioButtonGroup = e.target; egret.log(rdbGroup.selectedValue); }, this); let rdb: eui.RadioButton = new eui.RadioButton(); rdb.label = "单选1"; rdb.value = 1; rdb.group = rdbGroup; mainGroup.addChild(rdb); let rdb2: eui.RadioButton = new eui.RadioButton(); rdb2.label = "单选2"; rdb2.value = 2; rdb2.group = rdbGroup; mainGroup.addChild(rdb2); let rdb3: eui.RadioButton = new eui.RadioButton(); rdb3.label = "单选3"; rdb3.value = 3; rdb3.group = rdbGroup; mainGroup.addChild(rdb3); //使用状态切换按钮 let switchButton: eui.ToggleSwitch = new eui.ToggleSwitch(); switchButton.label = "ToggleSwitch"; switchButton.addEventListener(eui.UIEvent.CHANGE, (e: eui.UIEvent) => { let switchButton: eui.ToggleSwitch = e.target; egret.log(switchButton.selected); }, this); mainGroup.addChild(switchButton); var toggleGroup: eui.Group = new eui.Group(); var toggleGroupLayout = new eui.HorizontalLayout(); toggleGroupLayout.verticalAlign = egret.VerticalAlign.CONTENT_JUSTIFY; toggleGroup.layout = toggleGroupLayout; mainGroup.addChild(toggleGroup); //使用ToggleButton var toggleBtns: Array<eui.ToggleButton> = []; for (var i: number = 0; i < 4; i++) { var btn: eui.ToggleButton = new eui.ToggleButton(); btn.label = i + 1 + ""; btn.addEventListener(eui.UIEvent.CHANGE, (e: eui.UIEvent) => { for (var i: number = 0; i < toggleBtns.length; i++) { var btn: eui.ToggleButton = toggleBtns[i]; btn.selected = (btn == e.target); } }, this); toggleBtns.push(btn); toggleGroup.addChild(btn); } //使用滑动选择器,水平滑动HSlider, 竖直滑动VSlider let hSlider: eui.HSlider = new eui.HSlider(); hSlider.width = 200; hSlider.x = 20; hSlider.y = 20; hSlider.minimum = 0; hSlider.maximum = 100; hSlider.value = 10; hSlider.addEventListener(eui.UIEvent.CHANGE, (e: eui.UIEvent) => { console.log(e.target.value); }, this); mainGroup.addChild(hSlider); //使用进度条 let progressBar: eui.ProgressBar = new eui.ProgressBar(); progressBar.maximum = 200; progressBar.minimum = 20; progressBar.width = 400; progressBar.height = 40; progressBar.value = 40; //定义进度条的方向 progressBar.direction = eui.Direction.BTT; mainGroup.addChild(progressBar); let timer = new egret.Timer(1000, 0); timer.addEventListener(egret.TimerEvent.TIMER, () => { progressBar.value += 10; if (progressBar.value >= progressBar.maximum) { timer.stop(); } }, this) timer.start(); //使用文本输入控件 var inputGroup: eui.Group = new eui.Group(); inputGroup.layout = new eui.BasicLayout(); mainGroup.addChild(inputGroup); var editBackground: eui.Image = new eui.Image(); var editText: eui.EditableText = new eui.EditableText(); editBackground.source = "resource/assets/bg_edit.png"; editBackground.scale9Grid = new egret.Rectangle(2, 2, 20, 20); editBackground.width = 500; editBackground.height = 200; editBackground.verticalCenter = 0; editBackground.horizontalCenter = 0; inputGroup.addChild(editBackground); editText.text = "请输入文本"; editText.textColor = 0x2233aa; editText.multiline = true; editText.verticalCenter = 0; editText.horizontalCenter = 0; editText.displayAsPassword = false; editText.wordWrap = true; editText.width = editBackground.width - 16; editText.height = editBackground.height - 16; editText.left = 0; inputGroup.addChild(editText); //使用TextInput let textInput = new eui.TextInput(); textInput.prompt = "请输入文字"; mainGroup.addChild(textInput); } private radioChangeHandler(e: eui.UIEvent): void { egret.log(e.target.value); } /** * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。 * Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json. */ private createBitmapByName(name: string): egret.Bitmap { let result = new egret.Bitmap(); let texture: egret.Texture = RES.getRes(name); result.texture = texture; return result; } }
the_stack
import { Inject, Injectable, Optional } from '@angular/core'; import { HttpClient, HttpHeaders, HttpParams, HttpResponse, HttpEvent } from '@angular/common/http'; import { CustomHttpUrlEncodingCodec } from '../encoder'; import { Observable } from 'rxjs'; import { Appearance } from '../model/appearance'; import { ArticleResponse } from '../model/articleResponse'; import { CategoryResponse } from '../model/categoryResponse'; import { CreateArticleDto } from '../model/createArticleDto'; import { CreateCategoryDto } from '../model/createCategoryDto'; import { CreateCustomDto } from '../model/createCustomDto'; import { CreateMediaDto } from '../model/createMediaDto'; import { CreatePageDto } from '../model/createPageDto'; import { CreateWidgetDto } from '../model/createWidgetDto'; import { CustomResponse } from '../model/customResponse'; import { EditArticleDto } from '../model/editArticleDto'; import { EditCategoryDto } from '../model/editCategoryDto'; import { EditCustomDto } from '../model/editCustomDto'; import { EditMediaDto } from '../model/editMediaDto'; import { EditPageDto } from '../model/editPageDto'; import { EditWidgetDto } from '../model/editWidgetDto'; import { KeyValue } from '../model/keyValue'; import { MediaResponse } from '../model/mediaResponse'; import { PageResponse } from '../model/pageResponse'; import { PaginateArticle } from '../model/paginateArticle'; import { PaginateCategory } from '../model/paginateCategory'; import { PaginateCustom } from '../model/paginateCustom'; import { PaginateMedia } from '../model/paginateMedia'; import { PaginatePage } from '../model/paginatePage'; import { PaginateWidget } from '../model/paginateWidget'; import { TreeNode } from '../model/treeNode'; import { WidgetResponse } from '../model/widgetResponse'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; @Injectable({ providedIn: 'root' }) export class CmsService { protected basePath = 'http://localhost'; public defaultHeaders = new HttpHeaders(); public configuration = new Configuration(); constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { if (configuration) { this.configuration = configuration; this.configuration.basePath = configuration.basePath || basePath || this.basePath; } else { this.configuration.basePath = basePath || this.basePath; } } /** * @param consumes string[] mime-types * @return true: consumes contains 'multipart/form-data', false: otherwise */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; for (const consume of consumes) { if (form === consume) { return true; } } return false; } /** * * 创建文章 * @param createArticleDto 创建参数 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public articleCreate(createArticleDto: CreateArticleDto, observe?: 'body', reportProgress?: boolean): Observable<ArticleResponse>; public articleCreate(createArticleDto: CreateArticleDto, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<ArticleResponse>>; public articleCreate(createArticleDto: CreateArticleDto, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<ArticleResponse>>; public articleCreate(createArticleDto: CreateArticleDto, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (createArticleDto === null || createArticleDto === undefined) { throw new Error('Required parameter createArticleDto was null or undefined when calling articleCreate.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ 'application/json' ]; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected !== undefined) { headers = headers.set('Content-Type', httpContentTypeSelected); } return this.httpClient.post<ArticleResponse>(`${this.configuration.basePath}/api/article`, createArticleDto, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 查询文章 * @param id 文章编号 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public articleGet(id: string, observe?: 'body', reportProgress?: boolean): Observable<ArticleResponse>; public articleGet(id: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<ArticleResponse>>; public articleGet(id: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<ArticleResponse>>; public articleGet(id: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling articleGet.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<ArticleResponse>(`${this.configuration.basePath}/api/article/${encodeURIComponent(String(id))}`, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 获取文章管理界面配置信息. * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public articleGetConfig(observe?: 'body', reportProgress?: boolean): Observable<Appearance>; public articleGetConfig(observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Appearance>>; public articleGetConfig(observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Appearance>>; public articleGetConfig(observe: any = 'body', reportProgress: boolean = false ): Observable<any> { let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<Appearance>(`${this.configuration.basePath}/api/article/config`, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 查询文章数据 * @param keyword 关键词 * @param category * @param page * @param size 页大小 * @param sort 排序 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public articleQuery(keyword?: string, category?: string, page?: number, size?: number, sort?: string, observe?: 'body', reportProgress?: boolean): Observable<PaginateArticle>; public articleQuery(keyword?: string, category?: string, page?: number, size?: number, sort?: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<PaginateArticle>>; public articleQuery(keyword?: string, category?: string, page?: number, size?: number, sort?: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<PaginateArticle>>; public articleQuery(keyword?: string, category?: string, page?: number, size?: number, sort?: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { let queryParameters = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); if (keyword !== undefined && keyword !== null) { queryParameters = queryParameters.set('keyword', <any>keyword); } if (category !== undefined && category !== null) { queryParameters = queryParameters.set('category', <any>category); } if (page !== undefined && page !== null) { queryParameters = queryParameters.set('page', <any>page); } if (size !== undefined && size !== null) { queryParameters = queryParameters.set('size', <any>size); } if (sort !== undefined && sort !== null) { queryParameters = queryParameters.set('sort', <any>sort); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<PaginateArticle>(`${this.configuration.basePath}/api/article/query`, { params: queryParameters, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 删除文章 * @param id 文章编号 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public articleRemove(id: string, observe?: 'body', reportProgress?: boolean): Observable<boolean>; public articleRemove(id: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<boolean>>; public articleRemove(id: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<boolean>>; public articleRemove(id: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling articleRemove.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'text/html' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.delete<boolean>(`${this.configuration.basePath}/api/article/${encodeURIComponent(String(id))}`, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 查询文章 * @param keyword 关键词 * @param value 已选中的文章编号 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public articleSearch(keyword?: string, value?: string, observe?: 'body', reportProgress?: boolean): Observable<Array<KeyValue>>; public articleSearch(keyword?: string, value?: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Array<KeyValue>>>; public articleSearch(keyword?: string, value?: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Array<KeyValue>>>; public articleSearch(keyword?: string, value?: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { let queryParameters = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); if (keyword !== undefined && keyword !== null) { queryParameters = queryParameters.set('keyword', <any>keyword); } if (value !== undefined && value !== null) { queryParameters = queryParameters.set('value', <any>value); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<Array<KeyValue>>(`${this.configuration.basePath}/api/article/search`, { params: queryParameters, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 更新文章 * @param editArticleDto 文章参数 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public articleUpdate(editArticleDto: EditArticleDto, observe?: 'body', reportProgress?: boolean): Observable<ArticleResponse>; public articleUpdate(editArticleDto: EditArticleDto, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<ArticleResponse>>; public articleUpdate(editArticleDto: EditArticleDto, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<ArticleResponse>>; public articleUpdate(editArticleDto: EditArticleDto, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (editArticleDto === null || editArticleDto === undefined) { throw new Error('Required parameter editArticleDto was null or undefined when calling articleUpdate.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ 'application/json' ]; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected !== undefined) { headers = headers.set('Content-Type', httpContentTypeSelected); } return this.httpClient.put<ArticleResponse>(`${this.configuration.basePath}/api/article`, editArticleDto, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 创建分类 * @param createCategoryDto 创建参数 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public categoryCreate(createCategoryDto: CreateCategoryDto, observe?: 'body', reportProgress?: boolean): Observable<CategoryResponse>; public categoryCreate(createCategoryDto: CreateCategoryDto, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<CategoryResponse>>; public categoryCreate(createCategoryDto: CreateCategoryDto, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<CategoryResponse>>; public categoryCreate(createCategoryDto: CreateCategoryDto, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (createCategoryDto === null || createCategoryDto === undefined) { throw new Error('Required parameter createCategoryDto was null or undefined when calling categoryCreate.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ 'application/json' ]; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected !== undefined) { headers = headers.set('Content-Type', httpContentTypeSelected); } return this.httpClient.post<CategoryResponse>(`${this.configuration.basePath}/api/category`, createCategoryDto, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 查询分类 * @param id 分类编号 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public categoryGet(id: string, observe?: 'body', reportProgress?: boolean): Observable<CategoryResponse>; public categoryGet(id: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<CategoryResponse>>; public categoryGet(id: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<CategoryResponse>>; public categoryGet(id: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling categoryGet.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<CategoryResponse>(`${this.configuration.basePath}/api/category/${encodeURIComponent(String(id))}`, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 获取分类管理界面配置信息. * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public categoryGetConfig(observe?: 'body', reportProgress?: boolean): Observable<Appearance>; public categoryGetConfig(observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Appearance>>; public categoryGetConfig(observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Appearance>>; public categoryGetConfig(observe: any = 'body', reportProgress: boolean = false ): Observable<any> { let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<Appearance>(`${this.configuration.basePath}/api/category/config`, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 查询分类数据 * @param keyword 关键词 * @param page 第几页 * @param size 页大小 * @param sort 排序 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public categoryQuery(keyword?: string, page?: number, size?: number, sort?: string, observe?: 'body', reportProgress?: boolean): Observable<PaginateCategory>; public categoryQuery(keyword?: string, page?: number, size?: number, sort?: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<PaginateCategory>>; public categoryQuery(keyword?: string, page?: number, size?: number, sort?: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<PaginateCategory>>; public categoryQuery(keyword?: string, page?: number, size?: number, sort?: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { let queryParameters = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); if (keyword !== undefined && keyword !== null) { queryParameters = queryParameters.set('keyword', <any>keyword); } if (page !== undefined && page !== null) { queryParameters = queryParameters.set('page', <any>page); } if (size !== undefined && size !== null) { queryParameters = queryParameters.set('size', <any>size); } if (sort !== undefined && sort !== null) { queryParameters = queryParameters.set('sort', <any>sort); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<PaginateCategory>(`${this.configuration.basePath}/api/category/query`, { params: queryParameters, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 删除分类 * @param id 分类编号 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public categoryRemove(id: string, observe?: 'body', reportProgress?: boolean): Observable<boolean>; public categoryRemove(id: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<boolean>>; public categoryRemove(id: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<boolean>>; public categoryRemove(id: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling categoryRemove.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'text/html' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.delete<boolean>(`${this.configuration.basePath}/api/category/${encodeURIComponent(String(id))}`, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 查询分类 * @param keyword 关键词 * @param value 已选中的分类编号 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public categorySearch(keyword?: string, value?: string, observe?: 'body', reportProgress?: boolean): Observable<Array<KeyValue>>; public categorySearch(keyword?: string, value?: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Array<KeyValue>>>; public categorySearch(keyword?: string, value?: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Array<KeyValue>>>; public categorySearch(keyword?: string, value?: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { let queryParameters = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); if (keyword !== undefined && keyword !== null) { queryParameters = queryParameters.set('keyword', <any>keyword); } if (value !== undefined && value !== null) { queryParameters = queryParameters.set('value', <any>value); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<Array<KeyValue>>(`${this.configuration.basePath}/api/category/search`, { params: queryParameters, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 查询分类 * @param keyword 关键词 * @param value 已选中的分类编号 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public categorySearchTree(keyword?: string, value?: string, observe?: 'body', reportProgress?: boolean): Observable<Array<TreeNode>>; public categorySearchTree(keyword?: string, value?: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Array<TreeNode>>>; public categorySearchTree(keyword?: string, value?: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Array<TreeNode>>>; public categorySearchTree(keyword?: string, value?: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { let queryParameters = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); if (keyword !== undefined && keyword !== null) { queryParameters = queryParameters.set('keyword', <any>keyword); } if (value !== undefined && value !== null) { queryParameters = queryParameters.set('value', <any>value); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<Array<TreeNode>>(`${this.configuration.basePath}/api/category/tree`, { params: queryParameters, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 更新分类 * @param editCategoryDto 分类参数 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public categoryUpdate(editCategoryDto: EditCategoryDto, observe?: 'body', reportProgress?: boolean): Observable<CategoryResponse>; public categoryUpdate(editCategoryDto: EditCategoryDto, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<CategoryResponse>>; public categoryUpdate(editCategoryDto: EditCategoryDto, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<CategoryResponse>>; public categoryUpdate(editCategoryDto: EditCategoryDto, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (editCategoryDto === null || editCategoryDto === undefined) { throw new Error('Required parameter editCategoryDto was null or undefined when calling categoryUpdate.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ 'application/json' ]; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected !== undefined) { headers = headers.set('Content-Type', httpContentTypeSelected); } return this.httpClient.put<CategoryResponse>(`${this.configuration.basePath}/api/category`, editCategoryDto, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 创建自定义内容 * @param createCustomDto 创建参数 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public customCreate(createCustomDto: CreateCustomDto, observe?: 'body', reportProgress?: boolean): Observable<CustomResponse>; public customCreate(createCustomDto: CreateCustomDto, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<CustomResponse>>; public customCreate(createCustomDto: CreateCustomDto, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<CustomResponse>>; public customCreate(createCustomDto: CreateCustomDto, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (createCustomDto === null || createCustomDto === undefined) { throw new Error('Required parameter createCustomDto was null or undefined when calling customCreate.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ 'application/json' ]; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected !== undefined) { headers = headers.set('Content-Type', httpContentTypeSelected); } return this.httpClient.post<CustomResponse>(`${this.configuration.basePath}/api/custom`, createCustomDto, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 查询自定义内容 * @param id 自定义内容编号 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public customGet(id: string, observe?: 'body', reportProgress?: boolean): Observable<CustomResponse>; public customGet(id: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<CustomResponse>>; public customGet(id: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<CustomResponse>>; public customGet(id: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling customGet.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<CustomResponse>(`${this.configuration.basePath}/api/custom/${encodeURIComponent(String(id))}`, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 获取自定义内容管理界面配置信息 * @param type 自定义内容集名 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public customGetConfig(type: string, observe?: 'body', reportProgress?: boolean): Observable<Appearance>; public customGetConfig(type: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Appearance>>; public customGetConfig(type: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Appearance>>; public customGetConfig(type: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (type === null || type === undefined) { throw new Error('Required parameter type was null or undefined when calling customGetConfig.'); } let queryParameters = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); if (type !== undefined && type !== null) { queryParameters = queryParameters.set('type', <any>type); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<Appearance>(`${this.configuration.basePath}/api/custom/config`, { params: queryParameters, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 查询自定义内容数据 * @param keyword 关键词 * @param category * @param type * @param page * @param size 页大小 * @param sort 排序 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public customQuery(keyword?: string, category?: string, type?: string, page?: number, size?: number, sort?: string, observe?: 'body', reportProgress?: boolean): Observable<PaginateCustom>; public customQuery(keyword?: string, category?: string, type?: string, page?: number, size?: number, sort?: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<PaginateCustom>>; public customQuery(keyword?: string, category?: string, type?: string, page?: number, size?: number, sort?: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<PaginateCustom>>; public customQuery(keyword?: string, category?: string, type?: string, page?: number, size?: number, sort?: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { let queryParameters = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); if (keyword !== undefined && keyword !== null) { queryParameters = queryParameters.set('keyword', <any>keyword); } if (category !== undefined && category !== null) { queryParameters = queryParameters.set('category', <any>category); } if (type !== undefined && type !== null) { queryParameters = queryParameters.set('type', <any>type); } if (page !== undefined && page !== null) { queryParameters = queryParameters.set('page', <any>page); } if (size !== undefined && size !== null) { queryParameters = queryParameters.set('size', <any>size); } if (sort !== undefined && sort !== null) { queryParameters = queryParameters.set('sort', <any>sort); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<PaginateCustom>(`${this.configuration.basePath}/api/custom/query`, { params: queryParameters, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 删除自定义内容 * @param id 自定义内容编号 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public customRemove(id: string, observe?: 'body', reportProgress?: boolean): Observable<boolean>; public customRemove(id: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<boolean>>; public customRemove(id: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<boolean>>; public customRemove(id: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling customRemove.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'text/html' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.delete<boolean>(`${this.configuration.basePath}/api/custom/${encodeURIComponent(String(id))}`, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 查询自定义内容 * @param keyword 关键词 * @param value 已选中的自定义内容编号 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public customSearch(keyword?: string, value?: string, observe?: 'body', reportProgress?: boolean): Observable<Array<KeyValue>>; public customSearch(keyword?: string, value?: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Array<KeyValue>>>; public customSearch(keyword?: string, value?: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Array<KeyValue>>>; public customSearch(keyword?: string, value?: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { let queryParameters = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); if (keyword !== undefined && keyword !== null) { queryParameters = queryParameters.set('keyword', <any>keyword); } if (value !== undefined && value !== null) { queryParameters = queryParameters.set('value', <any>value); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<Array<KeyValue>>(`${this.configuration.basePath}/api/custom/search`, { params: queryParameters, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 更新自定义内容 * @param editCustomDto 自定义内容参数 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public customUpdate(editCustomDto: EditCustomDto, observe?: 'body', reportProgress?: boolean): Observable<CustomResponse>; public customUpdate(editCustomDto: EditCustomDto, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<CustomResponse>>; public customUpdate(editCustomDto: EditCustomDto, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<CustomResponse>>; public customUpdate(editCustomDto: EditCustomDto, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (editCustomDto === null || editCustomDto === undefined) { throw new Error('Required parameter editCustomDto was null or undefined when calling customUpdate.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ 'application/json' ]; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected !== undefined) { headers = headers.set('Content-Type', httpContentTypeSelected); } return this.httpClient.put<CustomResponse>(`${this.configuration.basePath}/api/custom`, editCustomDto, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 创建媒体 * @param createMediaDto 创建参数 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public mediaCreate(createMediaDto: CreateMediaDto, observe?: 'body', reportProgress?: boolean): Observable<MediaResponse>; public mediaCreate(createMediaDto: CreateMediaDto, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<MediaResponse>>; public mediaCreate(createMediaDto: CreateMediaDto, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<MediaResponse>>; public mediaCreate(createMediaDto: CreateMediaDto, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (createMediaDto === null || createMediaDto === undefined) { throw new Error('Required parameter createMediaDto was null or undefined when calling mediaCreate.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ 'application/json' ]; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected !== undefined) { headers = headers.set('Content-Type', httpContentTypeSelected); } return this.httpClient.post<MediaResponse>(`${this.configuration.basePath}/api/media`, createMediaDto, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 查询媒体 * @param id 媒体编号 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public mediaGet(id: string, observe?: 'body', reportProgress?: boolean): Observable<MediaResponse>; public mediaGet(id: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<MediaResponse>>; public mediaGet(id: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<MediaResponse>>; public mediaGet(id: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling mediaGet.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<MediaResponse>(`${this.configuration.basePath}/api/media/${encodeURIComponent(String(id))}`, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 获取媒体管理界面配置信息. * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public mediaGetConfig(observe?: 'body', reportProgress?: boolean): Observable<Appearance>; public mediaGetConfig(observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Appearance>>; public mediaGetConfig(observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Appearance>>; public mediaGetConfig(observe: any = 'body', reportProgress: boolean = false ): Observable<any> { let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<Appearance>(`${this.configuration.basePath}/api/media/config`, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 查询媒体数据 * @param keyword 关键词 * @param isMedia * @param page 第几页 * @param size 页大小 * @param sort 排序 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public mediaQuery(keyword?: string, isMedia?: boolean, page?: number, size?: number, sort?: string, observe?: 'body', reportProgress?: boolean): Observable<PaginateMedia>; public mediaQuery(keyword?: string, isMedia?: boolean, page?: number, size?: number, sort?: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<PaginateMedia>>; public mediaQuery(keyword?: string, isMedia?: boolean, page?: number, size?: number, sort?: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<PaginateMedia>>; public mediaQuery(keyword?: string, isMedia?: boolean, page?: number, size?: number, sort?: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { let queryParameters = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); if (keyword !== undefined && keyword !== null) { queryParameters = queryParameters.set('keyword', <any>keyword); } if (isMedia !== undefined && isMedia !== null) { queryParameters = queryParameters.set('isMedia', <any>isMedia); } if (page !== undefined && page !== null) { queryParameters = queryParameters.set('page', <any>page); } if (size !== undefined && size !== null) { queryParameters = queryParameters.set('size', <any>size); } if (sort !== undefined && sort !== null) { queryParameters = queryParameters.set('sort', <any>sort); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<PaginateMedia>(`${this.configuration.basePath}/api/media/query`, { params: queryParameters, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 删除媒体 * @param id 媒体编号 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public mediaRemove(id: string, observe?: 'body', reportProgress?: boolean): Observable<boolean>; public mediaRemove(id: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<boolean>>; public mediaRemove(id: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<boolean>>; public mediaRemove(id: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling mediaRemove.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'text/html' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.delete<boolean>(`${this.configuration.basePath}/api/media/${encodeURIComponent(String(id))}`, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 查询媒体 * @param keyword 关键词 * @param value 已选中的媒体编号 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public mediaSearch(keyword?: string, value?: string, observe?: 'body', reportProgress?: boolean): Observable<Array<KeyValue>>; public mediaSearch(keyword?: string, value?: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Array<KeyValue>>>; public mediaSearch(keyword?: string, value?: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Array<KeyValue>>>; public mediaSearch(keyword?: string, value?: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { let queryParameters = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); if (keyword !== undefined && keyword !== null) { queryParameters = queryParameters.set('keyword', <any>keyword); } if (value !== undefined && value !== null) { queryParameters = queryParameters.set('value', <any>value); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<Array<KeyValue>>(`${this.configuration.basePath}/api/media/search`, { params: queryParameters, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 更新媒体 * @param editMediaDto 媒体参数 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public mediaUpdate(editMediaDto: EditMediaDto, observe?: 'body', reportProgress?: boolean): Observable<MediaResponse>; public mediaUpdate(editMediaDto: EditMediaDto, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<MediaResponse>>; public mediaUpdate(editMediaDto: EditMediaDto, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<MediaResponse>>; public mediaUpdate(editMediaDto: EditMediaDto, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (editMediaDto === null || editMediaDto === undefined) { throw new Error('Required parameter editMediaDto was null or undefined when calling mediaUpdate.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ 'application/json' ]; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected !== undefined) { headers = headers.set('Content-Type', httpContentTypeSelected); } return this.httpClient.put<MediaResponse>(`${this.configuration.basePath}/api/media`, editMediaDto, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 创建页面 * @param createPageDto 创建参数 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public pageCreate(createPageDto: CreatePageDto, observe?: 'body', reportProgress?: boolean): Observable<PageResponse>; public pageCreate(createPageDto: CreatePageDto, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<PageResponse>>; public pageCreate(createPageDto: CreatePageDto, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<PageResponse>>; public pageCreate(createPageDto: CreatePageDto, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (createPageDto === null || createPageDto === undefined) { throw new Error('Required parameter createPageDto was null or undefined when calling pageCreate.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ 'application/json' ]; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected !== undefined) { headers = headers.set('Content-Type', httpContentTypeSelected); } return this.httpClient.post<PageResponse>(`${this.configuration.basePath}/api/page`, createPageDto, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 查询页面 * @param id 页面编号 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public pageGet(id: string, observe?: 'body', reportProgress?: boolean): Observable<PageResponse>; public pageGet(id: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<PageResponse>>; public pageGet(id: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<PageResponse>>; public pageGet(id: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling pageGet.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<PageResponse>(`${this.configuration.basePath}/api/page/${encodeURIComponent(String(id))}`, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 获取页面管理界面配置信息. * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public pageGetConfig(observe?: 'body', reportProgress?: boolean): Observable<Appearance>; public pageGetConfig(observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Appearance>>; public pageGetConfig(observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Appearance>>; public pageGetConfig(observe: any = 'body', reportProgress: boolean = false ): Observable<any> { let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<Appearance>(`${this.configuration.basePath}/api/page/config`, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 查询页面数据 * @param keyword 关键词 * @param page 第几页 * @param size 页大小 * @param sort 排序 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public pageQuery(keyword?: string, page?: number, size?: number, sort?: string, observe?: 'body', reportProgress?: boolean): Observable<PaginatePage>; public pageQuery(keyword?: string, page?: number, size?: number, sort?: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<PaginatePage>>; public pageQuery(keyword?: string, page?: number, size?: number, sort?: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<PaginatePage>>; public pageQuery(keyword?: string, page?: number, size?: number, sort?: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { let queryParameters = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); if (keyword !== undefined && keyword !== null) { queryParameters = queryParameters.set('keyword', <any>keyword); } if (page !== undefined && page !== null) { queryParameters = queryParameters.set('page', <any>page); } if (size !== undefined && size !== null) { queryParameters = queryParameters.set('size', <any>size); } if (sort !== undefined && sort !== null) { queryParameters = queryParameters.set('sort', <any>sort); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<PaginatePage>(`${this.configuration.basePath}/api/page/query`, { params: queryParameters, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 删除页面 * @param id 页面编号 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public pageRemove(id: string, observe?: 'body', reportProgress?: boolean): Observable<boolean>; public pageRemove(id: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<boolean>>; public pageRemove(id: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<boolean>>; public pageRemove(id: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling pageRemove.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'text/html' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.delete<boolean>(`${this.configuration.basePath}/api/page/${encodeURIComponent(String(id))}`, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 查询页面 * @param keyword 关键词 * @param value 已选中的页面编号 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public pageSearch(keyword?: string, value?: string, observe?: 'body', reportProgress?: boolean): Observable<Array<KeyValue>>; public pageSearch(keyword?: string, value?: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Array<KeyValue>>>; public pageSearch(keyword?: string, value?: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Array<KeyValue>>>; public pageSearch(keyword?: string, value?: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { let queryParameters = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); if (keyword !== undefined && keyword !== null) { queryParameters = queryParameters.set('keyword', <any>keyword); } if (value !== undefined && value !== null) { queryParameters = queryParameters.set('value', <any>value); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<Array<KeyValue>>(`${this.configuration.basePath}/api/page/search`, { params: queryParameters, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 更新页面 * @param editPageDto 页面参数 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public pageUpdate(editPageDto: EditPageDto, observe?: 'body', reportProgress?: boolean): Observable<PageResponse>; public pageUpdate(editPageDto: EditPageDto, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<PageResponse>>; public pageUpdate(editPageDto: EditPageDto, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<PageResponse>>; public pageUpdate(editPageDto: EditPageDto, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (editPageDto === null || editPageDto === undefined) { throw new Error('Required parameter editPageDto was null or undefined when calling pageUpdate.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ 'application/json' ]; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected !== undefined) { headers = headers.set('Content-Type', httpContentTypeSelected); } return this.httpClient.put<PageResponse>(`${this.configuration.basePath}/api/page`, editPageDto, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 创建小部件 * @param createWidgetDto 创建参数 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public widgetCreate(createWidgetDto: CreateWidgetDto, observe?: 'body', reportProgress?: boolean): Observable<WidgetResponse>; public widgetCreate(createWidgetDto: CreateWidgetDto, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<WidgetResponse>>; public widgetCreate(createWidgetDto: CreateWidgetDto, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<WidgetResponse>>; public widgetCreate(createWidgetDto: CreateWidgetDto, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (createWidgetDto === null || createWidgetDto === undefined) { throw new Error('Required parameter createWidgetDto was null or undefined when calling widgetCreate.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ 'application/json' ]; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected !== undefined) { headers = headers.set('Content-Type', httpContentTypeSelected); } return this.httpClient.post<WidgetResponse>(`${this.configuration.basePath}/api/widget`, createWidgetDto, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 查询小部件 * @param id 小部件编号 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public widgetGet(id: string, observe?: 'body', reportProgress?: boolean): Observable<WidgetResponse>; public widgetGet(id: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<WidgetResponse>>; public widgetGet(id: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<WidgetResponse>>; public widgetGet(id: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling widgetGet.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<WidgetResponse>(`${this.configuration.basePath}/api/widget/${encodeURIComponent(String(id))}`, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 获取小部件管理界面配置信息. * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public widgetGetConfig(observe?: 'body', reportProgress?: boolean): Observable<Appearance>; public widgetGetConfig(observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Appearance>>; public widgetGetConfig(observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Appearance>>; public widgetGetConfig(observe: any = 'body', reportProgress: boolean = false ): Observable<any> { let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<Appearance>(`${this.configuration.basePath}/api/widget/config`, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 查询小部件数据 * @param keyword 关键词 * @param isWidget * @param page 第几页 * @param size 页大小 * @param sort 排序 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public widgetQuery(keyword?: string, isWidget?: boolean, page?: number, size?: number, sort?: string, observe?: 'body', reportProgress?: boolean): Observable<PaginateWidget>; public widgetQuery(keyword?: string, isWidget?: boolean, page?: number, size?: number, sort?: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<PaginateWidget>>; public widgetQuery(keyword?: string, isWidget?: boolean, page?: number, size?: number, sort?: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<PaginateWidget>>; public widgetQuery(keyword?: string, isWidget?: boolean, page?: number, size?: number, sort?: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { let queryParameters = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); if (keyword !== undefined && keyword !== null) { queryParameters = queryParameters.set('keyword', <any>keyword); } if (isWidget !== undefined && isWidget !== null) { queryParameters = queryParameters.set('isWidget', <any>isWidget); } if (page !== undefined && page !== null) { queryParameters = queryParameters.set('page', <any>page); } if (size !== undefined && size !== null) { queryParameters = queryParameters.set('size', <any>size); } if (sort !== undefined && sort !== null) { queryParameters = queryParameters.set('sort', <any>sort); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<PaginateWidget>(`${this.configuration.basePath}/api/widget/query`, { params: queryParameters, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 删除小部件 * @param id 小部件编号 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public widgetRemove(id: string, observe?: 'body', reportProgress?: boolean): Observable<boolean>; public widgetRemove(id: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<boolean>>; public widgetRemove(id: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<boolean>>; public widgetRemove(id: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling widgetRemove.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'text/html' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.delete<boolean>(`${this.configuration.basePath}/api/widget/${encodeURIComponent(String(id))}`, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 查询小部件 * @param keyword 关键词 * @param value 已选中的小部件编号 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public widgetSearch(keyword?: string, value?: string, observe?: 'body', reportProgress?: boolean): Observable<Array<KeyValue>>; public widgetSearch(keyword?: string, value?: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<Array<KeyValue>>>; public widgetSearch(keyword?: string, value?: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<Array<KeyValue>>>; public widgetSearch(keyword?: string, value?: string, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { let queryParameters = new HttpParams({encoder: new CustomHttpUrlEncodingCodec()}); if (keyword !== undefined && keyword !== null) { queryParameters = queryParameters.set('keyword', <any>keyword); } if (value !== undefined && value !== null) { queryParameters = queryParameters.set('value', <any>value); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ ]; return this.httpClient.get<Array<KeyValue>>(`${this.configuration.basePath}/api/widget/search`, { params: queryParameters, withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } /** * * 更新小部件 * @param editWidgetDto 小部件参数 * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. * @param reportProgress flag to report request and response progress. */ public widgetUpdate(editWidgetDto: EditWidgetDto, observe?: 'body', reportProgress?: boolean): Observable<WidgetResponse>; public widgetUpdate(editWidgetDto: EditWidgetDto, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<WidgetResponse>>; public widgetUpdate(editWidgetDto: EditWidgetDto, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<WidgetResponse>>; public widgetUpdate(editWidgetDto: EditWidgetDto, observe: any = 'body', reportProgress: boolean = false ): Observable<any> { if (editWidgetDto === null || editWidgetDto === undefined) { throw new Error('Required parameter editWidgetDto was null or undefined when calling widgetUpdate.'); } let headers = this.defaultHeaders; // to determine the Accept header let httpHeaderAccepts: string[] = [ 'application/json' ]; const httpHeaderAcceptSelected: string | undefined = this.configuration.selectHeaderAccept(httpHeaderAccepts); if (httpHeaderAcceptSelected !== undefined) { headers = headers.set('Accept', httpHeaderAcceptSelected); } // to determine the Content-Type header const consumes: string[] = [ 'application/json' ]; const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); if (httpContentTypeSelected !== undefined) { headers = headers.set('Content-Type', httpContentTypeSelected); } return this.httpClient.put<WidgetResponse>(`${this.configuration.basePath}/api/widget`, editWidgetDto, { withCredentials: this.configuration.withCredentials, headers: headers, observe: observe, reportProgress: reportProgress } ); } }
the_stack
import { Channel, Committer, Discoverer, DiscoveryService, Endorsement, Endorser, IdentityContext, Endpoint, Client } from 'fabric-common'; import * as protos from 'fabric-protos'; import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import * as chaiAsPromised from 'chai-as-promised'; import * as path from 'path'; import { Gateway, Wallet, Wallets, X509Identity } from 'fabric-network'; import * as sinon from 'sinon'; import { DefinedSmartContract, LifecycleChannel, SmartContractDefinitionOptions } from '../src/LifecycleChannel'; import { Lifecycle } from '../src/Lifecycle'; import { EndorsementPolicy } from '../src/Policy'; import { Collection } from '../src'; import { CollectionConfig } from '../src/CollectionConfig'; // this is horrible but needed as the transaction constructor isn't exported so can't stub it without stubbing the world // tslint:disable-next-line:no-var-requires import { Transaction } from 'fabric-network/lib/transaction' chai.should(); chai.use(sinonChai); chai.use(chaiAsPromised); const should: Chai.Should = chai.should(); // tslint:disable:no-unused-expression describe('LifecycleChannel', () => { let wallet: Wallet; let channel: LifecycleChannel; let lifecycle: Lifecycle; before(async () => { wallet = await Wallets.newFileSystemWallet(path.join(__dirname, 'tmp', 'wallet')); const peerOrg1Identity: X509Identity = { credentials: { certificate: '-----BEGIN CERTIFICATE-----\n' + 'MIICujCCAmGgAwIBAgIUUOge6hz++rKSbrV1Ya2t/kcC3s0wCgYIKoZIzj0EAwIw\n' + 'cDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\n' + 'EwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\n' + 'Lm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE3MTU0NzAwWhcNMjEwMzE3MTU1MjAw\n' + 'WjBgMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExFDASBgNV\n' + 'BAoTC0h5cGVybGVkZ2VyMQ4wDAYDVQQLEwVhZG1pbjESMBAGA1UEAxMJb3JnMWFk\n' + 'bWluMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEoELj0ASt7TpEAUNJjPkG7zNY\n' + 'wLMP3LDsFc38rWKm6ZRGtJIQ5k7jcoXXScuhS1YuRop/xKAvOhiLbd1hyo7fAqOB\n' + '6DCB5TAOBgNVHQ8BAf8EBAMCB4AwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQUEKQz\n' + 'qJPP/lPsRO7BizDnjJptylswHwYDVR0jBBgwFoAUSS9NU/qBB+Wx0R7PispddLmZ\n' + 'fd0wKAYDVR0RBCEwH4IdQ2Fyb2xpbmVzLU1hY0Jvb2stUHJvLTMubG9jYWwwWwYI\n' + 'KgMEBQYHCAEET3siYXR0cnMiOnsiaGYuQWZmaWxpYXRpb24iOiIiLCJoZi5FbnJv\n' + 'bGxtZW50SUQiOiJvcmcxYWRtaW4iLCJoZi5UeXBlIjoiYWRtaW4ifX0wCgYIKoZI\n' + 'zj0EAwIDRwAwRAIgHhpQYEAtQ9rPhvh4Wer3hKtuq7FChoqJWkj9rNdnbIkCIC4I\n' + 'GzjjS7hZRKsETRvIT3LRFTZJLJq6AcGOtepFso/n\n' + '-----END CERTIFICATE-----', privateKey: '-----BEGIN PRIVATE KEY-----\n' + 'MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgvprUzTpK7GBMXVvI\n' + 'NOlGgxyqqi1TM6CA63qNK8PTwfihRANCAASgQuPQBK3tOkQBQ0mM+QbvM1jAsw/c\n' + 'sOwVzfytYqbplEa0khDmTuNyhddJy6FLVi5Gin/EoC86GItt3WHKjt8C\n' + '-----END PRIVATE KEY-----', }, mspId: `myMSPID`, type: 'X.509', }; await wallet.put('myIdentity', peerOrg1Identity); lifecycle = new Lifecycle(); lifecycle.addPeer({ url: 'grpcs://localhost:7051', mspid: 'myMSPID', name: 'myPeer', requestTimeout: 70000, pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n' }); lifecycle.addPeer({ url: 'grpc://localhost:8051', mspid: 'myMSPID', name: 'myPeer2', sslTargetNameOverride: 'localhost', apiOptions: { 'grpc.some_setting': 'maximum power' } }); lifecycle.addOrderer({ name: 'myOrderer', url: 'grpcs://localhost:7050', pem: '-----BEGIN CERTIFICATE-----\\nMIICJjCCAc2gAwIBAgIURY9F2Rt0JqOtiHbNJ6rRgfiDy2EwCgYIKoZIzj0EAwIw\\ncDELMAkGA1UEBhMCVVMxFzAVBgNVBAgTDk5vcnRoIENhcm9saW5hMQ8wDQYDVQQH\\nEwZEdXJoYW0xGTAXBgNVBAoTEG9yZzEuZXhhbXBsZS5jb20xHDAaBgNVBAMTE2Nh\\nLm9yZzEuZXhhbXBsZS5jb20wHhcNMjAwMzE2MTQ1MDAwWhcNMzUwMzEzMTQ1MDAw\\nWjBwMQswCQYDVQQGEwJVUzEXMBUGA1UECBMOTm9ydGggQ2Fyb2xpbmExDzANBgNV\\nBAcTBkR1cmhhbTEZMBcGA1UEChMQb3JnMS5leGFtcGxlLmNvbTEcMBoGA1UEAxMT\\nY2Eub3JnMS5leGFtcGxlLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABHic\\nzHXBRqfe7elvQ8zuxIwigOFCuk/49bjChQxf19fL/qHBLYLOXgd3Ox5jTVyyLuO/\\nf9x19piTv7gVgv8h7BijRTBDMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAG\\nAQH/AgEBMB0GA1UdDgQWBBRGw4tXsbZSI45NZNTsDT7rssJpzjAKBggqhkjOPQQD\\nAgNHADBEAiBWNIFkaageeAiEMmhauY3bTHoG45Wgjk99CjHZ6KJoTgIgMfKc9mBL\\na5JHbGNB/gsBhxIm8/akE6g+SikIz/JGty4=\\n-----END CERTIFICATE-----\\n"\n' }); channel = new LifecycleChannel(lifecycle, 'mychannel', wallet, 'myIdentity'); }); describe(`constructor`, () => { it('should create a LifecycleChannel instance', () => { channel['lifecycle'].should.deep.equal(lifecycle); channel['channelName'].should.equal('mychannel'); channel['wallet'].should.deep.equal(wallet); channel['identity'].should.equal('myIdentity'); }); }); describe('fabric functions', () => { describe('submitTransaction', () => { let mysandbox: sinon.SinonSandbox; // let gatewayConnectSpy: sinon.SinonSpy; let transactionSetEndorsingPeersSpy: sinon.SinonSpy; let transactionSubmitStub: sinon.SinonStub; let addEndorserStub: sinon.SinonStub; let addCommitterStub: sinon.SinonStub; let getEndorsersStub: sinon.SinonStub; let protoArgs: protos.lifecycle.IApproveChaincodeDefinitionForMyOrgArgs = {}; beforeEach(() => { mysandbox = sinon.createSandbox(); mysandbox.stub(Endorser.prototype, 'connect').resolves(); mysandbox.stub(Discoverer.prototype, 'connect').resolves(); mysandbox.stub(Committer.prototype, 'connect').resolves(); protoArgs.name = 'myContract'; protoArgs.version = '0.0.1'; protoArgs.sequence = 1; const local: protos.lifecycle.ChaincodeSource.Local = new protos.lifecycle.ChaincodeSource.Local(); local.package_id = 'myPackageId'; const source: protos.lifecycle.ChaincodeSource = new protos.lifecycle.ChaincodeSource(); source.local_package = local; protoArgs.source = source; // @ts-ignore mysandbox.spy(Gateway.prototype, 'connect'); // @ts-ignore getEndorsersStub = mysandbox.stub(Channel.prototype, 'getEndorsers').returns([{ name: 'myPeer' }, { name: 'myPeer2' }, { name: 'myPeer:7051' }, { name: 'peer0.org2.example.com:9051' }]); mysandbox.stub(DiscoveryService.prototype, 'build'); mysandbox.stub(DiscoveryService.prototype, 'sign'); mysandbox.stub(DiscoveryService.prototype, 'send').resolves(); addEndorserStub = mysandbox.stub(Channel.prototype, 'addEndorser'); addCommitterStub = mysandbox.stub(Channel.prototype, 'addCommitter'); transactionSetEndorsingPeersSpy = mysandbox.spy(Transaction.prototype, 'setEndorsingPeers'); transactionSubmitStub = mysandbox.stub(Transaction.prototype, 'submit'); }); afterEach(() => { mysandbox.restore(); protoArgs = {}; }); it('should handle no peerNames set', async () => { // @ts-ignore await channel.submitTransaction([], 'myOrderer', { packageId: 'myPackageId', sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1', }).should.eventually.be.rejectedWith('parameter peers was missing or empty array'); }); it('should handle no orderer set (grpc)', async () => { const newEndpointSpy: sinon.SinonSpy = mysandbox.spy(Client.prototype, 'newEndpoint'); // @ts-ignore getEndorsersStub.returns([ { name: 'myPeer', endpoint: {protocol: 'grpc'} }, { name: 'myPeer2', endpoint: {protocol: 'grpc'} }, { name: 'myPeer:7051', endpoint: {protocol: 'grpc'} }, { name: 'peer0.org2.example.com:9051', endpoint: {protocol: 'grpc'} }] as Endorser[]); const discoverChannelStub: sinon.SinonStub = mysandbox.stub(channel, 'discoverChannel').resolves( { msps: { osmsp: { tlsRootCerts: 'tlsRootCert', tlsIntermediateCerts: 'tlsIntermediateCert' }, org1msp: { } }, orderers: { osmsp: { endpoints: [ { host: 'host', name: 'host:1000', port: 1000 } ] } }, peers_by_org: { }, timestamp: 123456789 } ) // @ts-ignore await channel.submitTransaction(['myPeer'], undefined, { packageId: 'myPackageId', sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1', }, 'approve'); discoverChannelStub.should.have.been.calledWith(['myPeer']) newEndpointSpy.should.have.been.calledWithExactly({ url: 'grpc://host:1000' }) }); it('should handle no orderer set (grpcs with tlsIntermediate cert)', async () => { const newEndpointSpy: sinon.SinonSpy = mysandbox.spy(Client.prototype, 'newEndpoint'); // @ts-ignore getEndorsersStub.returns([ { name: 'myPeer', endpoint: {protocol: 'grpcs'} }, { name: 'myPeer2', endpoint: {protocol: 'grpcs'} }, { name: 'myPeer:7051', endpoint: {protocol: 'grpcs'} }, { name: 'peer0.org2.example.com:9051', endpoint: {protocol: 'grpcs'} }] as Endorser[]); const discoverChannelStub: sinon.SinonStub = mysandbox.stub(channel, 'discoverChannel').resolves( { msps: { osmsp: { tlsRootCerts: 'tlsRootCert', tlsIntermediateCerts: 'tlsIntermediateCert' }, org1msp: { } }, orderers: { osmsp: { endpoints: [ { host: 'host', name: 'host:1000', port: 1000 } ] } }, peers_by_org: { }, timestamp: 123456789 } ) // @ts-ignore await channel.submitTransaction(['myPeer'], undefined, { packageId: 'myPackageId', sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1', }, 'approve'); discoverChannelStub.should.have.been.calledWith(['myPeer']) newEndpointSpy.should.have.been.calledWithExactly({ url: 'grpcs://host:1000', pem: 'tlsRootCert\ntlsIntermediateCert' }) }); it('should handle no orderer set (grpcs without tlsIntermediate cert)', async () => { const newEndpointSpy: sinon.SinonSpy = mysandbox.spy(Client.prototype, 'newEndpoint'); // @ts-ignore getEndorsersStub.returns([ { name: 'myPeer', endpoint: {protocol: 'grpcs'} }, { name: 'myPeer2', endpoint: {protocol: 'grpcs'} }, { name: 'myPeer:7051', endpoint: {protocol: 'grpcs'} }, { name: 'peer0.org2.example.com:9051', endpoint: {protocol: 'grpcs'} }] as Endorser[]); const discoverChannelStub: sinon.SinonStub = mysandbox.stub(channel, 'discoverChannel').resolves( { msps: { osmsp: { tlsRootCerts: 'tlsRootCert', tlsIntermediateCerts: '' }, org1msp: { } }, orderers: { osmsp: { endpoints: [ { host: 'host', name: 'host:1000', port: 1000 } ] } }, peers_by_org: { }, timestamp: 123456789 } ); // @ts-ignore await channel.submitTransaction(['myPeer'], undefined, { packageId: 'myPackageId', sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1', }, 'approve'); discoverChannelStub.should.have.been.calledWith(['myPeer']) newEndpointSpy.should.have.been.calledWithExactly({ url: 'grpcs://host:1000', pem: 'tlsRootCert' }) }); it('should handle no orderers being discovered', async () => { const newEndpointSpy: sinon.SinonSpy = mysandbox.spy(Client.prototype, 'newEndpoint'); // @ts-ignore getEndorsersStub.returns([ { name: 'myPeer', endpoint: {protocol: 'grpcs'} }, { name: 'myPeer2', endpoint: {protocol: 'grpcs'} }, { name: 'myPeer:7051', endpoint: {protocol: 'grpcs'} }, { name: 'peer0.org2.example.com:9051', endpoint: {protocol: 'grpcs'} }] as Endorser[]); const discoverChannelStub: sinon.SinonStub = mysandbox.stub(channel, 'discoverChannel').resolves( { msps: { osmsp: { tlsRootCerts: 'tlsRootCert', tlsIntermediateCerts: '' }, org1msp: { } }, orderers: { }, peers_by_org: { }, timestamp: 123456789 } ); // @ts-ignore await channel.submitTransaction(['myPeer'], undefined, { packageId: 'myPackageId', sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1', }, 'approve').should.be.rejectedWith(/Unable to discover any orderers./); discoverChannelStub.should.have.been.calledWith(['myPeer']) newEndpointSpy.should.not.have.been.calledWithExactly({ url: 'grpcs://host:1000', pem: 'tlsRootCert' }) }); it('should handle no options set', async () => { // @ts-ignore await channel.submitTransaction(['myPeer'], 'myOrderer', undefined).should.eventually.be.rejectedWith('parameter options is missing'); }); it('should handle no sequence set', async () => { // @ts-ignore await channel.submitTransaction(['myPeer'], 'myOrderer', { packageId: 'myPackageId', smartContractName: 'myContract', smartContractVersion: '0.0.1', }).should.eventually.be.rejectedWith('missing option sequence'); }); it('should handle no smartContractName set', async () => { // @ts-ignore await channel.submitTransaction(['myPeer'], 'myOrderer', { packageId: 'myPackageId', sequence: 1, smartContractVersion: '0.0.1', }).should.eventually.be.rejectedWith('missing option smartContractName'); }); it('should handle no smartContractVersion set', async () => { // @ts-ignore await channel.submitTransaction(['myPeer'], 'myOrderer', { packageId: 'myPackageId', sequence: 1, smartContractName: 'myContract', }).should.eventually.be.rejectedWith('missing option smartContractVersion'); }); it('should handle error from submit', async () => { transactionSubmitStub.rejects({ message: 'some error' }); const arg: Uint8Array = protos.lifecycle.ApproveChaincodeDefinitionForMyOrgArgs.encode(protoArgs).finish(); await channel.submitTransaction(['myPeer'], 'myOrderer', { packageId: 'myPackageId', sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1' }, 'approve').should.eventually.be.rejectedWith('Could not approve smart contract definition, received error: some error'); addEndorserStub.should.have.been.calledWith(sinon.match.instanceOf(Endorser)); addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }]); transactionSubmitStub.should.have.been.calledWith(Buffer.from(arg)); }); it('should handle error from not finding peer', async () => { await channel.approveSmartContractDefinition(['myPeer', 'peer.does.not.exist:5060'], 'myOrderer', { sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1' }).should.eventually.be.rejectedWith('Could not approve smart contract definition, received error: Could not find peer peer.does.not.exist:5060 in discovered peers'); }); }); describe('approveSmartContractDefinition', () => { let mysandbox: sinon.SinonSandbox; let gatewayConnectSpy: sinon.SinonSpy; let transactionSetEndorsingPeersSpy: sinon.SinonSpy; let transactionSubmitStub: sinon.SinonStub; let addEndorserStub: sinon.SinonStub; let addCommitterStub: sinon.SinonStub; let protoArgs: protos.lifecycle.IApproveChaincodeDefinitionForMyOrgArgs = {}; beforeEach(() => { mysandbox = sinon.createSandbox(); mysandbox.stub(Endorser.prototype, 'connect').resolves(); mysandbox.stub(Discoverer.prototype, 'connect').resolves(); mysandbox.stub(Committer.prototype, 'connect').resolves(); protoArgs.name = 'myContract'; protoArgs.version = '0.0.1'; protoArgs.sequence = 1; const local: protos.lifecycle.ChaincodeSource.Local = new protos.lifecycle.ChaincodeSource.Local(); local.package_id = 'myPackageId'; const source: protos.lifecycle.ChaincodeSource = new protos.lifecycle.ChaincodeSource(); source.local_package = local; protoArgs.source = source; addEndorserStub = mysandbox.stub(Channel.prototype, 'addEndorser'); addCommitterStub = mysandbox.stub(Channel.prototype, 'addCommitter'); // @ts-ignore mysandbox.stub(Channel.prototype, 'getEndorsers').returns([{ name: 'myPeer' }, { name: 'myPeer2' }, { name: 'myPeer:7051' }, { name: 'peer0.org2.example.com:9051' }]); gatewayConnectSpy = mysandbox.spy(Gateway.prototype, 'connect'); mysandbox.stub(DiscoveryService.prototype, 'build'); mysandbox.stub(DiscoveryService.prototype, 'sign'); mysandbox.stub(DiscoveryService.prototype, 'send').resolves(); transactionSetEndorsingPeersSpy = mysandbox.spy(Transaction.prototype, 'setEndorsingPeers'); transactionSubmitStub = mysandbox.stub(Transaction.prototype, 'submit'); }); afterEach(() => { mysandbox.restore(); protoArgs = {}; }); it('should approve a smart contract definition', async () => { const arg: Uint8Array = protos.lifecycle.ApproveChaincodeDefinitionForMyOrgArgs.encode(protoArgs).finish(); await channel.approveSmartContractDefinition(['myPeer'], 'myOrderer', { packageId: 'myPackageId', sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1' }); addEndorserStub.should.have.been.calledWith(sinon.match.instanceOf(Endorser)); addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }]); transactionSubmitStub.should.have.been.calledWith(Buffer.from(arg)); }); it('should approve a smart contract definition with timeout set', async () => { const arg: Uint8Array = protos.lifecycle.ApproveChaincodeDefinitionForMyOrgArgs.encode(protoArgs).finish(); await channel.approveSmartContractDefinition(['myPeer2'], 'myOrderer', { packageId: 'myPackageId', sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1' }, 1234); addEndorserStub.should.have.been.calledWith(sinon.match.instanceOf(Endorser)); addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); const call: sinon.SinonSpyCall = gatewayConnectSpy.getCall(0); call.args[1].eventHandlerOptions.should.deep.equal({ commitTimeout: 1234, endorseTimeout: 1234 }); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer2' }]); transactionSubmitStub.should.have.been.calledWith(Buffer.from(arg)); }); it('should approve a smart contract definition and set initRequired if set', async () => { protoArgs.init_required = true; const arg: Uint8Array = protos.lifecycle.ApproveChaincodeDefinitionForMyOrgArgs.encode(protoArgs).finish(); await channel.approveSmartContractDefinition(['myPeer'], 'myOrderer', { packageId: 'myPackageId', sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1', initRequired: true }); addEndorserStub.should.have.been.calledWith(sinon.match.instanceOf(Endorser)); addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }]); transactionSubmitStub.should.have.been.calledWith(Buffer.from(arg)); }); it('should approve a smart contract definition handle no packageId', async () => { const unavailable: protos.lifecycle.ChaincodeSource.Unavailable = new protos.lifecycle.ChaincodeSource.Unavailable(); const source: protos.lifecycle.ChaincodeSource = new protos.lifecycle.ChaincodeSource(); source.unavailable = unavailable; protoArgs.source = source; const arg: Uint8Array = protos.lifecycle.ApproveChaincodeDefinitionForMyOrgArgs.encode(protoArgs).finish(); await channel.approveSmartContractDefinition(['myPeer'], 'myOrderer', { sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1', }); addEndorserStub.should.have.been.calledWith(sinon.match.instanceOf(Endorser)); addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }]); transactionSubmitStub.should.have.been.calledWith(Buffer.from(arg)); }); it('should approve a smart contract definition with endorsement plugin', async () => { protoArgs.endorsement_plugin = 'myPlugin'; const arg: Uint8Array = protos.lifecycle.ApproveChaincodeDefinitionForMyOrgArgs.encode(protoArgs).finish(); await channel.approveSmartContractDefinition(['myPeer'], 'myOrderer', { packageId: 'myPackageId', sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1', endorsementPlugin: 'myPlugin' }); addEndorserStub.should.have.been.calledWith(sinon.match.instanceOf(Endorser)); addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }]); transactionSubmitStub.should.have.been.calledWith(Buffer.from(arg)); }); it('should approve a smart contract definition with validation plugin', async () => { protoArgs.validation_plugin = 'myPlugin'; const arg: Uint8Array = protos.lifecycle.ApproveChaincodeDefinitionForMyOrgArgs.encode(protoArgs).finish(); await channel.approveSmartContractDefinition(['myPeer'], 'myOrderer', { packageId: 'myPackageId', sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1', validationPlugin: 'myPlugin' }); addEndorserStub.should.have.been.calledWith(sinon.match.instanceOf(Endorser)); addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }]); transactionSubmitStub.should.have.been.calledWith(Buffer.from(arg)); }); it('should approve a smart contract definition with endorsement policy', async () => { const policyString: string = `AND('org1.member', 'org2.member')`; const policy: EndorsementPolicy = new EndorsementPolicy(); const policyResult: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(policyString); const applicationPolicy: protos.common.IApplicationPolicy = {}; applicationPolicy.signature_policy = policyResult; const policyBuffer: Buffer = Buffer.from(protos.common.ApplicationPolicy.encode(applicationPolicy).finish()); protoArgs.validation_parameter = policyBuffer; const arg: Uint8Array = protos.lifecycle.ApproveChaincodeDefinitionForMyOrgArgs.encode(protoArgs).finish(); await channel.approveSmartContractDefinition(['myPeer'], 'myOrderer', { packageId: 'myPackageId', sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1', endorsementPolicy: policyString }); addEndorserStub.should.have.been.calledWith(sinon.match.instanceOf(Endorser)); addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }]); transactionSubmitStub.should.have.been.calledWith(Buffer.from(arg)); }); it('should approve a smart contract definition with collection config', async () => { const collectionConfig: Collection[] = [ { name: 'CollectionOne', policy: `OR('Org1MSP.member')`, requiredPeerCount: 1, maxPeerCount: 1, blockToLive: 0, memberOnlyRead: true } ]; protoArgs.collections = CollectionConfig.buildCollectionConfigPackage(collectionConfig); const arg: Uint8Array = protos.lifecycle.ApproveChaincodeDefinitionForMyOrgArgs.encode(protoArgs).finish(); await channel.approveSmartContractDefinition(['myPeer'], 'myOrderer', { packageId: 'myPackageId', sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1', collectionConfig: collectionConfig }); addEndorserStub.should.have.been.calledWith(sinon.match.instanceOf(Endorser)); addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }]); transactionSubmitStub.should.have.been.calledWith(Buffer.from(arg)); }); }); describe('commitSmartContractDefinition', () => { let mysandbox: sinon.SinonSandbox; let gatewayConnectSpy: sinon.SinonSpy; let transactionSetEndorsingPeersSpy: sinon.SinonSpy; let transactionSubmitStub: sinon.SinonStub; let addEndorserStub: sinon.SinonStub; let addCommitterStub: sinon.SinonStub; let protoArgs: protos.lifecycle.ICommitChaincodeDefinitionArgs = {}; beforeEach(() => { mysandbox = sinon.createSandbox(); mysandbox.stub(Endorser.prototype, 'connect').resolves(); mysandbox.stub(Discoverer.prototype, 'connect').resolves(); mysandbox.stub(Committer.prototype, 'connect').resolves(); protoArgs.name = 'myContract'; protoArgs.version = '0.0.1'; protoArgs.sequence = 1; addEndorserStub = mysandbox.stub(Channel.prototype, 'addEndorser'); addCommitterStub = mysandbox.stub(Channel.prototype, 'addCommitter'); // @ts-ignore mysandbox.stub(Channel.prototype, 'getEndorsers').returns([{ name: 'myPeer' }, { name: 'myPeer:7051' }, { name: 'peer0.org2.example.com:9051' }]); gatewayConnectSpy = mysandbox.spy(Gateway.prototype, 'connect'); mysandbox.stub(DiscoveryService.prototype, 'build'); mysandbox.stub(DiscoveryService.prototype, 'sign'); mysandbox.stub(DiscoveryService.prototype, 'send').resolves(); transactionSetEndorsingPeersSpy = mysandbox.spy(Transaction.prototype, 'setEndorsingPeers'); transactionSubmitStub = mysandbox.stub(Transaction.prototype, 'submit'); }); afterEach(() => { mysandbox.restore(); protoArgs = {}; }); it('should commit a smart contract definition', async () => { const arg: Uint8Array = protos.lifecycle.CommitChaincodeDefinitionArgs.encode(protoArgs).finish(); await channel.commitSmartContractDefinition(['myPeer', 'peer0.org2.example.com:9051'], 'myOrderer', { sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1' }); addEndorserStub.should.have.been.calledOnce; addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }, { name: 'peer0.org2.example.com:9051' }]); transactionSubmitStub.should.have.been.calledWith(Buffer.from(arg)); }); it('should commit a smart contract definition with timeout set', async () => { const arg: Uint8Array = protos.lifecycle.CommitChaincodeDefinitionArgs.encode(protoArgs).finish(); await channel.commitSmartContractDefinition(['myPeer', 'peer0.org2.example.com:9051'], 'myOrderer', { sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1' }, 1234); addEndorserStub.should.have.been.calledOnce; addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); const call: sinon.SinonSpyCall = gatewayConnectSpy.getCall(0); call.args[1].eventHandlerOptions.should.deep.equal({ commitTimeout: 1234, endorseTimeout: 1234 }); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }, { name: 'peer0.org2.example.com:9051' }]); transactionSubmitStub.should.have.been.calledWith(Buffer.from(arg)); }); it('should commit a smart contract definition and set initRequired if set', async () => { protoArgs.init_required = true; const arg: Uint8Array = protos.lifecycle.CommitChaincodeDefinitionArgs.encode(protoArgs).finish(); await channel.commitSmartContractDefinition(['myPeer', 'peer0.org2.example.com:9051'], 'myOrderer', { sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1', initRequired: true }); addEndorserStub.should.have.been.calledOnce; addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }, { name: 'peer0.org2.example.com:9051' }]); transactionSubmitStub.should.have.been.calledWith(Buffer.from(arg)); }); it('should commit a smart contract definition with endorsement plugin', async () => { protoArgs.endorsement_plugin = 'myPlugin'; const arg: Uint8Array = protos.lifecycle.CommitChaincodeDefinitionArgs.encode(protoArgs).finish(); await channel.commitSmartContractDefinition(['myPeer', 'peer0.org2.example.com:9051'], 'myOrderer', { sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1', endorsementPlugin: 'myPlugin' }); addEndorserStub.should.have.been.calledOnce; addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }, { name: 'peer0.org2.example.com:9051' }]); transactionSubmitStub.should.have.been.calledWith(Buffer.from(arg)); }); it('should commit a smart contract definition with validation plugin', async () => { protoArgs.validation_plugin = 'myPlugin'; const arg: Uint8Array = protos.lifecycle.CommitChaincodeDefinitionArgs.encode(protoArgs).finish(); await channel.commitSmartContractDefinition(['myPeer', 'peer0.org2.example.com:9051'], 'myOrderer', { sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1', validationPlugin: 'myPlugin' }); addEndorserStub.should.have.been.calledOnce; addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }, { name: 'peer0.org2.example.com:9051' }]); transactionSubmitStub.should.have.been.calledWith(Buffer.from(arg)); }); it('should commit a smart contract definition with endorsement policy', async () => { const policyString: string = `AND('org1.member', 'org2.member')`; const policy: EndorsementPolicy = new EndorsementPolicy(); const policyResult: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(policyString); const applicationPolicy: protos.common.IApplicationPolicy = {}; applicationPolicy.signature_policy = policyResult; const policyBuffer: Buffer = Buffer.from(protos.common.ApplicationPolicy.encode(applicationPolicy).finish()); protoArgs.validation_parameter = policyBuffer; const arg: Uint8Array = protos.lifecycle.CommitChaincodeDefinitionArgs.encode(protoArgs).finish(); await channel.commitSmartContractDefinition(['myPeer', 'peer0.org2.example.com:9051'], 'myOrderer', { sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1', endorsementPolicy: policyString }); addEndorserStub.should.have.been.calledOnce; addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }, { name: 'peer0.org2.example.com:9051' }]); transactionSubmitStub.should.have.been.calledWith(Buffer.from(arg)); }); it('should commit a smart contract definition with endorsement policy channel reference', async () => { const policyString: string = `myPolicyReference`; const applicationPolicy: protos.common.IApplicationPolicy = {}; applicationPolicy.channel_config_policy_reference = policyString; const policyBuffer: Buffer = Buffer.from(protos.common.ApplicationPolicy.encode(applicationPolicy).finish()); protoArgs.validation_parameter = policyBuffer; const arg: Uint8Array = protos.lifecycle.CommitChaincodeDefinitionArgs.encode(protoArgs).finish(); await channel.commitSmartContractDefinition(['myPeer', 'peer0.org2.example.com:9051'], 'myOrderer', { sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1', endorsementPolicy: policyString }); addEndorserStub.should.have.been.calledOnce; addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }, { name: 'peer0.org2.example.com:9051' }]); transactionSubmitStub.should.have.been.calledWith(Buffer.from(arg)); }); it('should commit a smart contract definition with collection config', async () => { const collectionConfig: Collection[] = [ { name: 'CollectionOne', policy: `OR('Org1MSP.member')`, requiredPeerCount: 1, maxPeerCount: 1, blockToLive: 0, memberOnlyRead: true } ]; protoArgs.collections = CollectionConfig.buildCollectionConfigPackage(collectionConfig); const arg: Uint8Array = protos.lifecycle.CommitChaincodeDefinitionArgs.encode(protoArgs).finish(); await channel.commitSmartContractDefinition(['myPeer', 'peer0.org2.example.com:9051'], 'myOrderer', { sequence: 1, smartContractName: 'myContract', smartContractVersion: '0.0.1', collectionConfig: collectionConfig }); addEndorserStub.should.have.been.calledOnce; addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }, { name: 'peer0.org2.example.com:9051' }]); transactionSubmitStub.should.have.been.calledWith(Buffer.from(arg)); }); }); describe('instantiateOrUpgradeSmartContractDefinition', () => { let mysandbox: sinon.SinonSandbox; let gatewayConnectSpy: sinon.SinonSpy; let transactionSetEndorsingPeersSpy: sinon.SinonSpy; let transactionSubmitStub: sinon.SinonStub; let addEndorserStub: sinon.SinonStub; let addCommitterStub: sinon.SinonStub; let peerNames: string[]; let ordererName: string; let options: SmartContractDefinitionOptions; let fcn: string; let args: string[]; let isUpgrade: boolean; let name: string; let version: string; let sequence: number; let packageId: string; let chaincodeDeploymentSpec: protos.protos.ChaincodeDeploymentSpec; beforeEach(() => { mysandbox = sinon.createSandbox(); mysandbox.stub(Endorser.prototype, 'connect').resolves(); mysandbox.stub(Discoverer.prototype, 'connect').resolves(); mysandbox.stub(Committer.prototype, 'connect').resolves(); peerNames = ['myPeer']; ordererName = 'myOrderer'; fcn = ''; args = []; isUpgrade = false; name = 'myContract'; version = '0.0.1'; sequence = -11; packageId = 'myPackageId'; options = { sequence: sequence, smartContractName: name, smartContractVersion: version, packageId: packageId, } addEndorserStub = mysandbox.stub(Channel.prototype, 'addEndorser'); addCommitterStub = mysandbox.stub(Channel.prototype, 'addCommitter'); // @ts-ignore mysandbox.stub(Channel.prototype, 'getEndorsers').returns([{ name: 'myPeer' }, { name: 'myPeer2' }, { name: 'myPeer:7051' }, { name: 'peer0.org2.example.com:9051' }]); gatewayConnectSpy = mysandbox.spy(Gateway.prototype, 'connect'); mysandbox.stub(DiscoveryService.prototype, 'build'); mysandbox.stub(DiscoveryService.prototype, 'sign'); mysandbox.stub(DiscoveryService.prototype, 'send').resolves(); transactionSetEndorsingPeersSpy = mysandbox.spy(Transaction.prototype, 'setEndorsingPeers'); transactionSubmitStub = mysandbox.stub(Transaction.prototype, 'submit'); const specArgs: Buffer[] = []; for (const arg of args) { specArgs.push(Buffer.from(arg, 'utf8')); } const ccSpec: any = { type: protos.protos.ChaincodeSpec.Type.GOLANG, chaincode_id: { name: options.smartContractName, version: options.smartContractVersion }, input: { args: specArgs } }; chaincodeDeploymentSpec = new protos.protos.ChaincodeDeploymentSpec(); chaincodeDeploymentSpec.chaincode_spec = ccSpec; }); afterEach(() => { mysandbox.restore(); options = {} as SmartContractDefinitionOptions; }); it('should instantiate a smart contract definition', async () => { const functionName: string = isUpgrade ? 'upgrade' : 'deploy'; const expectedArgs: string[] = [ functionName, channel['channelName'], protos.protos.ChaincodeDeploymentSpec.encode(chaincodeDeploymentSpec).finish().toString(), '', 'escc', 'vscc' ]; await channel.instantiateOrUpgradeSmartContractDefinition(peerNames, ordererName, options, fcn, args, isUpgrade, 1234); addEndorserStub.should.have.been.calledWith(sinon.match.instanceOf(Endorser)); addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }]); transactionSubmitStub.should.have.been.calledWith(expectedArgs[1], expectedArgs[2], expectedArgs[3], expectedArgs[4], expectedArgs[5]); }); it('should instantiate a smart contract definition with undefined fcn and args', async () => { fcn = undefined; args = undefined; const derivedFcn: string = 'init'; const derivedArgs: string[] = []; const newSpecArgs: Buffer[] = []; newSpecArgs.push(Buffer.from(derivedFcn, 'utf8')); for (const arg of derivedArgs) { newSpecArgs.push(Buffer.from(arg, 'utf8')); } const ccSpec: any = { type: protos.protos.ChaincodeSpec.Type.GOLANG, chaincode_id: { name: options.smartContractName, version: options.smartContractVersion }, input: { args: newSpecArgs } }; chaincodeDeploymentSpec = new protos.protos.ChaincodeDeploymentSpec(); chaincodeDeploymentSpec.chaincode_spec = ccSpec; const functionName: string = isUpgrade ? 'upgrade' : 'deploy'; const expectedArgs: string[] = [ functionName, channel['channelName'], protos.protos.ChaincodeDeploymentSpec.encode(chaincodeDeploymentSpec).finish().toString(), '', 'escc', 'vscc' ]; await channel.instantiateOrUpgradeSmartContractDefinition(peerNames, ordererName, options, fcn, args, isUpgrade, 1234); addEndorserStub.should.have.been.calledWith(sinon.match.instanceOf(Endorser)); addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }]); transactionSubmitStub.should.have.been.calledWith(expectedArgs[1], expectedArgs[2], expectedArgs[3], expectedArgs[4], expectedArgs[5]); }); it('should instantiate a smart contract definition with instantiate function and arguments', async () => { fcn = 'someFcn'; args = ['some', 'args']; const newSpecArgs: Buffer[] = []; newSpecArgs.push(Buffer.from(fcn, 'utf8')); for (const arg of args) { newSpecArgs.push(Buffer.from(arg, 'utf8')); } const ccSpec: any = { type: protos.protos.ChaincodeSpec.Type.GOLANG, chaincode_id: { name: options.smartContractName, version: options.smartContractVersion }, input: { args: newSpecArgs } }; chaincodeDeploymentSpec = new protos.protos.ChaincodeDeploymentSpec(); chaincodeDeploymentSpec.chaincode_spec = ccSpec; const functionName: string = isUpgrade ? 'upgrade' : 'deploy'; const expectedArgs: string[] = [ functionName, channel['channelName'], protos.protos.ChaincodeDeploymentSpec.encode(chaincodeDeploymentSpec).finish().toString(), '', 'escc', 'vscc' ]; await channel.instantiateOrUpgradeSmartContractDefinition(peerNames, ordererName, options, fcn, args, isUpgrade); addEndorserStub.should.have.been.calledWith(sinon.match.instanceOf(Endorser)); addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }]); transactionSubmitStub.should.have.been.calledWith(expectedArgs[1], expectedArgs[2], expectedArgs[3], expectedArgs[4], expectedArgs[5]); }); it('should upgrade a smart contract definition', async () => { isUpgrade = true; const functionName: string = isUpgrade ? 'upgrade' : 'deploy'; const expectedArgs: string[] = [ functionName, channel['channelName'], protos.protos.ChaincodeDeploymentSpec.encode(chaincodeDeploymentSpec).finish().toString(), '', 'escc', 'vscc' ]; await channel.instantiateOrUpgradeSmartContractDefinition(peerNames, ordererName, options, fcn, args, isUpgrade); addEndorserStub.should.have.been.calledWith(sinon.match.instanceOf(Endorser)); addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }]); transactionSubmitStub.should.have.been.calledWith(expectedArgs[1], expectedArgs[2], expectedArgs[3], expectedArgs[4], expectedArgs[5]); }); it('should instantiate a smart contract definition with all options and timeout', async () => { const functionName: string = isUpgrade ? 'upgrade' : 'deploy'; options.endorsementPolicy = 'OR(\'Org1.member\')'; options.endorsementPlugin = 'escc'; options.validationPlugin = 'vscc' options.collectionConfig = [ { name: 'CollectionOne', policy: `OR('Org1MSP.member')`, requiredPeerCount: 1, maxPeerCount: 1, blockToLive: 0, memberOnlyRead: true } ]; const expectedArgs: string[] = [ functionName, channel['channelName'], protos.protos.ChaincodeDeploymentSpec.encode(chaincodeDeploymentSpec).finish().toString(), LifecycleChannel.getEndorsementPolicyBytes(options.endorsementPolicy, true).toString(), options.endorsementPlugin, options.validationPlugin, LifecycleChannel.getCollectionConfig(options.collectionConfig, true).toString() ]; await channel.instantiateOrUpgradeSmartContractDefinition(peerNames, ordererName, options, fcn, args, isUpgrade, 1234); addEndorserStub.should.have.been.calledWith(sinon.match.instanceOf(Endorser)); addCommitterStub.should.have.been.calledWith(sinon.match.instanceOf(Committer)); transactionSetEndorsingPeersSpy.should.have.been.calledWith([{ name: 'myPeer' }]); transactionSubmitStub.should.have.been.calledWith(expectedArgs[1], expectedArgs[2], expectedArgs[3], expectedArgs[4], expectedArgs[5]); const call: sinon.SinonSpyCall = gatewayConnectSpy.getCall(0); call.args[1].eventHandlerOptions.should.deep.equal({ commitTimeout: 1234, endorseTimeout: 1234 }); }); }); describe('getCommitReadiness', () => { let mysandbox: sinon.SinonSandbox; let endorserConnectStub: sinon.SinonStub; let endorsementBuildSpy: sinon.SinonSpy; let endorsementSignSpy: sinon.SinonSpy; let endorsementSendStub: sinon.SinonStub; let protoArgs: protos.lifecycle.ICheckCommitReadinessArgs = {}; let buildRequest: any; beforeEach(() => { mysandbox = sinon.createSandbox(); protoArgs.name = 'myContract'; protoArgs.version = '0.0.1'; protoArgs.sequence = 1; const arg: Uint8Array = protos.lifecycle.CheckCommitReadinessArgs.encode(protoArgs).finish(); buildRequest = { fcn: 'CheckCommitReadiness', args: [Buffer.from(arg)] }; endorserConnectStub = mysandbox.stub(Endorser.prototype, 'connect').resolves(); endorsementBuildSpy = mysandbox.spy(Endorsement.prototype, 'build'); endorsementSignSpy = mysandbox.spy(Endorsement.prototype, 'sign'); endorsementSendStub = mysandbox.stub(Endorsement.prototype, 'send'); endorsementSendStub.resolves(); }); afterEach(() => { mysandbox.restore(); protoArgs = {} buildRequest = {} }); it('should get the commit readiness of a smart contract definition', async () => { const encodedResult: Buffer = Buffer.from(protos.lifecycle.CheckCommitReadinessResult.encode({ approvals: { org1: true, org2: false } }).finish()); endorsementSendStub.resolves({ responses: [{ response: { status: 200, payload: encodedResult } }] }); const result: Map<string, boolean> = await channel.getCommitReadiness('myPeer', { smartContractName: 'myContract', smartContractVersion: '0.0.1', sequence: 1 }); result.size.should.equal(2); // @ts-ignore result.get('org1').should.equal(true); // @ts-ignore result.get('org2').should.equal(false); endorserConnectStub.should.have.been.called; endorsementBuildSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext), buildRequest); endorsementSignSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); endorsementSendStub.should.have.been.calledWith({ targets: [sinon.match.instanceOf(Endorser)] }); }); it('should get the commit readiness of a smart contract definition with a timeout', async () => { const encodedResult: Buffer = Buffer.from(protos.lifecycle.CheckCommitReadinessResult.encode({ approvals: { org1: true, org2: false } }).finish()); endorsementSendStub.resolves({ responses: [{ response: { status: 200, payload: encodedResult } }] }); const result: Map<string, boolean> = await channel.getCommitReadiness('myPeer', { smartContractName: 'myContract', smartContractVersion: '0.0.1', sequence: 1 }, 1234); result.size.should.equal(2); // @ts-ignore result.get('org1').should.equal(true); // @ts-ignore result.get('org2').should.equal(false); endorserConnectStub.should.have.been.called; endorsementBuildSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext), buildRequest); endorsementSignSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); endorsementSendStub.should.have.been.calledWith({ targets: [sinon.match.instanceOf(Endorser)], requestTimeout: 1234 }); }); it('should get the commit readiness of a smart contract definition with init required', async () => { protoArgs.init_required = true; const arg: Uint8Array = protos.lifecycle.CheckCommitReadinessArgs.encode(protoArgs).finish(); buildRequest = { fcn: 'CheckCommitReadiness', args: [Buffer.from(arg)] }; const encodedResult: Buffer = Buffer.from(protos.lifecycle.CheckCommitReadinessResult.encode({ approvals: { org1: true, org2: false } }).finish()); endorsementSendStub.resolves({ responses: [{ response: { status: 200, payload: encodedResult } }] }); const result: Map<string, boolean> = await channel.getCommitReadiness('myPeer', { smartContractName: 'myContract', smartContractVersion: '0.0.1', sequence: 1, initRequired: true }); result.size.should.equal(2); // @ts-ignore result.get('org1').should.equal(true); // @ts-ignore result.get('org2').should.equal(false); endorserConnectStub.should.have.been.called; endorsementBuildSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext), buildRequest); endorsementSignSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); endorsementSendStub.should.have.been.calledWith({ targets: [sinon.match.instanceOf(Endorser)] }); }); it('should get the commit readiness of a smart contract definition with endorsement plugin', async () => { protoArgs.endorsement_plugin = 'myPlugin'; const arg: Uint8Array = protos.lifecycle.CheckCommitReadinessArgs.encode(protoArgs).finish(); buildRequest = { fcn: 'CheckCommitReadiness', args: [Buffer.from(arg)] }; const encodedResult: Buffer = Buffer.from(protos.lifecycle.CheckCommitReadinessResult.encode({ approvals: { org1: true, org2: false } }).finish()); endorsementSendStub.resolves({ responses: [{ response: { status: 200, payload: encodedResult } }] }); const result: Map<string, boolean> = await channel.getCommitReadiness('myPeer', { smartContractName: 'myContract', smartContractVersion: '0.0.1', sequence: 1, endorsementPlugin: 'myPlugin' }); result.size.should.equal(2); // @ts-ignore result.get('org1').should.equal(true); // @ts-ignore result.get('org2').should.equal(false); endorserConnectStub.should.have.been.called; endorsementBuildSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext), buildRequest); endorsementSignSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); endorsementSendStub.should.have.been.calledWith({ targets: [sinon.match.instanceOf(Endorser)] }); }); it('should get the commit readiness of a smart contract definition with validation plugin', async () => { protoArgs.validation_plugin = 'myPlugin'; const arg: Uint8Array = protos.lifecycle.CheckCommitReadinessArgs.encode(protoArgs).finish(); buildRequest = { fcn: 'CheckCommitReadiness', args: [Buffer.from(arg)] }; const encodedResult: Buffer = Buffer.from(protos.lifecycle.CheckCommitReadinessResult.encode({ approvals: { org1: true, org2: false } }).finish()); endorsementSendStub.resolves({ responses: [{ response: { status: 200, payload: encodedResult } }] }); const result: Map<string, boolean> = await channel.getCommitReadiness('myPeer', { smartContractName: 'myContract', smartContractVersion: '0.0.1', sequence: 1, validationPlugin: 'myPlugin' }); result.size.should.equal(2); // @ts-ignore result.get('org1').should.equal(true); // @ts-ignore result.get('org2').should.equal(false); endorserConnectStub.should.have.been.called; endorsementBuildSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext), buildRequest); endorsementSignSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); endorsementSendStub.should.have.been.calledWith({ targets: [sinon.match.instanceOf(Endorser)] }); }); it('should get the commit readiness of a smart contract definition with endorsement policy', async () => { const policyString: string = `AND('org1.member', 'org2.member')`; const policy: EndorsementPolicy = new EndorsementPolicy(); const policyResult: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(policyString); const applicationPolicy: protos.common.IApplicationPolicy = {}; applicationPolicy.signature_policy = policyResult; const policyBuffer: Buffer = Buffer.from(protos.common.ApplicationPolicy.encode(applicationPolicy).finish()); protoArgs.validation_parameter = policyBuffer; const arg: Uint8Array = protos.lifecycle.CheckCommitReadinessArgs.encode(protoArgs).finish(); buildRequest = { fcn: 'CheckCommitReadiness', args: [Buffer.from(arg)] }; const encodedResult: Buffer = Buffer.from(protos.lifecycle.CheckCommitReadinessResult.encode({ approvals: { org1: true, org2: false } }).finish()); endorsementSendStub.resolves({ responses: [{ response: { status: 200, payload: encodedResult } }] }); const result: Map<string, boolean> = await channel.getCommitReadiness('myPeer', { smartContractName: 'myContract', smartContractVersion: '0.0.1', sequence: 1, endorsementPolicy: policyString }); result.size.should.equal(2); // @ts-ignore result.get('org1').should.equal(true); // @ts-ignore result.get('org2').should.equal(false); endorserConnectStub.should.have.been.called; endorsementBuildSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext), buildRequest); endorsementSignSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); endorsementSendStub.should.have.been.calledWith({ targets: [sinon.match.instanceOf(Endorser)] }); }); it('should get the commit readiness of a smart contract definition with collection config', async () => { const collectionConfig: Collection[] = [ { name: 'CollectionOne', policy: `OR('Org1MSP.member')`, requiredPeerCount: 1, maxPeerCount: 1, blockToLive: 0, memberOnlyRead: true } ]; protoArgs.collections = CollectionConfig.buildCollectionConfigPackage(collectionConfig); const arg: Uint8Array = protos.lifecycle.CheckCommitReadinessArgs.encode(protoArgs).finish(); buildRequest = { fcn: 'CheckCommitReadiness', args: [Buffer.from(arg)] }; const encodedResult: Buffer = Buffer.from(protos.lifecycle.CheckCommitReadinessResult.encode({ approvals: { org1: true, org2: false } }).finish()); endorsementSendStub.resolves({ responses: [{ response: { status: 200, payload: encodedResult } }] }); const result: Map<string, boolean> = await channel.getCommitReadiness('myPeer', { smartContractName: 'myContract', smartContractVersion: '0.0.1', sequence: 1, collectionConfig: collectionConfig }); result.size.should.equal(2); // @ts-ignore result.get('org1').should.equal(true); // @ts-ignore result.get('org2').should.equal(false); endorserConnectStub.should.have.been.called; endorsementBuildSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext), buildRequest); endorsementSignSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); endorsementSendStub.should.have.been.calledWith({ targets: [sinon.match.instanceOf(Endorser)] }); }); it('should handle no peerName set', async () => { // @ts-ignore await channel.getCommitReadiness(undefined, { smartContractName: 'myContract', smartContractVersion: '0.0.1', sequence: 1, }).should.eventually.be.rejectedWith('parameter peerName is missing'); }); it('should handle no options set', async () => { // @ts-ignore await channel.getCommitReadiness('myPeer', undefined).should.eventually.be.rejectedWith('parameter options is missing'); }); it('should handle no smartContractName set', async () => { // @ts-ignore await channel.getCommitReadiness('myPeer', { smartContractVersion: '0.0.1', sequence: 1, }).should.eventually.be.rejectedWith('missing option smartContractName'); }); it('should handle no smartContractVersion set', async () => { // @ts-ignore await channel.getCommitReadiness('myPeer', { smartContractName: 'myContract', sequence: 1, }).should.eventually.be.rejectedWith('missing option smartContractVersion'); }); it('should handle error with sending request', async () => { endorsementSendStub.rejects({ message: 'some error' }); await channel.getCommitReadiness('myPeer', { smartContractName: 'myContract', smartContractVersion: '0.0.1', sequence: 1 }).should.eventually.be.rejectedWith('Could not get commit readiness, received error: some error'); endorserConnectStub.should.have.been.called; endorsementBuildSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext), buildRequest); endorsementSignSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); endorsementSendStub.should.have.been.calledWith({ targets: [sinon.match.instanceOf(Endorser)] }); }); }); describe('getAllCommittedSmartContracts', () => { let mysandbox: sinon.SinonSandbox; let endorserConnectStub: sinon.SinonStub; let endorsementBuildSpy: sinon.SinonSpy; let endorsementSignSpy: sinon.SinonSpy; let endorsementSendStub: sinon.SinonStub; let arg: Uint8Array; let protoArgs: protos.lifecycle.IQueryChaincodeDefinitionsArgs = {}; let buildRequest: any; beforeEach(() => { mysandbox = sinon.createSandbox(); arg = protos.lifecycle.QueryChaincodeDefinitionsArgs.encode(protoArgs).finish(); buildRequest = { fcn: 'QueryChaincodeDefinitions', args: [Buffer.from(arg)] }; endorserConnectStub = mysandbox.stub(Endorser.prototype, 'connect').resolves(); endorsementBuildSpy = mysandbox.spy(Endorsement.prototype, 'build'); endorsementSignSpy = mysandbox.spy(Endorsement.prototype, 'sign'); endorsementSendStub = mysandbox.stub(Endorsement.prototype, 'send'); endorsementSendStub.resolves(); }); afterEach(() => { mysandbox.restore(); protoArgs = {}; }); it('should get all the committed smart contracts', async () => { const encodedResult: Buffer = Buffer.from(protos.lifecycle.QueryChaincodeDefinitionsResult.encode({ chaincode_definitions: [{ name: 'myContract', sequence: 1, version: '0.0.1', init_required: false, endorsement_plugin: 'escc', validation_plugin: 'vscc', validation_parameter: Buffer.from(JSON.stringify({})), collections: {} }, { name: 'myContract2', sequence: 4, version: '0.0.7', init_required: false, endorsement_plugin: 'escc', validation_plugin: 'vscc', validation_parameter: Buffer.from(JSON.stringify({})), collections: {} }] }).finish()); endorsementSendStub.resolves({ responses: [{ response: { status: 200, payload: encodedResult } }] }); const result: DefinedSmartContract[] = await channel.getAllCommittedSmartContracts('myPeer'); result.length.should.equal(2); result[0].smartContractName.should.equal('myContract'); result[0].smartContractVersion.should.equal('0.0.1'); result[0].sequence.should.equal(1); // @ts-ignore result[0].initRequired.should.equal(false); result[1].smartContractName.should.equal('myContract2'); result[1].smartContractVersion.should.equal('0.0.7'); result[1].sequence.should.equal(4); // @ts-ignore result[1].initRequired.should.equal(false); endorserConnectStub.should.have.been.called; endorsementBuildSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext), buildRequest); endorsementSignSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); endorsementSendStub.should.have.been.calledWith({ targets: [sinon.match.instanceOf(Endorser)] }); }); it('should get all the committed smart contracts with timeout', async () => { const encodedResult: Buffer = Buffer.from(protos.lifecycle.QueryChaincodeDefinitionsResult.encode({ chaincode_definitions: [{ name: 'myContract', sequence: 1, version: '0.0.1', init_required: false, endorsement_plugin: 'escc', validation_plugin: 'vscc', validation_parameter: Buffer.from(JSON.stringify({})), collections: {} }, { name: 'myContract2', sequence: 4, version: '0.0.7', init_required: false, endorsement_plugin: 'escc', validation_plugin: 'vscc', validation_parameter: Buffer.from(JSON.stringify({})), collections: {} }] }).finish()); endorsementSendStub.resolves({ responses: [{ response: { status: 200, payload: encodedResult } }] }); const result: DefinedSmartContract[] = await channel.getAllCommittedSmartContracts('myPeer', 1234); result.length.should.equal(2); result[0].smartContractName.should.equal('myContract'); result[0].smartContractVersion.should.equal('0.0.1'); result[0].sequence.should.equal(1); // @ts-ignore result[0].initRequired.should.equal(false); result[1].smartContractName.should.equal('myContract2'); result[1].smartContractVersion.should.equal('0.0.7'); result[1].sequence.should.equal(4); // @ts-ignore result[1].initRequired.should.equal(false); endorserConnectStub.should.have.been.called; endorsementBuildSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext), buildRequest); endorsementSignSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); endorsementSendStub.should.have.been.calledWith({ targets: [sinon.match.instanceOf(Endorser)], requestTimeout: 1234 }); }); it('should handle no peerName', async () => { // @ts-ignore await channel.getAllCommittedSmartContracts(undefined).should.eventually.be.rejectedWith('parameter peerName is missing'); }); it('should handle error from send', async () => { endorsementSendStub.rejects({ message: 'some error' }); await channel.getAllCommittedSmartContracts('myPeer').should.eventually.be.rejectedWith('Could not get smart contract definitions, received error: some error'); }); }); describe('getAllInstantiatedSmartContracts', () => { let mysandbox: sinon.SinonSandbox; let endorserConnectStub: sinon.SinonStub; let endorsementBuildSpy: sinon.SinonSpy; let endorsementSignSpy: sinon.SinonSpy; let endorsementSendStub: sinon.SinonStub; let buildRequest: any; beforeEach(() => { mysandbox = sinon.createSandbox(); buildRequest = { fcn: 'GetChaincodes', args: [] }; endorserConnectStub = mysandbox.stub(Endorser.prototype, 'connect').resolves(); endorsementBuildSpy = mysandbox.spy(Endorsement.prototype, 'build'); endorsementSignSpy = mysandbox.spy(Endorsement.prototype, 'sign'); endorsementSendStub = mysandbox.stub(Endorsement.prototype, 'send'); endorsementSendStub.resolves(); }); afterEach(() => { mysandbox.restore(); }); it('should get all the instantiated smart contracts', async () => { const encodedResult: Buffer = Buffer.from(protos.protos.ChaincodeQueryResponse.encode({ chaincodes: [{ name: 'myContract', version: '0.0.2', escc: 'escc', vscc: 'vscc', }, { name: 'myContract2', version: '0.0.3', escc: 'escc', vscc: 'vscc', }] }).finish()); endorsementSendStub.resolves({ responses: [{ response: { status: 200, payload: encodedResult } }] }); const result: DefinedSmartContract[] = await channel.getAllInstantiatedSmartContracts('myPeer'); result.length.should.equal(2); result[0].smartContractName.should.equal('myContract'); result[0].smartContractVersion.should.equal('0.0.2'); result[0].sequence.should.equal(-1); should.equal(undefined, result[0].initRequired); result[1].smartContractName.should.equal('myContract2'); result[1].smartContractVersion.should.equal('0.0.3'); result[1].sequence.should.equal(-1); should.equal(undefined, result[1].initRequired); endorserConnectStub.should.have.been.called; endorsementBuildSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext), buildRequest); endorsementSignSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); endorsementSendStub.should.have.been.calledWith({ targets: [sinon.match.instanceOf(Endorser)] }); }); it('should get all the instantiated smart contracts with timeout', async () => { const encodedResult: Buffer = Buffer.from(protos.protos.ChaincodeQueryResponse.encode({ chaincodes: [{ name: 'myContract', version: '0.0.2', escc: 'escc', vscc: 'vscc', }, { name: 'myContract2', version: '0.0.3', escc: 'escc', vscc: 'vscc', }] }).finish()); endorsementSendStub.resolves({ responses: [{ response: { status: 200, payload: encodedResult } }] }); const result: DefinedSmartContract[] = await channel.getAllInstantiatedSmartContracts('myPeer', 1234); result.length.should.equal(2); result[0].smartContractName.should.equal('myContract'); result[0].smartContractVersion.should.equal('0.0.2'); result[0].sequence.should.equal(-1); should.equal(undefined, result[0].initRequired); // @ts-ignore // result[0].initRequired.should.equal(false); result[1].smartContractName.should.equal('myContract2'); result[1].smartContractVersion.should.equal('0.0.3'); result[1].sequence.should.equal(-1); should.equal(undefined, result[0].initRequired); // @ts-ignore // result[1].initRequired.should.equal(false); endorserConnectStub.should.have.been.called; endorsementBuildSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext), buildRequest); endorsementSignSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); endorsementSendStub.should.have.been.calledWith({ targets: [sinon.match.instanceOf(Endorser)], requestTimeout: 1234 }); }); it('should handle no peerName', async () => { // @ts-ignore await channel.getAllInstantiatedSmartContracts(undefined).should.eventually.be.rejectedWith('parameter peerName is missing'); }); it('should handle empty response from send', async () => { endorsementSendStub.resolves(); await channel.getAllInstantiatedSmartContracts('myPeer').should.eventually.be.rejectedWith('Could not get smart contract definitions, received error: Payload results are missing from the query'); }); it('should handle send throwing error', async () => { endorsementSendStub.rejects({ message: 'some error' }); await channel.getAllInstantiatedSmartContracts('myPeer').should.eventually.be.rejectedWith('Could not get smart contract definitions, received error: some error'); }); it('should handle error response', async () => { endorsementSendStub.resolves({ errors: [ new Error('some service error') ] }); await channel.getAllInstantiatedSmartContracts('myPeer').should.eventually.be.rejectedWith('Could not get smart contract definitions, received error: some service error'); }); it('should handle problem with request response flagged up by status and message', async () => { endorsementSendStub.resolves({ responses: [{ response: { status: 500, message: 'some fabric error' } }] }); await channel.getAllInstantiatedSmartContracts('myPeer').should.eventually.be.rejectedWith('Could not get smart contract definitions, received error: some fabric error'); }); it('should handle problem with request response flagged up by status but no message', async () => { const problemResponse: any = { response: { status: 300, } }; endorsementSendStub.resolves({ responses: [problemResponse] }); await channel.getAllInstantiatedSmartContracts('myPeer').should.eventually.be.rejectedWith(`Could not get smart contract definitions, received error: ${problemResponse.toString()}`); }); it('should handle problem with request response', async () => { const problemResponse: any = {strangeKey: 'strange value'}; endorsementSendStub.resolves({ responses: [problemResponse] }); await channel.getAllInstantiatedSmartContracts('myPeer').should.eventually.be.rejectedWith(`Could not get smart contract definitions, received error: ${problemResponse.toString()}`); }); }); describe('getCommittedSmartContract', () => { let mysandbox: sinon.SinonSandbox; let endorserConnectStub: sinon.SinonStub; let endorsementBuildSpy: sinon.SinonSpy; let endorsementSignSpy: sinon.SinonSpy; let endorsementSendStub: sinon.SinonStub; let arg: any; let protoArgs: protos.lifecycle.IQueryChaincodeDefinitionArgs = {}; let buildRequest: any; beforeEach(() => { mysandbox = sinon.createSandbox(); protoArgs.name = 'myContract'; arg = protos.lifecycle.QueryChaincodeDefinitionArgs.encode(protoArgs).finish(); buildRequest = { fcn: 'QueryChaincodeDefinition', args: [Buffer.from(arg)] }; endorserConnectStub = mysandbox.stub(Endorser.prototype, 'connect').resolves(); endorsementBuildSpy = mysandbox.spy(Endorsement.prototype, 'build'); endorsementSignSpy = mysandbox.spy(Endorsement.prototype, 'sign'); endorsementSendStub = mysandbox.stub(Endorsement.prototype, 'send'); endorsementSendStub.resolves(); }); afterEach(() => { mysandbox.restore(); protoArgs = {}; }); it('should get the committed smart contract', async () => { const encodedResult: Buffer = Buffer.from(protos.lifecycle.QueryChaincodeDefinitionResult.encode({ sequence: 1, version: '0.0.1', init_required: false, endorsement_plugin: 'escc', validation_plugin: 'vscc', validation_parameter: Buffer.from(JSON.stringify({})), collections: {}, approvals: { 'Org1MSP': true, 'Org2MSP': true } }).finish()); endorsementSendStub.resolves({ responses: [{ response: { status: 200, payload: encodedResult } }] }); const result: DefinedSmartContract = await channel.getCommittedSmartContract('myPeer', 'myContract'); result.smartContractName.should.equal('myContract'); result.smartContractVersion.should.equal('0.0.1'); result.sequence.should.equal(1); // @ts-ignore result.initRequired.should.equal(false); result.approvals!.size.should.equal(2); result.approvals!.get('Org1MSP')!.should.equal(true); result.approvals!.get('Org2MSP')!.should.equal(true); endorserConnectStub.should.have.been.called; endorsementBuildSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext), buildRequest); endorsementSignSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); endorsementSendStub.should.have.been.calledWith({ targets: [sinon.match.instanceOf(Endorser)] }); }); it('should get all the committed smart contracts with timeout', async () => { const encodedResult: Buffer = Buffer.from(protos.lifecycle.QueryChaincodeDefinitionResult.encode({ sequence: 1, version: '0.0.1', init_required: false, endorsement_plugin: 'escc', validation_plugin: 'vscc', validation_parameter: Buffer.from(JSON.stringify({})), collections: {}, approvals: { 'Org1MSP': true, 'Org2MSP': true } }).finish()); endorsementSendStub.resolves({ responses: [{ response: { status: 200, payload: encodedResult } }] }); const result: DefinedSmartContract = await channel.getCommittedSmartContract('myPeer', 'myContract', 1234); result.smartContractName.should.equal('myContract'); result.smartContractVersion.should.equal('0.0.1'); result.sequence.should.equal(1); // @ts-ignore result.initRequired.should.equal(false); result.approvals!.size.should.equal(2); result.approvals!.get('Org1MSP')!.should.equal(true); result.approvals!.get('Org2MSP')!.should.equal(true); endorserConnectStub.should.have.been.called; endorsementBuildSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext), buildRequest); endorsementSignSpy.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); endorsementSendStub.should.have.been.calledWith({ targets: [sinon.match.instanceOf(Endorser)], requestTimeout: 1234 }); }); it('should handle no peerName', async () => { // @ts-ignore await channel.getCommittedSmartContract(undefined).should.eventually.be.rejectedWith('parameter peerName is missing'); }); it('should handle no smartContractName', async () => { // @ts-ignore await channel.getCommittedSmartContract('myPeer', undefined).should.eventually.be.rejectedWith('parameter smartContractName is missing'); }); it('should handle error from send', async () => { endorsementSendStub.rejects({ message: 'some error' }); await channel.getCommittedSmartContract('myPeer', 'mySmartContract').should.eventually.be.rejectedWith('Could not get smart contract definition, received error: some error'); }); }); describe('getEndorsementPolicyBytes', () => { it('should get the buffer of the endorsment policy using AND', () => { const policyString: string = `AND('org1.member', 'org2.member')`; const policy: EndorsementPolicy = new EndorsementPolicy(); const policyResult: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(policyString); const applicationPolicy: protos.common.IApplicationPolicy = {}; applicationPolicy.signature_policy = policyResult; const policyBuffer: Buffer = Buffer.from(protos.common.ApplicationPolicy.encode(applicationPolicy).finish()); const result: Buffer = LifecycleChannel.getEndorsementPolicyBytes(policyString); result.should.deep.equal(policyBuffer); }); it('should get the buffer of the endorsment policy when using OR', () => { const policyString: string = `OR('org1.member', 'org2.member')`; const policy: EndorsementPolicy = new EndorsementPolicy(); const policyResult: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(policyString); const applicationPolicy: protos.common.IApplicationPolicy = {}; applicationPolicy.signature_policy = policyResult; const policyBuffer: Buffer = Buffer.from(protos.common.ApplicationPolicy.encode(applicationPolicy).finish()); const result: Buffer = LifecycleChannel.getEndorsementPolicyBytes(policyString); result.should.deep.equal(policyBuffer); }); it('should get the buffer of the endorsment policy when using outOf', () => { const policyString: string = `OutOf(1, 'org1.member', 'org2.member')`; const policy: EndorsementPolicy = new EndorsementPolicy(); const policyResult: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(policyString); const applicationPolicy: protos.common.IApplicationPolicy = {}; applicationPolicy.signature_policy = policyResult; const policyBuffer: Buffer = Buffer.from(protos.common.ApplicationPolicy.encode(applicationPolicy).finish()); const result: Buffer = LifecycleChannel.getEndorsementPolicyBytes(policyString); result.should.deep.equal(policyBuffer); }); it('should get the buffer of the endorsment policy when using channel reference', () => { const policyString: string = `myPolicyReference`; const applicationPolicy: protos.common.IApplicationPolicy = {}; applicationPolicy.channel_config_policy_reference = policyString; const policyBuffer: Buffer = Buffer.from(protos.common.ApplicationPolicy.encode(applicationPolicy).finish()); const result: Buffer = LifecycleChannel.getEndorsementPolicyBytes(policyString); result.should.deep.equal(policyBuffer); }); it('should get the buffer of the endorsment policy when using a valid input for a v1 contract', () => { const policyString: string = `OR('org1.member', 'org2.member')`; const policy: EndorsementPolicy = new EndorsementPolicy(); const policyResult: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(policyString); const applicationPolicy: protos.common.IApplicationPolicy = {}; applicationPolicy.signature_policy = policyResult; const policyBuffer: Buffer = Buffer.from(protos.common.SignaturePolicyEnvelope.encode(applicationPolicy.signature_policy).finish()); const result: Buffer = LifecycleChannel.getEndorsementPolicyBytes(policyString, true); result.should.deep.equal(policyBuffer); }); it('should throw error if invalid input for a v1 contract', () => { const policyString: string = `strange policy string`; (() => LifecycleChannel.getEndorsementPolicyBytes(policyString, true)).should.throw(`Cannot build endorsement policy from user input: ${policyString}`); }); it('should handle no policy string', () => { const policyString: string = ''; (() => LifecycleChannel.getEndorsementPolicyBytes(policyString)).should.throw('Missing parameter endorsementPolicy'); }); }); describe('getCollectionConfig', () => { it('should get the collection config', () => { const collection: Collection = { name: 'myCollection', policy: `OR('Org1MSP.member', 'Org2MSP.member')`, requiredPeerCount: 0, maxPeerCount: 3 }; const expectedResult: protos.common.CollectionConfigPackage = CollectionConfig.buildCollectionConfigPackage([collection]); const actualResult: protos.common.CollectionConfigPackage = LifecycleChannel.getCollectionConfig([collection]) as protos.common.CollectionConfigPackage; actualResult.should.deep.equal(expectedResult); }); it('should get the collection config as a buffer', () => { const collection: Collection = { name: 'myCollection', policy: `OR('Org1MSP.member', 'Org2MSP.member')`, requiredPeerCount: 0, maxPeerCount: 3 }; const expectedResult: protos.common.CollectionConfigPackage = CollectionConfig.buildCollectionConfigPackage([collection]); const actualResult: Buffer = LifecycleChannel.getCollectionConfig([collection], true) as Buffer; const arg: Uint8Array = protos.common.CollectionConfigPackage.encode({ config: expectedResult.config }).finish(); actualResult.should.deep.equal(Buffer.from(arg)); }); }); describe('getDiscoveredPeerNames', () => { let mysandbox: sinon.SinonSandbox; let gatewayConnectSpy: sinon.SinonSpy; let discoverServiceSignStub: sinon.SinonStub; let discoverServiceBuildStub: sinon.SinonStub; let discoverServiceSendStub: sinon.SinonStub; let getEndorsersStub: sinon.SinonStub; beforeEach(() => { mysandbox = sinon.createSandbox(); mysandbox.stub(Endorser.prototype, 'connect').resolves(); mysandbox.stub(Discoverer.prototype, 'connect').resolves(); mysandbox.stub(Channel.prototype, 'addEndorser'); // @ts-ignore getEndorsersStub = mysandbox.stub(Channel.prototype, 'getEndorsers') getEndorsersStub.returns([{ name: 'myPeer', endpoint: { url: 'url.one:7051' } }, { name: 'myPeer:7051', endpoint: { url: 'url.one:7051' } }, { name: 'peer0.org2.example.com:9051', endpoint: { url: 'url.three:7051' } }]); gatewayConnectSpy = mysandbox.spy(Gateway.prototype, 'connect'); discoverServiceBuildStub = mysandbox.stub(DiscoveryService.prototype, 'build'); discoverServiceSignStub = mysandbox.stub(DiscoveryService.prototype, 'sign'); discoverServiceSendStub = mysandbox.stub(DiscoveryService.prototype, 'send').resolves(); }); afterEach(() => { mysandbox.restore(); }); it('should get the discovered peers', async () => { const result: string[] = await channel.getDiscoveredPeerNames(['myPeer']); result.should.deep.equal(['myPeer', 'peer0.org2.example.com:9051']); discoverServiceSignStub.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); discoverServiceBuildStub.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); discoverServiceSendStub.should.have.been.calledWith({ asLocalhost: true, targets: [sinon.match.instanceOf(Discoverer)] }); }); it('should filter out peers with the same endpoint and return discovered peers', async () => { getEndorsersStub.returns([{ name: 'myPeer', endpoint: { url: 'localhost:9051' } }, { name: 'peer1.org1.example.com:9051', endpoint: { url: 'localhost:9051' } }, { name: 'peer1.org2.example.com:8051', endpoint: { url: 'localhost:8051' } }, { name: 'Org2Peer1', endpoint: { url: 'localhost:8051' } }, { name: 'Org3Peer1:6051', endpoint: { url: 'localhost:6051' } }, { name: 'peer1.org3.example.com:6051', endpoint: { url: 'localhost:6051' } }]); const result: string[] = await channel.getDiscoveredPeerNames(['myPeer']); result.should.deep.equal(['myPeer', 'Org2Peer1', 'peer1.org3.example.com:6051']); discoverServiceSignStub.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); discoverServiceBuildStub.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); discoverServiceSendStub.should.have.been.calledWith({ asLocalhost: true, targets: [sinon.match.instanceOf(Discoverer)] }); }); it('should filter out peers with the same endpoint and same options and return discovered peers', async () => { getEndorsersStub.returns([ { name: 'myPeer1', endpoint: { url: 'localhost:8080', options: { 'grpc.default_authority': 'peer0.org1.example.com' } } }, { name: 'myPeer2', endpoint: { url: 'localhost:8080' } }, { name: 'myPeer3', endpoint: { url: 'localhost:8080', options: { 'grpc.default_authority': 'peer0.org1.example.com' } } }, { name: 'myPeer4', endpoint: { url: '192.168.1.12:8080', options: { 'grpc.default_authority': 'peer0.org1.example.com' } } }, { name: 'myPeer5', endpoint: { url: 'localhost:8080', options: { 'grpc.default_authority': 'peer0.org2.example.com' } } }, ]); const result: string[] = await channel.getDiscoveredPeerNames(['myPeer']); result.should.deep.equal(['myPeer2', 'myPeer3', 'myPeer4', 'myPeer5']); discoverServiceSignStub.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); discoverServiceBuildStub.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); discoverServiceSendStub.should.have.been.calledWith({ asLocalhost: true, targets: [sinon.match.instanceOf(Discoverer)] }); }); it('should get the discovered peer with timeout', async () => { const result: string[] = await channel.getDiscoveredPeerNames(['myPeer'], 1234); result.should.deep.equal(['myPeer', 'peer0.org2.example.com:9051']); discoverServiceSignStub.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); discoverServiceBuildStub.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); discoverServiceSendStub.should.have.been.calledWith({ asLocalhost: true, targets: [sinon.match.instanceOf(Discoverer)] }); const call: sinon.SinonSpyCall = gatewayConnectSpy.getCall(0); call.args[1].eventHandlerOptions.should.deep.equal({ commitTimeout: 1234, endorseTimeout: 1234 }); }); it('should handle no peerNames set', async () => { // @ts-ignore await channel.getDiscoveredPeerNames().should.eventually.be.rejectedWith('parameter peers was missing or empty array'); }); it('should handle error', async () => { discoverServiceSendStub.rejects({ message: 'some error' }); await channel.getDiscoveredPeerNames(['myPeer']).should.eventually.be.rejectedWith('Could discover peers, received error some error'); discoverServiceSignStub.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); discoverServiceBuildStub.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); discoverServiceSendStub.should.have.been.calledWith({ asLocalhost: true, targets: [sinon.match.instanceOf(Discoverer)] }); }); }); describe('getDiscoveredPeers', () => { let mysandbox: sinon.SinonSandbox; let gatewayConnectSpy: sinon.SinonSpy; let discoverServiceSignStub: sinon.SinonStub; let discoverServiceBuildStub: sinon.SinonStub; let discoverServiceSendStub: sinon.SinonStub; let getEndorsersStub: sinon.SinonStub; beforeEach(() => { mysandbox = sinon.createSandbox(); mysandbox.stub(Endorser.prototype, 'connect').resolves(); mysandbox.stub(Discoverer.prototype, 'connect').resolves(); mysandbox.stub(Channel.prototype, 'addEndorser'); // @ts-ignore getEndorsersStub = mysandbox.stub(Channel.prototype, 'getEndorsers') getEndorsersStub.returns([{ name: 'myPeer', endpoint: { url: 'url.one:7051' } }, { name: 'myPeer:7051', endpoint: { url: 'urltwo:7051' } }, { name: 'peer0.org2.example.com:9051', endpoint: { url: 'url.three:7051' } }]); gatewayConnectSpy = mysandbox.spy(Gateway.prototype, 'connect'); discoverServiceBuildStub = mysandbox.stub(DiscoveryService.prototype, 'build'); discoverServiceSignStub = mysandbox.stub(DiscoveryService.prototype, 'sign'); discoverServiceSendStub = mysandbox.stub(DiscoveryService.prototype, 'send').resolves(); }); afterEach(() => { mysandbox.restore(); }); it('should get the discovered peer names', async () => { const result: Endpoint[] = await channel.getDiscoveredPeers(['myPeer']); result.should.deep.equal([{ name: 'myPeer', endpoint: { url: 'url.one:7051' } }, { name: 'myPeer:7051', endpoint: { url: 'urltwo:7051' } }, { name: 'peer0.org2.example.com:9051', endpoint: { url: 'url.three:7051' } }]); discoverServiceSignStub.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); discoverServiceBuildStub.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); discoverServiceSendStub.should.have.been.calledWith({ asLocalhost: true, targets: [sinon.match.instanceOf(Discoverer)] }); }); it('should filter out peers with the same endpoint and return discovered peer names', async () => { getEndorsersStub.returns([{ name: 'myPeer', endpoint: { url: 'localhost:9051' } }, { name: 'peer1.org1.example.com:9051', endpoint: { url: 'localhost:9051' } }, { name: 'peer1.org2.example.com:8051', endpoint: { url: 'localhost:8051' } }, { name: 'Org2Peer1', endpoint: { url: 'localhost:8051' } }, { name: 'Org3Peer1:6051', endpoint: { url: 'localhost:6051' } }, { name: 'peer1.org3.example.com:6051', endpoint: { url: 'localhost:6051' } }]); const result: Endorser[] = await channel.getDiscoveredPeers(['myPeer']); result.should.deep.equal([{ name: 'myPeer', endpoint: { url: 'localhost:9051' } }, { name: 'Org2Peer1', endpoint: { url: 'localhost:8051' } }, { name: 'peer1.org3.example.com:6051', endpoint: { url: 'localhost:6051' } }]); discoverServiceSignStub.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); discoverServiceBuildStub.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); discoverServiceSendStub.should.have.been.calledWith({ asLocalhost: true, targets: [sinon.match.instanceOf(Discoverer)] }); }); it('should get the discovered peer names with timeout', async () => { const result: Endorser[] = await channel.getDiscoveredPeers(['myPeer'], 1234); result.should.deep.equal([{ name: 'myPeer', endpoint: { url: 'url.one:7051' } }, { name: 'myPeer:7051', endpoint: { url: 'urltwo:7051' } }, { name: 'peer0.org2.example.com:9051', endpoint: { url: 'url.three:7051' } }]); discoverServiceSignStub.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); discoverServiceBuildStub.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); discoverServiceSendStub.should.have.been.calledWith({ asLocalhost: true, targets: [sinon.match.instanceOf(Discoverer)] }); const call: sinon.SinonSpyCall = gatewayConnectSpy.getCall(0); call.args[1].eventHandlerOptions.should.deep.equal({ commitTimeout: 1234, endorseTimeout: 1234 }); }); it('should handle no peerNames set', async () => { // @ts-ignore await channel.getDiscoveredPeers().should.eventually.be.rejectedWith('parameter peers was missing or empty array'); }); it('should handle error', async () => { discoverServiceSendStub.rejects({ message: 'some error' }); await channel.getDiscoveredPeers(['myPeer']).should.eventually.be.rejectedWith('Could discover peers, received error some error'); discoverServiceSignStub.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); discoverServiceBuildStub.should.have.been.calledWith(sinon.match.instanceOf(IdentityContext)); discoverServiceSendStub.should.have.been.calledWith({ asLocalhost: true, targets: [sinon.match.instanceOf(Discoverer)] }); }); }); }); });
the_stack
import { IConfigParseResult } from '../libs/config-parse-result'; import { IPlugin, forwardChildWebpackConfigs, forwardChildPostBuilds, forwardChildIamRoleStatements } from '../libs/plugin'; import { isDataLayer } from './datalayer-component' import * as deepmerge from 'deepmerge'; import {PARSER_MODES} from "../libs/parser"; /** * Parameters that apply to the whole Plugin, passed by other plugins * * The DataLayer is supported by: * - `IsomorphicApp` */ export interface IDataLayerPlugin { /** * one of the [[PARSER_MODES]] */ parserMode: string, /** * path to a directory where we put the final bundles */ buildPath: string, /** * path to the main config file */ configFilePath: string, } /** * The Data * * @param props */ export const DataLayerPlugin = (props: IDataLayerPlugin): IPlugin => { const path = require('path'); const result: IPlugin = { applies: (component):boolean => { return isDataLayer(component); }, // convert the component into configuration parts // while the component is of Type `any`, its props must be of type `IDataLayerArgs` | `IDataLayerProps` process: ( component: any, childConfigs: Array<IConfigParseResult>, infrastructureMode: string | undefined ):IConfigParseResult => { const dbPath = path.join( require("../../../infrastructure-scripts/dist/infra-comp-utils/system-libs").currentAbsolutePath(),".dynamodb" ); // the datalayer has a (query) server application /*const queryWebPack = (args) => require("../../../infrastructure-scripts/dist/infra-comp-utils/webpack-libs").complementWebpackConfig( require("../../../infrastructure-scripts/dist/infra-comp-utils/webpack-libs").createServerWebpackConfig( "./"+path.join("node_modules", "infrastructure-components", "dist" , "assets", "data-layer.js"), //entryPath: string, path.join(require("../../../infrastructure-scripts/dist/infra-comp-utils/system-libs").currentAbsolutePath(), props.buildPath), //use the buildpath from the parent plugin component.id, // name of the server // aliasesDict { __CONFIG_FILE_PATH__: require("../../../infrastructure-scripts/dist/infra-comp-utils/system-libs").pathToConfigFile(props.configFilePath), // replace the IsoConfig-Placeholder with the real path to the main-config-bundle }, // replacementsDict { __DATALAYER_ID__: `"${component.id}"`, /*, __ASSETS_PATH__: `"${component.assetsPath}"`, __RESOLVED_ASSETS_PATH__: `"${resolveAssetsPath( component.buildPath, serverName, component.assetsPath ) }"`* / } ) );*/ /** * setup a database and a handler */ const dataLayerConfig = { /*functions: { /* query: { // index.default refers to the default export of the file, points to the output of the queryWebpack-bundle handler: path.join(props.buildPath, component.id, `${component.id}.default`), role: "DataLayerLambdaRole", events: [ { http: { //this path must match the path specified in the environment below path: "query", // the Apollo Api usually works via POST, mutations always use POST method: "POST", cors: "true" } }, ] } },*/ plugins: ["serverless-dynamodb-local"], /* see: https://www.npmjs.com/package/serverless-dynamodb-local */ custom: { "dynamodb": { stages: ["${self:provider.stage}", "dev"], start: { port: 8000, //inMemory: "true", dbPath: dbPath, heapInitial: "200m", heapMax: "1g", migrate: "true", //seed: "true", convertEmptyValues: "true", //cors: ['localhost:3000', 'localhost:3001'] }, } }, provider: { environment: { // set the table name in an environment variable TABLE_NAME: "${self:service}-${self:provider.stage, env:STAGE, 'dev'}-data-layer", // must match the http-path from the function-event GRAPHQL_PATH: "query" } }, resources: { Resources: { ApplicationDynamoDBTable: { Type: "AWS::DynamoDB::Table", Properties: { TableName: "${self:service}-${self:provider.stage, env:STAGE, 'dev'}-data-layer", BillingMode: "PAY_PER_REQUEST", AttributeDefinitions: [ { AttributeName: "pk", AttributeType: "S" }, { AttributeName: "sk", AttributeType: "S" } ], KeySchema: [ { AttributeName: "pk", KeyType: "HASH" }, { AttributeName: "sk", KeyType: "RANGE" } ], GlobalSecondaryIndexes: [ { IndexName: "reverse", KeySchema: [ { AttributeName: "sk", KeyType: "HASH" }, { AttributeName: "pk", KeyType: "RANGE" } ], Projection: { ProjectionType: "ALL" } } ] } } } } }; async function createLocalDbFolder () { //console.log("check for >>copyAssetsPostBuild<<"); const fs = require('fs'); if (props.parserMode == PARSER_MODES.MODE_BUILD) { if ( !fs.existsSync( dbPath ) ) { console.log("creating folder: ", dbPath); fs.mkdirSync( dbPath, {recursive: true} ); await require("../../../infrastructure-scripts/dist/infra-comp-utils/sls-libs").runSlsCmd("sls dynamodb install", data => { console.log(data); }); } } }; const iamRoleStatements = [ { Effect: "Allow", Action: [ "dynamodb:GetItem", "dynamodb:UpdateItem", "dynamodb:DeleteItem", "dynamodb:PutItem", "dynamodb:Scan", "dynamodb:Query" ], Resource: [ '"arn:aws:dynamodb:${self:provider.region}:*:table/${self:service}-${self:provider.stage, env:STAGE, \'dev\'}-data-layer"', '"arn:aws:dynamodb:${self:provider.region}:*:table/${self:service}-${self:provider.stage, env:STAGE, \'dev\'}-data-layer/*"' ] } ].concat(forwardChildIamRoleStatements(childConfigs)); //console.log("datalayer iamStatements: ", iamRoleStatements); return { slsConfigs: deepmerge.all([ dataLayerConfig ].concat(childConfigs.map(config => config.slsConfigs))), // forward the webpacks (of the WebApps) as-is, add the queryApp-Webpack-bundle webpackConfigs: /*[queryWebPack].concat(*/forwardChildWebpackConfigs(childConfigs).map( // complement the args with the datalayer-id fWp => (args) => fWp(Object.assign({ datalayerid : component.id}, args)) )/*)*/, postBuilds: childConfigs.reduce((result, config) => result.concat(config.postBuilds), [createLocalDbFolder]), iamRoleStatements: iamRoleStatements } } }; return result; };
the_stack
import { assert } from 'chai' import { Wallet, XrplNetwork, XrpUtils } from 'xpring-common-js' import WebSocketNetworkClient from '../../src/XRP/network-clients/web-socket-network-client' import GrpcNetworkClient from '../../src/XRP/network-clients/grpc-xrp-network-client' import { ResponseStatus, WebSocketFailureResponse, TransactionResponse, AccountOffersSuccessfulResponse, RipplePathFindSuccessfulResponse, SourceCurrency, } from '../../src/XRP/shared/rippled-web-socket-schema' import XrpError from '../../src/XRP/shared/xrp-error' import XrpClient from '../../src/XRP/xrp-client' import IssuedCurrency from '../../src/XRP/shared/issued-currency' import IssuedCurrencyClient from '../../src/XRP/issued-currency-client' import XRPTestUtils from './helpers/xrp-test-utils' import { RippledErrorMessages } from '../../src/XRP/shared/rippled-error-messages' // A timeout for these tests. // eslint-disable-next-line @typescript-eslint/no-magic-numbers -- 1 minute in milliseconds const timeoutMs = 60 * 1000 const rippledGrpcUrl = 'test.xrp.xpring.io:50051' const rippledWebSocketUrl = 'wss://wss.test.xrp.xpring.io' const webSocketNetworkClient = new WebSocketNetworkClient( rippledWebSocketUrl, console.log, ) const grpcNetworkClient = new GrpcNetworkClient(rippledGrpcUrl) function sleep(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)) } describe('WebSocket Tests', function (): void { // A Wallet with some balance on Testnet. let wallet: Wallet let wallet2: Wallet let issuedCurrencyClient: IssuedCurrencyClient before(async function () { wallet = await XRPTestUtils.randomWalletFromFaucet() wallet2 = await XRPTestUtils.randomWalletFromFaucet() issuedCurrencyClient = new IssuedCurrencyClient( grpcNetworkClient, webSocketNetworkClient, XrplNetwork.Test, ) }) after(function (done) { webSocketNetworkClient.close() done() }) it('subscribeToAccount/unsubscribeFromAccount - valid request', async function (): Promise<void> { this.timeout(timeoutMs) const xrpAmount = '100' let messageReceived = false const callback = (data: TransactionResponse) => { if (messageReceived) { assert.fail('Second message should not be received after unsubscribing') } messageReceived = true assert.equal(data.engine_result, 'tesSUCCESS') assert.equal(data.engine_result_code, 0) assert.equal( data.engine_result_message, 'The transaction was applied. Only final in a validated ledger.', ) assert.equal(data.meta.TransactionResult, 'tesSUCCESS') assert.equal(data.status, 'closed') assert.equal(data.type, 'transaction') assert.equal(data.validated, true) assert.equal(data.transaction.Amount, xrpAmount) assert.equal(data.transaction.Destination, address) assert.equal(data.transaction.TransactionType, 'Payment') } const waitUntilMessageReceived = async () => { while (!messageReceived) { await sleep(5) } } const xrpClient = new XrpClient(rippledGrpcUrl, XrplNetwork.Test) // GIVEN a valid test address const xAddress = wallet.getAddress() const classicAddress = XrpUtils.decodeXAddress(xAddress) const address = classicAddress!.address // WHEN subscribeToAccount is called for that address const subscribeResponse = await webSocketNetworkClient.subscribeToAccount( address, callback, ) // THEN the subscribe request is successfully submitted and received assert.equal(subscribeResponse.status, ResponseStatus.success) assert.equal(subscribeResponse.type, 'response') // WHEN a payment is sent to that address await xrpClient.sendXrp(xrpAmount, xAddress, wallet2) await waitUntilMessageReceived() // THEN the payment is successfully received assert(messageReceived) // WHEN unsubscribe is called for that address const unsubscribeResponse = await webSocketNetworkClient.unsubscribeFromAccount( address, ) // THEN the unsubscribe request is successfully submitted and received assert.equal(unsubscribeResponse.status, ResponseStatus.success) assert.equal(unsubscribeResponse.type, 'response') // WHEN a payment is sent to that address await xrpClient.sendXrp(xrpAmount, xAddress, wallet2) // THEN the payment is not received by the callback // (If a payment is received, fail will be called in the callback) }) it('subscribeToAccount - bad address', async function (): Promise<void> { this.timeout(timeoutMs) // GIVEN a test address that is malformed. const address = 'badAddress' // WHEN subscribeToAccount is called for that address THEN an error is thrown. try { await webSocketNetworkClient.subscribeToAccount( address, // eslint-disable-next-line @typescript-eslint/no-empty-function () => {}, ) assert.fail('Method call should fail') } catch (e) { if (!(e instanceof XrpError)) { assert.fail('wrong error') } } }) it('unsubscribeFromAccount - not-subscribed address', async function (): Promise<void> { this.timeout(timeoutMs) // GIVEN a test address that is not subscribed to. const xAddress = wallet2.getAddress() const classicAddress = XrpUtils.decodeXAddress(xAddress) const address = classicAddress!.address // WHEN unsubscribeFromAccount is called for that address THEN an error is thrown. try { await webSocketNetworkClient.unsubscribeFromAccount(address) assert.fail('Method call should fail') } catch (e) { if (!(e instanceof XrpError)) { assert.fail('wrong error') } } }) it('unsubscribeFromAccount - bad address', async function (): Promise<void> { this.timeout(timeoutMs) // GIVEN a test address that is malformed. const address = 'badAddress' // WHEN unsubscribeFromAccount is called for that address THEN an error is thrown. try { await webSocketNetworkClient.unsubscribeFromAccount(address) assert.fail('Method call should fail') } catch (e) { if (!(e instanceof XrpError)) { assert.fail('wrong error') } } }) it('getAccountOffers - valid requests', async function (): Promise<void> { this.timeout(timeoutMs) const issuedCurrencyClient = IssuedCurrencyClient.issuedCurrencyClientWithEndpoint( rippledGrpcUrl, rippledWebSocketUrl, console.log, XrplNetwork.Test, ) // GIVEN a valid test address with no offers const xAddress = wallet.getAddress() const classicAddress = XrpUtils.decodeXAddress(xAddress) const address = classicAddress!.address // WHEN getAccountOffers is called for that address const accountOfferResponse = await webSocketNetworkClient.getAccountOffers( address, ) // THEN the request is successfully submitted and received, with no listed offers assert.equal(accountOfferResponse.status, ResponseStatus.success) assert.equal(accountOfferResponse.type, 'response') const result = (accountOfferResponse as AccountOffersSuccessfulResponse) .result assert.equal(result.account, address) assert.isEmpty(result.offers) this.timeout(timeoutMs) // GIVEN a valid test address with an offer const takerGetsIssuedCurrency: IssuedCurrency = { issuer: address, currency: 'FAK', value: '100', } const takerPaysXrp = '50' await issuedCurrencyClient.createOffer( wallet, takerGetsIssuedCurrency, takerPaysXrp, ) // WHEN getAccountOffers is called for that address const accountOfferResponse2 = await webSocketNetworkClient.getAccountOffers( address, ) // THEN the request is successfully submitted and received, with the one listed offer assert.equal(accountOfferResponse2.status, ResponseStatus.success) assert.equal(accountOfferResponse2.type, 'response') const result2 = (accountOfferResponse2 as AccountOffersSuccessfulResponse) .result assert.equal(result2.account, address) assert.isNotEmpty(result2.offers) const offer = result2.offers[0] assert.equal(offer.taker_pays, takerPaysXrp) assert.deepEqual(offer.taker_gets, takerGetsIssuedCurrency) issuedCurrencyClient.webSocketNetworkClient.close() }) it('getAccountOffers - bad address', async function (): Promise<void> { this.timeout(timeoutMs) // GIVEN a test address that is malformed. const address = 'badAddress' // WHEN getAccountOffers is called for that address THEN an error is thrown. const response = await webSocketNetworkClient.getAccountOffers(address) assert.equal(response.status, ResponseStatus.error) assert.equal(response.type, 'response') const errorResponse = response as WebSocketFailureResponse assert.equal(errorResponse.error, RippledErrorMessages.accountNotFound) }) it('findRipplePath - success, mandatory fields', async function (): Promise<void> { this.timeout(timeoutMs) const sourceAddress = XrpUtils.decodeXAddress(wallet.getAddress())!.address const destinationAddress = XrpUtils.decodeXAddress(wallet2.getAddress())! .address const destinationAmount: IssuedCurrency = { currency: 'CNY', issuer: 'razqQKzJRdB4UxFPWf5NEpEG3WMkmwgcXA', value: '50', } // GIVEN two valid test addresses // WHEN findRipplePath is called between those addresses const response = await webSocketNetworkClient.findRipplePath( sourceAddress, destinationAddress, destinationAmount, ) // THEN the request is successfully submitted and received assert.equal(response.status, 'success') assert.equal(response.type, 'response') // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion const result = (response as RipplePathFindSuccessfulResponse).result assert.equal(result.destination_account, destinationAddress) assert.deepEqual(result.destination_amount, destinationAmount) assert.equal(result.source_account, sourceAddress) assert.include(result.destination_currencies, 'XRP') }) it('findRipplePath - failure, both sendMax and sourceCurrencies', async function (): Promise<void> { this.timeout(timeoutMs) const sourceAddress = XrpUtils.decodeXAddress(wallet.getAddress())!.address const destinationAddress = XrpUtils.decodeXAddress(wallet2.getAddress())! .address const destinationAmount: IssuedCurrency = { currency: 'CNY', issuer: 'razqQKzJRdB4UxFPWf5NEpEG3WMkmwgcXA', value: '50', } const sendMaxAmount = '100' const sourceCurrency: SourceCurrency = { currency: 'USD' } // GIVEN two valid test addresses // WHEN findRipplePath is called between those addresses THEN an error is thrown. try { await webSocketNetworkClient.findRipplePath( sourceAddress, destinationAddress, destinationAmount, sendMaxAmount, [sourceCurrency], ) assert.fail('Method call should fail') } catch (e) { if (!(e instanceof XrpError)) { assert.fail('wrong error') } } }) it('findRipplePath - successful direct path', async function (): Promise<void> { this.timeout(timeoutMs) const sourceAddress = XrpUtils.decodeXAddress(wallet.getAddress())!.address const destinationAddress = XrpUtils.decodeXAddress(wallet2.getAddress())! .address // GIVEN two valid test addresses with a trust line between them const trustLineLimit = '200' const trustLineCurrency = 'FOO' await issuedCurrencyClient.createTrustLine( wallet.getAddress(), trustLineCurrency, trustLineLimit, wallet2, ) const destinationAmount: IssuedCurrency = { issuer: destinationAddress, currency: trustLineCurrency, value: '50', } // WHEN findRipplePath is called between those addresses const response = await webSocketNetworkClient.findRipplePath( sourceAddress, destinationAddress, destinationAmount, ) // THEN the request is successfully submitted and received assert.equal(response.status, 'success') assert.equal(response.type, 'response') // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion const result = (response as RipplePathFindSuccessfulResponse).result assert.equal(result.destination_account, destinationAddress) assert.deepEqual( result.destination_amount as IssuedCurrency, destinationAmount, ) assert.equal(result.source_account, sourceAddress) assert.include(result.destination_currencies, trustLineCurrency) assert(result.alternatives.length >= 1) }) it('findRipplePath - successful path through issuers own offer', async function (): Promise<void> { this.timeout(timeoutMs) const issuerWallet = await XRPTestUtils.randomWalletFromFaucet() const issuerClassicAddress = XrpUtils.decodeXAddress( issuerWallet.getAddress(), )!.address const sourceAddress = XrpUtils.decodeXAddress(wallet.getAddress())!.address const destinationAddress = XrpUtils.decodeXAddress(wallet2.getAddress())! .address // GIVEN two valid test addresses, an issuing address, a trust line from one test address (wallet2) to the issuer // and an offer on the dex to exchange XRP for some this issuer's issued currency. const trustLineLimit = '1000' const trustLineCurrency = 'FOO' await issuedCurrencyClient.enableRippling(issuerWallet) await issuedCurrencyClient.createTrustLine( issuerWallet.getAddress(), trustLineCurrency, trustLineLimit, wallet2, ) // Create an offer to accept XRP in exchange for FOO const takerGetsAmount: IssuedCurrency = { currency: trustLineCurrency, issuer: issuerClassicAddress, value: '200', } const takerPaysAmount = '200000000' // 200 XRP, 1:1 exchange rate await issuedCurrencyClient.createOffer( issuerWallet, takerGetsAmount, takerPaysAmount, ) // WHEN findRipplePath is called between the two non-issuing addresses, offering to spend XRP and deliver FOO const destinationAmount: IssuedCurrency = { issuer: issuerClassicAddress, currency: trustLineCurrency, value: '50', } const sourceCurrency: SourceCurrency = { currency: 'XRP', } const sourceCurrencies = [sourceCurrency] const response = await webSocketNetworkClient.findRipplePath( sourceAddress, destinationAddress, destinationAmount, undefined, sourceCurrencies, ) // THEN the request is successfully submitted and received assert.equal(response.status, 'success') assert.equal(response.type, 'response') // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion const result = (response as RipplePathFindSuccessfulResponse).result assert.equal(result.destination_account, destinationAddress) assert.deepEqual(result.destination_amount, destinationAmount) assert.equal(result.source_account, sourceAddress) assert.include(result.destination_currencies, 'FOO') assert(result.alternatives.length >= 1) }) it('findRipplePath - successful path through third-party offer', async function (): Promise<void> { this.timeout(timeoutMs) const issuerWallet = await XRPTestUtils.randomWalletFromFaucet() const offerCreatorWallet = await XRPTestUtils.randomWalletFromFaucet() const issuerClassicAddress = XrpUtils.decodeXAddress( issuerWallet.getAddress(), )!.address const sourceAddress = XrpUtils.decodeXAddress(wallet.getAddress())!.address const destinationAddress = XrpUtils.decodeXAddress(wallet2.getAddress())! .address // GIVEN two valid test addresses, an issuing address, a trust line from one test address (wallet2) to the issuer // and an offer on the dex to exchange XRP for some this issuer's issued currency. const trustLineLimit = '1000' const trustLineCurrency = 'FOO' await issuedCurrencyClient.enableRippling(issuerWallet) await issuedCurrencyClient.createTrustLine( issuerWallet.getAddress(), trustLineCurrency, trustLineLimit, offerCreatorWallet, ) await issuedCurrencyClient.createTrustLine( issuerWallet.getAddress(), trustLineCurrency, trustLineLimit, wallet2, ) // Fund an address with some issued currency, who can then create an offer. await issuedCurrencyClient.createIssuedCurrency( issuerWallet, offerCreatorWallet.getAddress(), trustLineCurrency, '500', ) // Create an offer to accept XRP in exchange for FOO const takerGetsAmount: IssuedCurrency = { currency: trustLineCurrency, issuer: issuerClassicAddress, value: '200', } const takerPaysAmount = '200000000' // 200 XRP, 1:1 exchange rate await issuedCurrencyClient.createOffer( offerCreatorWallet, takerGetsAmount, takerPaysAmount, ) // WHEN findRipplePath is called between the two non-issuing addresses, offering to spend XRP and deliver FOO const destinationAmount: IssuedCurrency = { issuer: issuerClassicAddress, currency: trustLineCurrency, value: '50', } const sourceCurrency: SourceCurrency = { currency: 'XRP', } const sourceCurrencies = [sourceCurrency] const response = await webSocketNetworkClient.findRipplePath( sourceAddress, destinationAddress, destinationAmount, undefined, sourceCurrencies, ) // THEN the request is successfully submitted and received assert.equal(response.status, 'success') assert.equal(response.type, 'response') // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion const result = (response as RipplePathFindSuccessfulResponse).result assert.equal(result.destination_account, destinationAddress) assert.deepEqual(result.destination_amount, destinationAmount) assert.equal(result.source_account, sourceAddress) assert.include(result.destination_currencies, 'FOO') assert(result.alternatives.length >= 1) }) it('findRipplePath - special sendMax case', async function (): Promise<void> { this.timeout(timeoutMs) const sourceAddress = XrpUtils.decodeXAddress(wallet.getAddress())!.address const destinationAddress = XrpUtils.decodeXAddress(wallet2.getAddress())! .address const destinationAmount = '-1' const sendMaxAmount: IssuedCurrency = { issuer: 'razqQKzJRdB4UxFPWf5NEpEG3WMkmwgcXA', currency: 'CNY', value: '50', } // GIVEN two valid test addresses // WHEN findRipplePath is called between those addresses const response = await webSocketNetworkClient.findRipplePath( sourceAddress, destinationAddress, destinationAmount, sendMaxAmount, ) // THEN the request is successfully submitted and received assert.equal(response.status, 'success') assert.equal(response.type, 'response') // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion const result = (response as RipplePathFindSuccessfulResponse).result assert.equal(result.destination_account, destinationAddress) assert.equal(result.destination_amount, destinationAmount) assert.equal(result.source_account, sourceAddress) assert.include(result.destination_currencies, 'XRP') }) })
the_stack
/// <reference types="node" /> import events = require("events"); import stream = require("stream"); export interface ConnectOpts { adapter: string; } export interface Adapter { name: string; /** * Create a new connection object. In common usage, config will be created by parse-db-url and passed to the adapter by any-db. * If a continuation is given, it must be called, either with an error or the established connection. */ createConnection(opts: ConnectOpts, callback?: (error: Error, result: Connection) => void): Connection; /** * Create a Query that may eventually be executed later on by a Connection. While this function is rarely needed by user code, * it makes it possible for ConnectionPool.query and Transaction.query to fulfill the Queryable.query contract * by synchronously returning a Query stream */ createQuery(text: string, params?: any[], callback?: (error: Error, result: ResultSet) => void): Query; createQuery(query: Query): Query; } /** * Other properties are driver specific */ export interface Field { name: string; } /** * ResultSet objects are just plain data that collect results of a query when a continuation * is provided to Queryable.query. The lastInsertId is optional, and currently supported by * sqlite3 and mysql but not postgres, because it is not supported by Postgres itself. */ export interface ResultSet { /** * Affected rows. Note e.g. for INSERT queries the rows property is not filled even * though rowCount is non-zero. */ rowCount: number; /** * Result rows */ rows: any[]; /** * Result field descriptions */ fields: Field[]; /** * Not supported by all drivers. */ fieldCount?: number; /** * Not supported by all drivers. */ lastInsertId?: any; /** * Not supported by all drivers. */ affectedRows?: number; /** * Not supported by all drivers. */ changedRows?: number; } /** * Query objects are returned by the Queryable.query method, available on connections, * pools, and transactions. Queries are instances of Readable, and as such can be piped * through transforms and support backpressure for more efficient memory-usage on very * large results sets. (Note: at this time the sqlite3 driver does not support backpressure) * * Internally, Query instances are created by a database Adapter and may have more methods, * properties, and events than are described here. Consult the documentation for your * specific adapter to find out about any extensions. * * Events: * * Error event * The 'error' event is emitted at most once per query. Note that this event will be * emitted for errors even if a callback was provided, the callback will * simply be subscribed to the 'error' event. * One argument is passed to event listeners: * error - the error object. * * Fields event * A 'fields' event is emmitted before any 'data' events. * One argument is passed to event listeners: * fields - an array of [Field][ResultSet] objects. * * The following events are part of the stream.Readable interface which is implemented by Query: * * Data event * A 'data' event is emitted for each row in the query result set. * One argument is passed to event listeners: * row contains the contents of a single row in the query result * * Close event * A 'close' event is emitted when the query completes. * No arguments are passed to event listeners. * * End event * An 'end' event is emitted after all query results have been consumed. * No arguments are passed to event listeners. */ export interface Query extends stream.Readable { /** * The SQL query as a string. If you are using MySQL this will contain * interpolated values after the query has been enqueued by a connection. */ text: string; /** * The array of parameter values. */ values: any[]; /** * The callback (if any) that was provided to Queryable.query. Note that * Query objects must not use a closed over reference to their callback, * as other any-db libraries may rely on modifying the callback property * of a Query they did not create. */ callback: (error: Error, results: ResultSet) => void; } /** * Events: * The 'query' event is emitted immediately before a query is executed. One argument is passed to event handlers: * - query: a Query object */ export interface Queryable extends events.EventEmitter { /** * The Adapter instance that will be used by this Queryable for creating Query instances and/or connections. */ adapter: Adapter; /** * Execute a SQL statement using bound parameters (if they are provided) and return a Query object * that is a Readable stream of the resulting rows. If a Continuation<ResultSet> is provided the rows * returned by the database will be aggregated into a [ResultSet][] which will be passed to the * continuation after the query has completed. * The second form is not needed for normal use, but must be implemented by adapters to work correctly * with ConnectionPool and Transaction. See Adapter.createQuery for more details. */ query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query /** * The second form is not needed for normal use, but must be implemented by adapters to work correctly * with ConnectionPool and Transaction. See Adapter.createQuery for more details. */ // query(query: Query): Query; } /** * Connection objects are obtained using createConnection from Any-DB or ConnectionPool.acquire, * both of which delegate to the createConnection implementation of the specified adapter. * While all Connection objects implement the Queryable interface, the implementations in * each adapter may add additional methods or emit additional events. If you need to access a * feature of your database that is not described here (such as Postgres' server-side prepared * statements), consult the documentation for your adapter. * * Events: * Error event * The 'error' event is emitted when there is a connection-level error. * No arguments are passed to event listeners. * * Open event * The 'open' event is emitted when the connection has been established and is ready to query. * No arguments are passed to event listeners. * * Close event * The 'close' event is emitted when the connection has been closed. * No arguments are passed to event listeners. */ export interface Connection extends Queryable { /** * Close the database connection. If a continuation is provided it * will be called after the connection has closed. */ end(callback?: (error: Error) => void): void; } export interface ConnectionStatic { new (): Connection; name: string; createConnection(): void; createPool(): void; } /** * ConnectionPool events * 'acquire' - emitted whenever pool.acquire is called * 'release' - emitted whenever pool.release is called * 'query', query - emitted immediately after .query is called on a * connection via pool.query. The argument is a Query object. * 'close' - emitted when the connection pool has closed all of it * connections after a call to close(). */ export interface ConnectionPool extends Queryable { /** * Implements Queryable.query by automatically acquiring a connection * and releasing it when the query completes. */ query(text: string, params?: any[], callback?: (error: Error, results: ResultSet) => void): Query; /** * Remove a connection from the pool. If you use this method you must * return the connection back to the pool using ConnectionPool.release */ acquire(callback: (error: Error, result: Connection) => void): void; /** * Return a connection to the pool. This should only be called with connections * you've manually acquired. You must not continue to use the connection after releasing it. */ release(connection: Connection): void; /** * Stop giving out new connections, and close all existing database connections as they * are returned to the pool. */ close(callback?: (error: Error) => void): void; } /** * A PoolConfig is generally a plain object with any of the following properties (they are all optional): */ export interface PoolConfig { /** * min (default 0) The minimum number of connections to keep open in the pool. */ min?: number; /** * max (default 10) The maximum number of connections to keep open in the pool. * When this limit is reached further requests for connections will queue waiting * for an existing connection to be released back into the pool. */ max?: number; /** * (default 30000) The maximum amount of time a connection can sit idle in the pool before being reaped */ idleTimeout?: number; /** * (default 1000) How frequently the pool should check for connections that are old enough to be reaped. */ reapInterval?: number; /** * (default true) When this is true, the pool will reap connections that * have been idle for more than idleTimeout milliseconds. */ refreshIdle?: boolean; /** * Called immediately after a connection is first established. Use this to do one-time setup of new connections. * The supplied Connection will not be added to the pool until you pass it to the done continuation. */ onConnect?: (connection: Connection, ready: (error: Error, result: Connection) => void) => void; /** * Called each time a connection is returned to the pool. Use this to restore a connection to * it's original state (e.g. rollback transactions, set the database session vars). If reset * fails to call the done continuation the connection will be lost in limbo. */ reset?: (connection: Connection, done: (error: Error) => void) => void; /** * (default function (err) { return true }) - Called when an error is encountered * by pool.query or emitted by an idle connection. If shouldDestroyConnection(error) * is truthy the connection will be destroyed, otherwise it will be reset. */ shouldDestroyConnection?: (error: Error) => boolean; } /** * Create a database connection. * @param url String of the form adapter://user:password@host/database * @param callback * @returns Connection object. */ export declare function createConnection(url: string, callback?: (error: Error, connection: Connection) => void): Connection; /** * Create a database connection. * @param opts Object with adapter name and any properties that the given adapter requires * @param callback * @returns Connection object. */ export declare function createConnection(opts: ConnectOpts, callback?: (error: Error, connection: Connection) => void): Connection; export declare function createPool(url: string, config: PoolConfig): ConnectionPool; export declare function createPool(opts: ConnectOpts, config: PoolConfig): ConnectionPool;
the_stack
import * as Sentry from '@sentry/react' import { CaptureContext } from '@sentry/types' import mixpanel from 'mixpanel-browser' import { autorun } from 'mobx' import { hotjar } from 'react-hotjar' import { config } from '../../config' import { RootStore } from '../../Store' import { MachineInfo, MiningStatus } from '../machine/models' import { NotificationMessage } from '../notifications/models' import { Profile } from '../profile/models' import { Reward } from '../reward/models' import { getRewardAvailability } from '../reward/utils' import { AntiVirusSoftware } from '../zendesk/models' export class AnalyticsStore { private started = false private mixpanelInitialized = false private previousStatus?: MiningStatus private previousStatusTimestamp?: number constructor(private readonly store: RootStore) { hotjar.initialize(2225817, 6) const token = config.mixpanelToken if (!token) { return } this.mixpanelInitialized = true mixpanel.init(token, { api_host: `${config.apiBaseUrl}/api/v2/mixpanel`, ignore_dnt: true, secure_cookie: true, xhr_headers: { rid: 'session', }, }) autorun(() => { console.log(`Detected change in status:${this.store.saladBowl.status}`) this.trackMiningStatus( this.store.saladBowl.status, this.store.saladBowl.plugin.name || '-', this.store.saladBowl.plugin.version || '-', this.store.saladBowl.plugin.algorithm || '-', ) }) } public start = (profile: Profile) => { if (this.started) { console.warn('Already started analytics. Skipping...') return } this.started = true Sentry.configureScope((scope) => { scope.setUser({ id: profile.id, email: profile.email, username: profile.username, }) }) if (this.mixpanelInitialized) { mixpanel.register({ $app_build_number: config.appBuild, Platform: this.store.native.platform, }) if (this.store.native.desktopVersion) { mixpanel.register({ $app_version_string: this.store.native.desktopVersion, }) } mixpanel.people.set({ Id: profile.id, $email: profile.email, $last_name: profile.username, $last_login: new Date().toISOString(), }) mixpanel.people.set_once({ 'First login': new Date().toISOString(), }) mixpanel.identify(profile.id) this.track('Login') } } public trackDesktopVersion = (version: string) => { if (!this.mixpanelInitialized) return mixpanel.register({ $app_version_string: version, }) } public trackMachineInformation = (info: MachineInfo) => { if (this.started) return if (!this.mixpanelInitialized) return const machineData = { 'Machine OS Distro': info.os?.distro, 'Machine OS Release': info.os?.release, 'Machine OS Arch': info.os?.arch, 'Machine Virtual': info.system?.virtual, // @ts-ignore TODO: Update ts definitions from hypervizor to hypervisor 'Machine HyperV': info.os?.hypervisor, 'Machine CPU': `${info.cpu?.manufacturer} ${info.cpu?.brand}`, 'Machine GPU': info.graphics?.controllers.map((x) => x.model), 'Machine RAM': `${ info.memLayout && info.memLayout.reduce((amount, memory) => amount + memory.size, 0) / (1024 * 1024 * 1024) } GB`, } // Adds machine information to every subsequent message mixpanel.register(machineData) this.track('Machine Registered') } public trackLogout = () => { if (!this.started) return this.started = false Sentry.configureScope((scope) => scope.setUser(null)) if (this.mixpanelInitialized) { this.track('Logout') mixpanel.reset() } } /** Tracks when a user views the What's New page */ public trackWhatsNew = (version: string) => { if (!this.mixpanelInitialized) return this.track('Whats New', { Version: version, }) mixpanel.people.set({ 'Whats New Version': version, }) } /** Track when mining starts */ public trackStart = ( reason: string, gpuEnabled: boolean, cpuEnabled: boolean, gpuNames: string[], cpuName: string, gpuOverridden: boolean, cpuOverridden: boolean, ) => { this.track('Start', { Reason: reason, GpuEnabled: gpuEnabled, CpuEnabled: cpuEnabled, GPUNames: gpuNames, CPUName: cpuName, GPUOverridden: gpuOverridden, CPUOverridden: cpuOverridden, }) } /** * Tracks when mining stops * @param reason Why did mining stop * @param totalTime Total time between start and stop (ms) * @param choppingTime Total time in the chopping state (ms) */ public trackStop = (reason: string, totalTime: number, choppingTime: number) => { this.track('Stop', { Reason: reason, TotalTime: totalTime, ChoppingTime: choppingTime, }) } public trackAutoStart = (enabled: boolean) => { if (!this.mixpanelInitialized) return this.track('AutoStart', { Enabled: enabled, }) mixpanel.people.set({ AutoStart: enabled, }) } public trackMiningStatus = (status: MiningStatus, pluginName: string, pluginVersion: string, algorithm: string) => { const now = Date.now() let previousTotalTime: number | undefined = undefined if (this.previousStatusTimestamp) { previousTotalTime = now - this.previousStatusTimestamp } this.track('Mining Status', { PrevStatus: this.previousStatus, MiningStatus: status, PluginName: pluginName, PluginVersion: pluginVersion, PrevTime: previousTotalTime, Algorithm: algorithm, }) if (status === MiningStatus.Stopped) { this.previousStatus = undefined this.previousStatusTimestamp = undefined } else { this.previousStatus = status this.previousStatusTimestamp = now } } /** Track when a machine goes to the earning state */ public trackMiningError = (type: string, errorCode: number) => { this.track('Mining Error', { ErrorType: type, ErrorCode: errorCode }) } /** Track when a reward is clicked */ public trackClickedReward = (reward: Partial<Reward>) => { const availability = getRewardAvailability(reward) this.track('Reward Clicked', { Availability: availability, RewardId: reward.id, RewardName: reward.name, RewardPrice: reward.price, RewardCategory: reward.tags, }) } /** Track when a reward is selected */ public trackSelectedReward = (reward: Reward) => { const availability = getRewardAvailability(reward) this.track('Reward Selected', { Availability: availability, RewardId: reward.id, RewardName: reward.name, RewardPrice: reward.price, RewardCategory: reward.tags, }) } /** Track when a reward is viewed */ public trackRewardView = (reward: Reward) => { const availability = getRewardAvailability(reward) this.track('Reward Viewed', { Availability: availability, RewardId: reward.id, RewardName: reward.name, RewardPrice: reward.price, RewardCategory: reward.tags, }) } /** Track when a reward category is viewed */ public trackRewardSearch = (searchTerm: string) => { this.track('Reward Search', { Term: searchTerm, }) } /** Track when a SaladPay is opened for a reward */ public trackSaladPayOpened = (reward: Reward) => { const availability = getRewardAvailability(reward) this.track('SaladPay Opened', { Availability: availability, RewardId: reward.id, RewardName: reward.name, RewardPrice: reward.price, RewardCategory: reward.tags, }) } /** Track when a reward is redeemed */ public trackRewardRedeemed = (reward: Reward, inProcess?: boolean) => { const trackingEvent = inProcess ? 'Reward Redemption In Process' : 'Reward Redeemed' const availability = getRewardAvailability(reward) this.track(trackingEvent, { Availability: availability, RewardId: reward.id, RewardName: reward.name, RewardPrice: reward.price, RewardCategory: reward.tags, }) } /** Track when a referral is sent */ public trackReferralSent = () => { this.track('Referral Sent') } /** Track when a header link is clicked */ private trackHeaderLinkClicked = (currentPath: string, to: string, label: string) => { this.track('Header Link Clicked', { CurrentPath: currentPath, To: to, Label: label, }) } /** Track when a sidebar link is clicked */ private trackSidebarLinkClicked = (currentPath: string, to: string, label: string) => { this.track('Sidebar Link Clicked', { CurrentPath: currentPath, To: to, Label: label, }) } /** Track when a link is clicked */ private trackLinkClicked = (currentPath: string, to: string, label: string) => { this.track('Link Clicked', { CurrentPath: currentPath, To: to, Label: label, }) } /** Track smart link based on what type was clicked */ public trackSmartLink = (to: string, label: string, type?: 'header' | 'sidebar') => { const currentPath = window && window.location.pathname switch (type) { case 'header': this.trackHeaderLinkClicked(currentPath, to, label) break case 'sidebar': this.trackSidebarLinkClicked(currentPath, to, label) break default: this.trackLinkClicked(currentPath, to, label) break } } /** Track when an element is clicked */ public trackElementClicked = (id: string, label: string) => { const currentPath = window && window.location.pathname this.track('Element Clicked', { CurrentPath: currentPath, Id: id, Label: label, }) } /** Track when a button is clicked */ public trackButtonClicked = (id: string, label: string, state: 'enabled' | 'disabled') => { const currentPath = window && window.location.pathname this.track('Button Clicked', { CurrentPath: currentPath, Id: id, Label: label, State: state, }) } /** Track when a switch is toggled */ public trackSwitchToggle = (id: string, label: string, checked: boolean) => { const currentPath = window && window.location.pathname this.track('Switch Toggled', { CurrentPath: currentPath, Id: id, Label: label, Checked: checked, }) } /** Track when the close app button is clicked */ public trackCloseAppClicked = (minimizeToTray: 'enabled' | 'disabled') => { const currentPath = window && window.location.pathname this.track('Close App Button Clicked', { CurrentPath: currentPath, Id: 'close_app_button_clicked', Label: 'Closed App', MinimizeToTray: minimizeToTray, }) } /** Track when a toast notification is shown */ public trackToastNotificationShown = (message: NotificationMessage) => { const type = message.type ? message.type : 'normal' this.track('Toast Notification Shown', { Category: message.category, Title: message.title, Message: message.message, Type: type, }) } /** Track when a toast notification is clicked */ public trackToastNotificationClicked = (message: NotificationMessage) => { const type = message.type ? message.type : 'normal' this.track('Toast Notification Clicked', { Category: message.category, Title: message.title, Message: message.message, Type: type, }) } /** Track when a toast notification is clicked */ public trackToastNotificationClosed = (message: NotificationMessage) => { const type = message.type ? message.type : 'normal' this.track('Toast Notification Closed', { Category: message.category, Title: message.title, Message: message.message, Type: type, }) } /** Track when an Error Page is viewed by the user */ public trackErrorPageViewed = (name: string) => { const currentPath = window && window.location.pathname this.track('Error Page Viewed', { CurrentPath: currentPath, ErrorPage: name, }) } /** Track a user as they go through the onboarding flow. Types will only be used if there are different variations of pages that can be shown e.g. different AV guides. */ public trackOnboardingPageViewed = (page: string, order: number, type?: string) => { const currentPath = window && window.location.pathname this.track('Onboarding', { CurrentPath: currentPath, page: page, order: order, type: type, }) } /** Track which onboarding antivirus guide was viewed **/ public trackOnboardingAntivirusGuideViewed = (to: string, antivirus: AntiVirusSoftware) => { const currentPath = window && window.location.pathname this.track('Onboarding Antivirus Guide Viewed', { CurrentPath: currentPath, To: to, AntivirusSoftware: antivirus, }) } private track = (event: string, properties?: { [key: string]: any }) => { if (!this.mixpanelInitialized) return mixpanel.track(event, properties) } public captureException = (err: Error, scope?: CaptureContext) => { console.error(err) Sentry.withScope((s) => { s.setFingerprint([err.name, err.message]) Sentry.captureException(err, scope) }) } }
the_stack
import { Collection, CollectionInsertOneOptions, CommonOptions, Cursor, DeleteWriteOpResultObject, FilterQuery, FindAndModifyWriteOpResultObject, FindOneAndUpdateOption, FindOneOptions, IndexSpecification, InsertOneWriteOpResult, InsertWriteOpResult, ObjectID, ObjectId, OptionalId, UpdateManyOptions, UpdateOneOptions, UpdateQuery, UpdateWriteOpResult, WithId, WithoutProjection, WriteOpResult, } from 'mongodb'; import { IRocketChatRecord, RocketChatRecordDeleted, } from '../../../../definition/IRocketChatRecord'; import { setUpdatedAt } from '../lib/setUpdatedAt'; export { IndexSpecification } from 'mongodb'; // [extracted from @types/mongo] TypeScript Omit (Exclude to be specific) does not work for objects with an "any" indexed type, and breaks discriminated unions type EnhancedOmit<T, K> = string | number extends keyof T ? T // T has indexed type e.g. { _id: string; [k: string]: any; } or it is "any" : T extends any ? Pick<T, Exclude<keyof T, K>> // discriminated unions : never; // [extracted from @types/mongo] type ExtractIdType<TSchema> = TSchema extends { _id: infer U } // user has defined a type for _id ? {} extends U ? Exclude<U, {}> : unknown extends U ? ObjectId : U : ObjectId; export type ModelOptionalId<T> = EnhancedOmit<T, '_id'> & { _id?: ExtractIdType<T> }; // InsertionModel forces both _id and _updatedAt to be optional, regardless of how they are declared in T export type InsertionModel<T> = EnhancedOmit<ModelOptionalId<T>, '_updatedAt'> & { _updatedAt?: Date; }; export interface IBaseRaw<T> { col: Collection<T>; } const baseName = 'rocketchat_'; type DefaultFields<Base> = Record<keyof Base, 1> | Record<keyof Base, 0> | void; type ResultFields<Base, Defaults> = Defaults extends void ? Base : Defaults[keyof Defaults] extends 1 ? Pick<Defaults, keyof Defaults> : Omit<Defaults, keyof Defaults>; const warnFields = process.env.NODE_ENV !== 'production' ? (...rest: any): void => { console.warn(...rest, new Error().stack); } : new Function(); export class BaseRaw<T, C extends DefaultFields<T> = undefined> implements IBaseRaw<T> { public readonly defaultFields: C; protected indexes?: IndexSpecification[]; protected name: string; private preventSetUpdatedAt: boolean; public readonly trash?: Collection<RocketChatRecordDeleted<T>>; constructor( public readonly col: Collection<T>, trash?: Collection<T>, options?: { preventSetUpdatedAt?: boolean }, ) { this.name = this.col.collectionName.replace(baseName, ''); this.trash = trash as unknown as Collection<RocketChatRecordDeleted<T>>; if (this.indexes?.length) { this.col.createIndexes(this.indexes); } this.preventSetUpdatedAt = options?.preventSetUpdatedAt ?? false; } private doNotMixInclusionAndExclusionFields(options: FindOneOptions<T> = {}): FindOneOptions<T> { const optionsDef = this.ensureDefaultFields(options); if (optionsDef?.projection === undefined) { return optionsDef; } const projection: Record<string, any> = optionsDef?.projection; const keys = Object.keys(projection); const removeKeys = keys.filter((key) => projection[key] === 0); if (keys.length > removeKeys.length) { removeKeys.forEach((key) => delete projection[key]); } return { ...optionsDef, projection, }; } private ensureDefaultFields( options?: undefined, ): C extends void ? undefined : WithoutProjection<FindOneOptions<T>>; private ensureDefaultFields( options: WithoutProjection<FindOneOptions<T>>, ): WithoutProjection<FindOneOptions<T>>; private ensureDefaultFields<P>(options: FindOneOptions<P>): FindOneOptions<P>; private ensureDefaultFields<P>( options?: any, ): FindOneOptions<P> | undefined | WithoutProjection<FindOneOptions<T>> { if (this.defaultFields === undefined) { return options; } const { fields: deprecatedFields, projection, ...rest } = options || {}; if (deprecatedFields) { warnFields("Using 'fields' in models is deprecated.", options); } const fields = { ...deprecatedFields, ...projection }; return { projection: this.defaultFields, ...fields && Object.values(fields).length && { projection: fields }, ...rest, }; } public findOneAndUpdate( query: FilterQuery<T>, update: UpdateQuery<T> | T, options?: FindOneAndUpdateOption<T>, ): Promise<FindAndModifyWriteOpResultObject<T>> { return this.col.findOneAndUpdate(query, update, options); } async findOneById( _id: string, options?: WithoutProjection<FindOneOptions<T>> | undefined, ): Promise<T | null>; async findOneById<P>( _id: string, options: FindOneOptions<P extends T ? T : P>, ): Promise<P | null>; async findOneById<P>(_id: string, options?: any): Promise<T | P | null> { const query = { _id } as FilterQuery<T>; const optionsDef = this.doNotMixInclusionAndExclusionFields(options); return this.col.findOne(query, optionsDef); } async findOne(query?: FilterQuery<T> | string, options?: undefined): Promise<T | null>; async findOne( query: FilterQuery<T> | string, options: WithoutProjection<FindOneOptions<T>>, ): Promise<T | null>; async findOne<P>( query: FilterQuery<T> | string, options: FindOneOptions<P extends T ? T : P>, ): Promise<P | null>; async findOne<P>(query: FilterQuery<T> | string = {}, options?: any): Promise<T | P | null> { const q = typeof query === 'string' ? ({ _id: query } as FilterQuery<T>) : query; const optionsDef = this.doNotMixInclusionAndExclusionFields(options); return this.col.findOne(q, optionsDef); } // findUsersInRoles(): void { // throw new Error('[overwrite-function] You must overwrite this function in the extended classes'); // } find(query?: FilterQuery<T>): Cursor<ResultFields<T, C>>; find( query: FilterQuery<T>, options: WithoutProjection<FindOneOptions<T>>, ): Cursor<ResultFields<T, C>>; find<P = T>(query: FilterQuery<T>, options: FindOneOptions<P extends T ? T : P>): Cursor<P>; find<P>(query: FilterQuery<T> | undefined = {}, options?: any): Cursor<P> | Cursor<T> { const optionsDef = this.doNotMixInclusionAndExclusionFields(options); return this.col.find(query, optionsDef); } update( filter: FilterQuery<T>, update: UpdateQuery<T> | Partial<T>, options?: UpdateOneOptions & { multi?: boolean }, ): Promise<WriteOpResult> { this.setUpdatedAt(update); return this.col.update(filter, update, options); } updateOne( filter: FilterQuery<T>, update: UpdateQuery<T> | Partial<T>, options?: UpdateOneOptions & { multi?: boolean }, ): Promise<UpdateWriteOpResult> { this.setUpdatedAt(update); return this.col.updateOne(filter, update, options); } updateMany( filter: FilterQuery<T>, update: UpdateQuery<T> | Partial<T>, options?: UpdateManyOptions, ): Promise<UpdateWriteOpResult> { this.setUpdatedAt(update); return this.col.updateMany(filter, update, options); } insertMany( docs: Array<InsertionModel<T>>, options?: CollectionInsertOneOptions, ): Promise<InsertWriteOpResult<WithId<T>>> { docs = docs.map((doc) => { if (!doc._id || typeof doc._id !== 'string') { const oid = new ObjectID(); return { _id: oid.toHexString(), ...doc }; } this.setUpdatedAt(doc); return doc; }); // TODO reavaluate following type casting return this.col.insertMany(docs as unknown as Array<OptionalId<T>>, options); } insertOne( doc: InsertionModel<T>, options?: CollectionInsertOneOptions, ): Promise<InsertOneWriteOpResult<WithId<T>>> { if (!doc._id || typeof doc._id !== 'string') { const oid = new ObjectID(); doc = { _id: oid.toHexString(), ...doc }; } this.setUpdatedAt(doc); // TODO reavaluate following type casting return this.col.insertOne(doc as unknown as OptionalId<T>, options); } removeById(_id: string): Promise<DeleteWriteOpResultObject> { return this.deleteOne({ _id } as FilterQuery<T>); } async deleteOne( filter: FilterQuery<T>, options?: CommonOptions & { bypassDocumentValidation?: boolean }, ): Promise<DeleteWriteOpResultObject> { if (!this.trash) { return this.col.deleteOne(filter, options); } const doc = (await this.findOne(filter)) as unknown as (IRocketChatRecord & T) | undefined; if (doc) { const { _id, ...record } = doc; const trash = { ...record, _deletedAt: new Date(), __collection__: this.name, } as RocketChatRecordDeleted<T>; // since the operation is not atomic, we need to make sure that the record is not already deleted/inserted await this.trash?.updateOne( { _id } as FilterQuery<RocketChatRecordDeleted<T>>, { $set: trash }, { upsert: true, }, ); } return this.col.deleteOne(filter, options); } async deleteMany( filter: FilterQuery<T>, options?: CommonOptions, ): Promise<DeleteWriteOpResultObject> { if (!this.trash) { return this.col.deleteMany(filter, options); } const cursor = this.find(filter); const ids: string[] = []; for await (const doc of cursor) { const { _id, ...record } = doc as unknown as IRocketChatRecord & T; const trash = { ...record, _deletedAt: new Date(), __collection__: this.name, } as RocketChatRecordDeleted<T>; ids.push(_id); // since the operation is not atomic, we need to make sure that the record is not already deleted/inserted await this.trash?.updateOne( { _id } as FilterQuery<RocketChatRecordDeleted<T>>, { $set: trash }, { upsert: true, }, ); } return this.col.deleteMany({ _id: { $in: ids } } as unknown as FilterQuery<T>, options); } // Trash trashFind<P extends RocketChatRecordDeleted<T>>( query: FilterQuery<RocketChatRecordDeleted<T>>, options: FindOneOptions<P extends RocketChatRecordDeleted<T> ? RocketChatRecordDeleted<T> : P>, ): Cursor<RocketChatRecordDeleted<P>> | undefined { if (!this.trash) { return undefined; } const { trash } = this; return trash.find( { __collection__: this.name, ...query, }, options, ); } trashFindOneById(_id: string): Promise<RocketChatRecordDeleted<T> | null>; trashFindOneById( _id: string, options: WithoutProjection<RocketChatRecordDeleted<T>>, ): Promise<RocketChatRecordDeleted<RocketChatRecordDeleted<T>> | null>; trashFindOneById<P>( _id: string, options: FindOneOptions<P extends RocketChatRecordDeleted<T> ? RocketChatRecordDeleted<T> : P>, ): Promise<P | null>; async trashFindOneById<P extends RocketChatRecordDeleted<T>>( _id: string, options?: | undefined | WithoutProjection<RocketChatRecordDeleted<T>> | FindOneOptions<P extends RocketChatRecordDeleted<T> ? RocketChatRecordDeleted<T> : P>, ): Promise<RocketChatRecordDeleted<P> | null> { const query = { _id, __collection__: this.name, } as FilterQuery<RocketChatRecordDeleted<T>>; if (!this.trash) { return null; } const { trash } = this; return trash.findOne(query, options); } private setUpdatedAt(record: UpdateQuery<T> | InsertionModel<T>): void { if (this.preventSetUpdatedAt) { return; } setUpdatedAt(record); } trashFindDeletedAfter(deletedAt: Date): Cursor<RocketChatRecordDeleted<T>>; trashFindDeletedAfter( deletedAt: Date, query: FilterQuery<RocketChatRecordDeleted<T>>, options: WithoutProjection<RocketChatRecordDeleted<T>>, ): Cursor<RocketChatRecordDeleted<T>>; trashFindDeletedAfter<P = RocketChatRecordDeleted<T>>( deletedAt: Date, query: FilterQuery<P>, options: FindOneOptions<P extends RocketChatRecordDeleted<T> ? RocketChatRecordDeleted<T> : P>, ): Cursor<RocketChatRecordDeleted<P>>; trashFindDeletedAfter<P = RocketChatRecordDeleted<T>>( deletedAt: Date, query?: FilterQuery<RocketChatRecordDeleted<T>>, options?: | WithoutProjection<RocketChatRecordDeleted<T>> | FindOneOptions<P extends RocketChatRecordDeleted<T> ? RocketChatRecordDeleted<T> : P>, ): Cursor<RocketChatRecordDeleted<T>> { const q = { __collection__: this.name, _deletedAt: { $gt: deletedAt, }, ...query, } as FilterQuery<RocketChatRecordDeleted<T>>; const { trash } = this; if (!trash) { throw new Error('Trash is not enabled for this collection'); } return trash.find(q, options as any); } }
the_stack
import { pick } from "lodash"; import { graphql } from "react-relay"; import { ConnectionHandler, Environment, RecordProxy, RecordSourceSelectorProxy, } from "relay-runtime"; import { getViewer, roleIsAtLeast } from "coral-framework/helpers"; import { CoralContext } from "coral-framework/lib/bootstrap"; import { commitMutationPromiseNormalized, createMutation, LOCAL_ID, lookup, MutationInput, } from "coral-framework/lib/relay"; import { GQLCOMMENT_SORT, GQLSTORY_MODE, GQLTAG, GQLUSER_ROLE, } from "coral-framework/schema"; import { CreateCommentEvent } from "coral-stream/events"; import { CreateCommentMutation as MutationTypes } from "coral-stream/__generated__/CreateCommentMutation.graphql"; import { CreateCommentMutation_story } from "coral-stream/__generated__/CreateCommentMutation_story.graphql"; import { CreateCommentMutation_viewer } from "coral-stream/__generated__/CreateCommentMutation_viewer.graphql"; import { COMMENT_SORT } from "coral-stream/__generated__/StreamContainerLocal.graphql"; import { incrementStoryCommentCounts, isPublished, lookupFlattenReplies, prependCommentEdgeToProfile, } from "../../helpers"; export type CreateCommentInput = Omit< MutationInput<MutationTypes>, "flattenReplies" > & { commentsOrderBy?: COMMENT_SORT; }; function sharedUpdater( environment: Environment, store: RecordSourceSelectorProxy, input: CreateCommentInput, uuidGenerator: CoralContext["uuidGenerator"] ) { const commentEdge = store .getRootField("createComment")! .getLinkedRecord("edge")!; const node = commentEdge.getLinkedRecord("node")!; const status = node.getValue("status"); node.setValue("CREATE", "lastViewerAction"); // If comment is not visible, we don't need to add it. if (!isPublished(status)) { return; } prependCommentEdgeToProfile(environment, store, commentEdge); addCommentToStory(store, input, commentEdge); incrementStoryCommentCounts(store, input.storyID, commentEdge); } /** * update integrates new comment into the CommentConnection. */ function addCommentToStory( store: RecordSourceSelectorProxy, input: CreateCommentInput, commentEdge: RecordProxy ) { const local = store.get(LOCAL_ID)!; const story = store.get(input.storyID)!; const commentsTab = store.get(LOCAL_ID)!.getValue("commentsTab")!; if (!input.rating && commentsTab === "REVIEWS") { // Frontend automatically switches to Questions tab. // Nothing to be done here. return; } let connectionKey = "Stream_comments"; if (commentsTab === "UNANSWERED_COMMENTS") { connectionKey = "UnansweredStream_comments"; } let tag: GQLTAG | undefined; let rating: number | undefined; switch (commentsTab) { case "UNANSWERED_COMMENTS": tag = GQLTAG.UNANSWERED; break; case "REVIEWS": tag = GQLTAG.REVIEW; rating = local.getValue("ratingFilter") as number; break; case "QUESTIONS": tag = GQLTAG.QUESTION; rating = local.getValue("ratingFilter") as number; break; default: } if (input.commentsOrderBy === GQLCOMMENT_SORT.CREATED_AT_ASC) { const con = ConnectionHandler.getConnection(story, connectionKey, { orderBy: GQLCOMMENT_SORT.CREATED_AT_ASC, tag, rating, }); if (con) { ConnectionHandler.insertEdgeAfter(con, commentEdge); } } else { const con = ConnectionHandler.getConnection(story, connectionKey, { orderBy: GQLCOMMENT_SORT.CREATED_AT_DESC, tag, rating, }); if (con) { ConnectionHandler.insertEdgeBefore(con, commentEdge); } } } /** These are needed to be included when querying for the stream. */ // eslint-disable-next-line no-unused-expressions graphql` fragment CreateCommentMutation_viewer on User { id avatar badges bio createdAt role username status { current ban { active } } } `; // eslint-disable-next-line no-unused-expressions graphql` fragment CreateCommentMutation_story on Story { id url viewerRating { id tags { code } rating } settings { moderation mode live { enabled } experts { id } } ratings { count average } } `; /** end */ const mutation = graphql` mutation CreateCommentMutation( $input: CreateCommentInput! $flattenReplies: Boolean! ) { createComment(input: $input) { edge { cursor node { id status tags { code } ...AllCommentsTabCommentContainer_comment story { id ratings { count average } ...CreateCommentMutation_story @relay(mask: false) } } } clientMutationId } } `; let clientMutationId = 0; export const CreateCommentMutation = createMutation( "createComment", async ( environment: Environment, input: CreateCommentInput, { uuidGenerator, relayEnvironment, eventEmitter }: CoralContext ) => { const viewer = getViewer<CreateCommentMutation_viewer>(environment)!; const currentDate = new Date().toISOString(); const id = uuidGenerator(); const story = lookup<CreateCommentMutation_story>( relayEnvironment, input.storyID )!; const storySettings = story.settings; if (!storySettings || !storySettings.moderation) { throw new Error("Moderation mode of the story was not included"); } // TODO: Generate and use schema types. const expectPremoderation = !roleIsAtLeast(viewer.role, GQLUSER_ROLE.STAFF) && storySettings.moderation === "PRE"; const createCommentEvent = CreateCommentEvent.begin(eventEmitter, { body: input.body, storyID: input.storyID, }); // Determine tags. const tags = new Array<{ code: GQLTAG }>(); if (input.rating) { if (input.body.length > 0 || input.media) { tags.push({ code: GQLTAG.REVIEW }); } } else if (storySettings.mode === GQLSTORY_MODE.RATINGS_AND_REVIEWS) { tags.push({ code: GQLTAG.QUESTION }); } else if (storySettings.mode === GQLSTORY_MODE.QA) { const experts = storySettings.experts; // if there are no experts or the author is not an expert, the question is unanswered if (!experts || experts.every((exp) => exp.id !== viewer.id)) { tags.push({ code: GQLTAG.UNANSWERED }); } } switch (viewer.role) { case GQLUSER_ROLE.ADMIN: tags.push({ code: GQLTAG.ADMIN }); break; case GQLUSER_ROLE.MODERATOR: tags.push({ code: GQLTAG.MODERATOR }); break; case GQLUSER_ROLE.STAFF: tags.push({ code: GQLTAG.STAFF }); break; default: break; } try { const result = await commitMutationPromiseNormalized<MutationTypes>( environment, { mutation, variables: { input: { storyID: input.storyID, body: input.body || "", nudge: input.nudge, media: input.media, rating: input.rating, clientMutationId: clientMutationId.toString(), }, flattenReplies: lookupFlattenReplies(environment), }, optimisticResponse: { createComment: { edge: { cursor: currentDate, node: { id, enteredLive: false, createdAt: currentDate, status: "NONE", pending: false, lastViewerAction: "CREATE", hasTraversalFocus: false, author: { id: viewer.id, username: viewer.username || null, bio: viewer.bio, createdAt: viewer.createdAt, badges: viewer.badges, avatar: viewer.avatar, ignoreable: false, }, site: { id: uuidGenerator(), }, revision: { id: uuidGenerator(), media: null, }, rating: input.rating, parent: null, body: input.body || "", editing: { editableUntil: new Date(Date.now() + 10000).toISOString(), edited: false, }, actionCounts: { reaction: { total: 0, }, }, tags, viewerActionPresence: { reaction: false, dontAgree: false, flag: false, }, replies: { edges: [], viewNewEdges: [], pageInfo: { endCursor: null, hasNextPage: false }, }, story: { id: input.storyID, url: story.url, settings: { moderation: storySettings.moderation, mode: storySettings.mode, live: { enabled: storySettings.live.enabled, }, experts: storySettings.experts.map((e) => pick(e, ["id"]) ), }, viewerRating: tags.some( ({ code }) => code === GQLTAG.REVIEW ) ? { id, tags, rating: input.rating!, } : story.viewerRating ? { id: story.viewerRating.id, tags: story.viewerRating.tags.map(({ code }) => ({ code, })), rating: story.viewerRating.rating, } : null, ratings: story.ratings ? { count: story.ratings.count, average: story.ratings.average, } : null, }, deleted: false, }, }, clientMutationId: (clientMutationId++).toString(), }, // TODO: (kiwi/wyattjoh) fix types! } as any, optimisticUpdater: (store) => { // Skip optimistic update if comment is probably premoderated. if (expectPremoderation) { return; } sharedUpdater(environment, store, input, uuidGenerator); store.get(id)!.setValue(true, "pending"); }, updater: (store) => { sharedUpdater(environment, store, input, uuidGenerator); }, } ); createCommentEvent.success({ id: result.edge.node.id, status: result.edge.node.status, }); return result; } catch (error) { createCommentEvent.error({ message: error.message, code: error.code }); throw error; } } );
the_stack
import { argumentGenerator, GQL, SubscriptionBenchConfig, yamlConfigToSocketManagerParams, COLORS, } from './utils' import Knex = require('knex') import { Model } from 'objection' import Reattempt from 'reattempt/dist/decorator' import WebSocket from 'ws' import WebSocketAsPromised from 'websocket-as-promised' import { Events } from './schema' import { observable, observe } from '@nx-js/observer-util' import logUpdate from 'log-update' const DEBUG = process.env.DEBUG /** * ================= * Program Contents * ================= * - SocketManager: * Holds config for the benchmark parameters and controls spawning/orchestrating Socket connections. * Also performs DB insert at the end. * * - Connection: * An individual Websocket, maintains an internal record of received events. * Message handlers are registered here, these push to events. * * - main(): * Reads from config file, instantiates a SocketManager based on params in file. * Spawns more sockets at configured number per second until target reached. * Listens for ctrl + c to kill, which invokes exit() * * - exit(): * Teardown handler. Awaits closing all socket connections, writing data to DB, and destroying DB connection. */ /** * Global Stat Observables */ const STATS_OBSERVABLE = observable({ DATA_EVENT_COUNT: 0, ERROR_EVENT_COUNT: 0, CONNECTED_SOCKETS: new Set(), }) function updateEventStatsStdout() { logUpdate( COLORS.FG_CYAN + `Socket count: ${STATS_OBSERVABLE.CONNECTED_SOCKETS.size} | ` + COLORS.RESET + COLORS.FG_GREEN + `Data Events Received: ${STATS_OBSERVABLE.DATA_EVENT_COUNT} | ` + COLORS.RESET + COLORS.FG_RED + `Error Events Received: ${STATS_OBSERVABLE.ERROR_EVENT_COUNT} ` + COLORS.RESET ) } /** * ===================== * SOCKET MANAGER CLASS * ===================== */ export interface SockerManagerConfig { label: string endpoint: string variables: object headers?: Record<string, string> maxConnections: number insertPayloadData: boolean connectionsPerSecond: number pgConnectionString: string subscriptionString: string } export class SocketManager { private nextSocketId = 1 public connections: { [id: number]: Connection } = {} public config: SockerManagerConfig public queryArgGenerator: Iterator<any> constructor(config: SockerManagerConfig) { this.config = config this.queryArgGenerator = argumentGenerator(config.variables) } public closeSockets() { return Promise.all( Object.values(this.connections).map((conn) => { conn.socket.sendPacked({ type: GQL.CONNECTION_TERMINATE }) conn.socket.close() }) ) } public get allEvents() { return Object.values(this.connections).flatMap((conn) => conn.events) } public async insertEvents() { return Events.query() .allowInsert('[connection_id, event_number, event_data, event_time]') .insertGraph(this.allEvents) } public async spawnConnection() { const socketId = this.nextSocketId++ const socketManagerConfig = this.config const queryVariables = this.queryArgGenerator.next().value try { const connection = new Connection({ id: socketId, queryVariables, socketManagerConfig, }) connection.startSubscription() this.connections[socketId] = connection return connection } catch (err) { console.log('Caught error when calling spawnConnection(), exiting', err) process.exit(1) } } } /** * ======================= * SOCKET CONNECTION CLASS * ======================= */ export type FormatedError = Error & { originalError?: any } interface ConnectionParams { id: number socketManagerConfig: SockerManagerConfig queryVariables: object } class Connection { public eventNumber = 1 public events: Array<any> = [] public socket: WebSocketAsPromised public isReconnecting: boolean = false constructor(public props: ConnectionParams) { this.socket = this.makeSocket() this.configureMessageHandlers() } private makeSocket() { const { endpoint, headers } = this.props.socketManagerConfig return new WebSocketAsPromised(endpoint, { createWebSocket: (url) => new WebSocket(url, 'graphql-ws', { headers }), extractMessageData: (event) => event, packMessage: (data) => JSON.stringify(data), unpackMessage: (data) => JSON.parse(data as string), } as any) } // TODO: Make the retry configurable through config.yaml @Reattempt({ times: 60, delay: 1000 }) public async startSubscription() { const socket = this.socket const { id, queryVariables } = this.props const { headers, subscriptionString } = this.props.socketManagerConfig if (DEBUG) console.log('Socket ID', id, 'attempting to start subscription') await socket.open() socket.sendPacked({ type: GQL.CONNECTION_INIT, payload: { headers }, }) socket.sendPacked({ id: String(id), type: GQL.START, payload: { query: subscriptionString, variables: queryVariables, }, }) } private makeEventRow({ payload, err }) { const { label, insertPayloadData } = this.props.socketManagerConfig return { label, is_error: err, operation_id: 1, connection_id: this.props.id, event_number: this.eventNumber++, event_data: insertPayloadData ? payload : { data: null }, event_time: new Date().toISOString(), } } private configureMessageHandlers() { // On socket close: this.socket.onClose.addListener(() => { // Print debug message if enabled if (DEBUG) console.log('Socket ID', this.props.id, 'closed') // Remove socket ID from Observable ES6 Set of connected sockets STATS_OBSERVABLE.CONNECTED_SOCKETS.delete(this.props.id) // If the socket is not currently trying to reconnect, begin trying if (!this.isReconnecting) this.startSubscription() // Set reconnecting state to true this.isReconnecting = true }) // On socket open: this.socket.onOpen.addListener(() => { // Print debug message if enabled if (DEBUG) console.log('Socket ID', this.props.id, 'connected') // Add the socket ID to ES6 Set of connected sockets STATS_OBSERVABLE.CONNECTED_SOCKETS.add(this.props.id) // Set reconnecting state to false this.isReconnecting = false }) // If debug mode enabled, also set up generalized data logger if (DEBUG) { this.socket.onSend.addListener((data) => console.log('sent', data)) } this.socket.onUnpackedMessage.addListener((data) => { switch (data.type) { case GQL.DATA: const event = this.makeEventRow({ payload: data.payload, err: false }) if (DEBUG) console.log('CALLED GQL.DATA CASE, GOT EVENT ROW', event) STATS_OBSERVABLE.DATA_EVENT_COUNT++ this.events.push(event) break case GQL.ERROR: const error = this.makeEventRow({ payload: data.payload, err: true }) if (DEBUG) console.log('CALLED GQL.ERROR CASE, GOT ERROR ROW', data) STATS_OBSERVABLE.ERROR_EVENT_COUNT++ this.events.push(error) break } }) } } /** * ===================== * UTILS & MISC * ===================== */ /** * Connection Object. Actual connection creation happens in the main method. */ let knexConnection: Knex ; async function assertDatabaseConnection() { return knexConnection.raw('select 1+1 as result').catch((err: any) => { console.log('Failed to establish connection to database! Exiting...') console.log(err) process.exit(1) }) } function prettyPrintConfig(options) { console.table({ url: options.url, db_connection_string: options.db_connection_string, }) console.table({ headers: options.headers }) console.table({ config: options.config }, [ 'label', 'max_connections', 'connections_per_second', ]) console.table({ variables: options.config.variables }) } /** * ===================== * MAIN PROGRAM CODE * ===================== */ export async function main(opts: SubscriptionBenchConfig) { if (!opts) { throw new Error("Subscription options invalid"); } if (!opts.db_connection_string) { throw new Error("DB Connection String not found"); } // Open the DB connection using connection string from config file let dbConfig = { client: 'pg', connection: opts.db_connection_string, migrations: { directory: './src/migrations', }, } as Knex.Config; knexConnection = Knex(dbConfig); Model.knex(knexConnection); const options: SubscriptionBenchConfig = opts; /** * Any time values change in these stats, run the below function * currently just updates the terminal output text with new data * * NOTE: This only works because updateEventStatsStdout() references * variables from the observable function, so the Proxy knows to fire */ observe(() => { updateEventStatsStdout() }) /** * Logging */ const database = process.env.PG_CONNECTION_STRING || options.db_connection_string console.log('Asserting database connectivity, trying to conect to:') console.log(COLORS.FG_CYAN, database, COLORS.RESET) await assertDatabaseConnection() prettyPrintConfig(options) console.log( 'Connected, starting subscriptions benchmark for a total of', options.config.max_connections, 'sockets at a connection rate of', options.config.connections_per_second, 'sockets per second' ) /** * Execution */ const socketManagerParams = yamlConfigToSocketManagerParams(options) const socketManager = new SocketManager(socketManagerParams) const MAX_CONNECTIONS = options.config.max_connections const SPAWN_RATE = 1000 / options.config.connections_per_second let socketSpawned = 0 const spawnFn = () => { socketSpawned++ return socketManager.spawnConnection().then((socket) => { if (socketSpawned >= MAX_CONNECTIONS) clearInterval(spawnInterval) }) } const spawnInterval = setInterval(spawnFn, SPAWN_RATE) process.on('SIGINT', () => exit(socketManager)) } /** * ===================== * EXIT TEARDOWN PROCESS * ===================== */ async function exit(socketManager: SocketManager) { console.log('\nExecuting Teardown Process') try { console.log('Starting to close socket connections') await socketManager.closeSockets() } catch (error) { console.log('Error while closing socket connections:', error) } try { console.log('Sockets closed, attempting to insert event data') const events = await socketManager.insertEvents() console.log( `Inserted total of ${events.length} events for label ${socketManager.config.label}` ) } catch (error) { console.log('Error while inserting events:', error) } try { console.log('Trying to close DB connection pool') await knexConnection.destroy() console.log('Database connection destroyed') } catch (error) { console.log('Error while destroying database connection:', error) } console.log('Now exiting the process') process.exit(0) }
the_stack
import { Component, OnDestroy, OnInit, QueryList, ViewChildren } from '@angular/core'; import dayjs from 'dayjs'; import { HttpErrorResponse, HttpResponse } from '@angular/common/http'; import { Subscription } from 'rxjs'; import { ActivatedRoute } from '@angular/router'; import { AlertService } from 'app/core/util/alert.service'; import { ParticipationService } from 'app/exercises/shared/participation/participation.service'; import { ParticipationWebsocketService } from 'app/overview/participation-websocket.service'; import { Result } from 'app/entities/result.model'; import { MultipleChoiceQuestionComponent } from 'app/exercises/quiz/shared/questions/multiple-choice-question/multiple-choice-question.component'; import { DragAndDropQuestionComponent } from 'app/exercises/quiz/shared/questions/drag-and-drop-question/drag-and-drop-question.component'; import { ShortAnswerQuestionComponent } from 'app/exercises/quiz/shared/questions/short-answer-question/short-answer-question.component'; import { TranslateService } from '@ngx-translate/core'; import * as smoothscroll from 'smoothscroll-polyfill'; import { StudentParticipation } from 'app/entities/participation/student-participation.model'; import { DeviceDetectorService } from 'ngx-device-detector'; import { ButtonSize, ButtonType } from 'app/shared/components/button.component'; import { JhiWebsocketService } from 'app/core/websocket/websocket.service'; import { ShortAnswerSubmittedAnswer } from 'app/entities/quiz/short-answer-submitted-answer.model'; import { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service'; import { DragAndDropMapping } from 'app/entities/quiz/drag-and-drop-mapping.model'; import { AnswerOption } from 'app/entities/quiz/answer-option.model'; import { ShortAnswerSubmittedText } from 'app/entities/quiz/short-answer-submitted-text.model'; import { QuizParticipationService } from 'app/exercises/quiz/participate/quiz-participation.service'; import { MultipleChoiceQuestion } from 'app/entities/quiz/multiple-choice-question.model'; import { QuizExercise } from 'app/entities/quiz/quiz-exercise.model'; import { DragAndDropSubmittedAnswer } from 'app/entities/quiz/drag-and-drop-submitted-answer.model'; import { QuizSubmission } from 'app/entities/quiz/quiz-submission.model'; import { ShortAnswerQuestion } from 'app/entities/quiz/short-answer-question.model'; import { QuizQuestionType } from 'app/entities/quiz/quiz-question.model'; import { MultipleChoiceSubmittedAnswer } from 'app/entities/quiz/multiple-choice-submitted-answer.model'; import { DragAndDropQuestion } from 'app/entities/quiz/drag-and-drop-question.model'; import { ArtemisQuizService } from 'app/shared/quiz/quiz.service'; import { roundScoreSpecifiedByCourseSettings } from 'app/shared/util/utils'; import { onError } from 'app/shared/util/global.utils'; import { UI_RELOAD_TIME } from 'app/shared/constants/exercise-exam-constants'; import { debounce } from 'lodash-es'; import { captureException } from '@sentry/browser'; import { getCourseFromExercise } from 'app/entities/exercise.model'; @Component({ selector: 'jhi-quiz', templateUrl: './quiz-participation.component.html', providers: [ParticipationService], styleUrls: ['./quiz-participation.component.scss'], }) export class QuizParticipationComponent implements OnInit, OnDestroy { // make constants available to html for comparison readonly DRAG_AND_DROP = QuizQuestionType.DRAG_AND_DROP; readonly MULTIPLE_CHOICE = QuizQuestionType.MULTIPLE_CHOICE; readonly SHORT_ANSWER = QuizQuestionType.SHORT_ANSWER; readonly ButtonSize = ButtonSize; readonly ButtonType = ButtonType; readonly roundScoreSpecifiedByCourseSettings = roundScoreSpecifiedByCourseSettings; readonly getCourseFromExercise = getCourseFromExercise; @ViewChildren(MultipleChoiceQuestionComponent) mcQuestionComponents: QueryList<MultipleChoiceQuestionComponent>; @ViewChildren(DragAndDropQuestionComponent) dndQuestionComponents: QueryList<DragAndDropQuestionComponent>; @ViewChildren(ShortAnswerQuestionComponent) shortAnswerQuestionComponents: QueryList<ShortAnswerQuestionComponent>; private subscription: Subscription; private subscriptionData: Subscription; // Difference between server and client time timeDifference = 0; runningTimeouts = new Array<any>(); // actually the function type setTimeout(): (handler: any, timeout?: any, ...args: any[]): number isSubmitting = false; // isSaving = false; lastSavedTimeText = ''; justSaved = false; waitingForQuizStart = false; refreshingQuiz = false; remainingTimeText = '?'; remainingTimeSeconds = 0; timeUntilStart = '0'; disconnected = false; unsavedChanges = false; sendWebsocket: (submission: QuizSubmission) => void; showingResult = false; userScore: number; mode: string; submission = new QuizSubmission(); quizExercise: QuizExercise; totalScore: number; selectedAnswerOptions = new Map<number, AnswerOption[]>(); dragAndDropMappings = new Map<number, DragAndDropMapping[]>(); shortAnswerSubmittedTexts = new Map<number, ShortAnswerSubmittedText[]>(); result: Result; questionScores = {}; quizId: number; courseId: number; interval: any; quizStarted = false; /** * Websocket channels */ submissionChannel: string; participationChannel: string; quizExerciseChannel: string; onConnected: () => void; onDisconnected: () => void; /** * debounced function to reset 'justSubmitted', so that time since last submission is displayed again when no submission has been made for at least 2 seconds * @type {Function} */ timeoutJustSaved = debounce(() => { this.justSaved = false; }, 2000); constructor( private jhiWebsocketService: JhiWebsocketService, private quizExerciseService: QuizExerciseService, private participationService: ParticipationService, private participationWebsocketService: ParticipationWebsocketService, private route: ActivatedRoute, private alertService: AlertService, private quizParticipationService: QuizParticipationService, private translateService: TranslateService, private deviceService: DeviceDetectorService, private quizService: ArtemisQuizService, ) { smoothscroll.polyfill(); } ngOnInit() { // set correct mode this.subscriptionData = this.route.data.subscribe((data) => { this.mode = data.mode; this.subscription = this.route.params.subscribe((params) => { this.quizId = Number(params['exerciseId']); this.courseId = Number(params['courseId']); // init according to mode switch (this.mode) { case 'practice': this.initPracticeMode(); break; case 'preview': this.initPreview(); break; case 'solution': this.initShowSolution(); break; case 'live': this.initLiveMode(); break; } }); }); // update displayed times in UI regularly this.interval = setInterval(() => { this.updateDisplayedTimes(); }, UI_RELOAD_TIME); } ngOnDestroy() { clearInterval(this.interval); /** * unsubscribe from all subscribed websocket channels when page is closed */ this.runningTimeouts.forEach((timeout) => { clearTimeout(timeout); }); if (this.submissionChannel) { this.jhiWebsocketService.unsubscribe('/user' + this.submissionChannel); } if (this.participationChannel) { this.jhiWebsocketService.unsubscribe(this.participationChannel); } if (this.quizExerciseChannel) { this.jhiWebsocketService.unsubscribe(this.quizExerciseChannel); } if (this.onConnected) { this.jhiWebsocketService.unbind('connect', this.onConnected); } if (this.onDisconnected) { this.jhiWebsocketService.unbind('disconnect', this.onDisconnected); } if (this.subscription) { this.subscription.unsubscribe(); } if (this.subscriptionData) { this.subscriptionData.unsubscribe(); } } /** * loads latest submission from server and sets up socket connection */ initLiveMode() { // listen to connect / disconnect events this.onConnected = () => { if (this.disconnected) { // if the disconnect happened during the live quiz and there are unsaved changes, we trigger a selection changed event to save the submission on the server if (this.unsavedChanges && this.sendWebsocket) { this.onSelectionChanged(); } // if the quiz was not yet started, we might have missed the quiz start => refresh if (this.quizExercise && !this.quizExercise.started) { this.refreshQuiz(true); } else if (this.quizExercise && this.quizExercise.adjustedDueDate && this.quizExercise.adjustedDueDate.isBefore(dayjs())) { // if the quiz has ended, we might have missed to load the results => refresh this.refreshQuiz(true); } } this.disconnected = false; }; this.jhiWebsocketService.bind('connect', () => { this.onConnected(); }); this.onDisconnected = () => { this.disconnected = true; }; this.jhiWebsocketService.bind('disconnect', () => { this.onDisconnected(); }); this.subscribeToWebsocketChannels(); // load the quiz (and existing submission if quiz has started) this.participationService.findParticipation(this.quizId).subscribe( (response: HttpResponse<StudentParticipation>) => { this.updateParticipationFromServer(response.body!); }, (error: HttpErrorResponse) => onError(this.alertService, error), ); } /** * loads quizExercise and starts practice mode */ initPracticeMode() { this.quizExerciseService.findForStudent(this.quizId).subscribe( (res: HttpResponse<QuizExercise>) => { if (res.body && res.body.isOpenForPractice) { this.startQuizPreviewOrPractice(res.body); } else { alert('Error: This quiz is not open for practice!'); } }, (error: HttpErrorResponse) => onError(this.alertService, error), ); } /** * loads quiz exercise and starts preview mode */ initPreview() { this.quizExerciseService.find(this.quizId).subscribe( (res: HttpResponse<QuizExercise>) => { this.startQuizPreviewOrPractice(res.body!); }, (error: HttpErrorResponse) => onError(this.alertService, error), ); } initShowSolution() { this.quizExerciseService.find(this.quizId).subscribe( (res: HttpResponse<QuizExercise>) => { this.quizExercise = res.body!; this.initQuiz(); this.showingResult = true; }, (error: HttpErrorResponse) => onError(this.alertService, error), ); } /** * Start the given quiz in practice or preview mode * * @param quizExercise {object} the quizExercise to start */ startQuizPreviewOrPractice(quizExercise: QuizExercise) { // init quiz this.quizExercise = quizExercise; this.initQuiz(); // randomize order this.quizService.randomizeOrder(this.quizExercise); // init empty submission this.submission = new QuizSubmission(); // adjust end date this.quizExercise.adjustedDueDate = dayjs().add(this.quizExercise.duration!, 'seconds'); // auto submit when time is up this.runningTimeouts.push( setTimeout(() => { this.onSubmit(); }, quizExercise.duration! * 1000), ); } /** * subscribe to any outstanding websocket channels */ subscribeToWebsocketChannels() { if (!this.submissionChannel) { this.submissionChannel = '/topic/quizExercise/' + this.quizId + '/submission'; // submission channel => react to new submissions this.jhiWebsocketService.subscribe('/user' + this.submissionChannel); this.jhiWebsocketService.receive('/user' + this.submissionChannel).subscribe( (payload) => { if (payload.error) { this.onSaveError(payload.error); } }, (error) => { this.onSaveError(error); }, ); // save answers (submissions) through websocket this.sendWebsocket = (submission: QuizSubmission) => { this.jhiWebsocketService.send(this.submissionChannel, submission); }; } if (!this.participationChannel) { this.participationChannel = '/user/topic/exercise/' + this.quizId + '/participation'; // TODO: subscribe for new results instead if this is what we are actually interested in // participation channel => react to new results this.jhiWebsocketService.subscribe(this.participationChannel); this.jhiWebsocketService.receive(this.participationChannel).subscribe((changedParticipation: StudentParticipation) => { if (changedParticipation && this.quizExercise && changedParticipation.exercise!.id === this.quizExercise.id) { if (this.waitingForQuizStart) { // only apply completely if quiz hasn't started to prevent jumping ui during participation this.updateParticipationFromServer(changedParticipation); } else { // update quizExercise and results / submission this.showQuizResultAfterQuizEnd(changedParticipation); } } }); } if (!this.quizExerciseChannel) { this.quizExerciseChannel = '/topic/courses/' + this.courseId + '/quizExercises'; // quizExercise channel => react to changes made to quizExercise (e.g. start date) this.jhiWebsocketService.subscribe(this.quizExerciseChannel); this.jhiWebsocketService.receive(this.quizExerciseChannel).subscribe( (quiz) => { if (this.waitingForQuizStart && this.quizId === quiz.id) { this.applyQuizFull(quiz); } }, () => {}, ); } } /** * updates all displayed (relative) times in the UI */ updateDisplayedTimes() { const translationBasePath = 'showStatistic.'; // update remaining time if (this.quizExercise && this.quizExercise.adjustedDueDate) { const endDate = this.quizExercise.adjustedDueDate; if (endDate.isAfter(dayjs())) { // quiz is still running => calculate remaining seconds and generate text based on that this.remainingTimeSeconds = endDate.diff(dayjs(), 'seconds'); this.remainingTimeText = this.relativeTimeText(this.remainingTimeSeconds); } else { // quiz is over => set remaining seconds to negative, to deactivate 'Submit' button this.remainingTimeSeconds = -1; this.remainingTimeText = this.translateService.instant(translationBasePath + 'quizhasEnded'); } } else { // remaining time is unknown => Set remaining seconds to 0, to keep 'Submit' button enabled this.remainingTimeSeconds = 0; this.remainingTimeText = '?'; } // update submission time if (this.submission && this.submission.adjustedSubmissionDate) { // exact value is not important => use default relative time from dayjs for better readability and less distraction this.lastSavedTimeText = dayjs(this.submission.adjustedSubmissionDate).fromNow(); } // update time until start if (this.quizExercise && this.quizExercise.adjustedReleaseDate) { if (this.quizExercise.adjustedReleaseDate.isAfter(dayjs())) { this.timeUntilStart = this.relativeTimeText(this.quizExercise.adjustedReleaseDate.diff(dayjs(), 'seconds')); } else { this.timeUntilStart = this.translateService.instant(translationBasePath + 'now'); // Check if websocket has updated the quiz exercise and check that following block is only executed once if (!this.quizExercise.started && !this.quizStarted) { this.quizStarted = true; // Refresh quiz after 5 seconds when client did not receive websocket message to start the quiz setTimeout(() => { // Check again if websocket has updated the quiz exercise within the 5 seconds if (!this.quizExercise.started) { this.refreshQuiz(true); } }, 5000); } } } else { this.timeUntilStart = ''; } } /** * Express the given timespan as humanized text * * @param remainingTimeSeconds {number} the amount of seconds to display * @return {string} humanized text for the given amount of seconds */ relativeTimeText(remainingTimeSeconds: number) { if (remainingTimeSeconds > 210) { return Math.ceil(remainingTimeSeconds / 60) + ' min'; } else if (remainingTimeSeconds > 59) { return Math.floor(remainingTimeSeconds / 60) + ' min ' + (remainingTimeSeconds % 60) + ' s'; } else { return remainingTimeSeconds + ' s'; } } /** * Initialize the selections / mappings for each question with an empty array */ initQuiz() { // calculate score this.totalScore = this.quizExercise.quizQuestions ? this.quizExercise.quizQuestions.reduce((score, question) => { return score + question.points!; }, 0) : 0; // prepare selection arrays for each question this.selectedAnswerOptions = new Map<number, AnswerOption[]>(); this.dragAndDropMappings = new Map<number, DragAndDropMapping[]>(); this.shortAnswerSubmittedTexts = new Map<number, ShortAnswerSubmittedText[]>(); if (this.quizExercise.quizQuestions) { this.quizExercise.quizQuestions.forEach((question) => { if (question.type === QuizQuestionType.MULTIPLE_CHOICE) { // add the array of selected options to the dictionary (add an empty array, if there is no submittedAnswer for this question) this.selectedAnswerOptions.set(question.id!, []); } else if (question.type === QuizQuestionType.DRAG_AND_DROP) { // add the array of mappings to the dictionary (add an empty array, if there is no submittedAnswer for this question) this.dragAndDropMappings.set(question.id!, []); } else if (question.type === QuizQuestionType.SHORT_ANSWER) { // add the array of submitted texts to the dictionary (add an empty array, if there is no submittedAnswer for this question) this.shortAnswerSubmittedTexts.set(question.id!, []); } else { console.error('Unknown question type: ' + question); } }, this); } } /** * applies the data from the model to the UI (reverse of applySelection): * * Sets the checkmarks (selected answers) for all questions according to the submission data * this needs to be done when we get new submission data, e.g. through the websocket connection */ applySubmission() { // create dictionaries (key: questionID, value: Array of selected answerOptions / mappings) // for the submittedAnswers to hand the selected options / mappings in individual arrays to the question components this.selectedAnswerOptions = new Map<number, AnswerOption[]>(); this.dragAndDropMappings = new Map<number, DragAndDropMapping[]>(); this.shortAnswerSubmittedTexts = new Map<number, ShortAnswerSubmittedText[]>(); if (this.quizExercise.quizQuestions) { // iterate through all questions of this quiz this.quizExercise.quizQuestions.forEach((question) => { // find the submitted answer that belongs to this question, only when submitted answers already exist const submittedAnswer = this.submission.submittedAnswers?.find((answer) => { return answer.quizQuestion!.id === question.id; }); if (question.type === QuizQuestionType.MULTIPLE_CHOICE) { // add the array of selected options to the dictionary (add an empty array, if there is no submittedAnswer for this question) this.selectedAnswerOptions.set(question.id!, (submittedAnswer as MultipleChoiceSubmittedAnswer)?.selectedOptions || []); } else if (question.type === QuizQuestionType.DRAG_AND_DROP) { // add the array of mappings to the dictionary (add an empty array, if there is no submittedAnswer for this question) this.dragAndDropMappings.set(question.id!, (submittedAnswer as DragAndDropSubmittedAnswer)?.mappings || []); } else if (question.type === QuizQuestionType.SHORT_ANSWER) { // add the array of submitted texts to the dictionary (add an empty array, if there is no submittedAnswer for this question) this.shortAnswerSubmittedTexts.set(question.id!, (submittedAnswer as ShortAnswerSubmittedAnswer)?.submittedTexts || []); } else { console.error('Unknown question type: ' + question); } }, this); } } /** * updates the model according to UI state (reverse of applySubmission): * Creates the submission from the user's selection * this needs to be done when we want to send the submission either for saving (through websocket) or for submitting (through REST call) */ applySelection() { // convert the selection dictionary (key: questionID, value: Array of selected answerOptions / mappings) // into an array of submittedAnswer objects and save it as the submittedAnswers of the submission this.submission.submittedAnswers = []; // for multiple-choice questions this.selectedAnswerOptions.forEach((answerOptions, questionId) => { // find the question object for the given question id const question = this.quizExercise.quizQuestions?.find((selectedQuestion) => { return selectedQuestion.id === questionId; }); if (!question) { console.error('question not found for ID: ' + questionId); return; } // generate the submittedAnswer object const mcSubmittedAnswer = new MultipleChoiceSubmittedAnswer(); mcSubmittedAnswer.quizQuestion = question; mcSubmittedAnswer.selectedOptions = answerOptions; this.submission.submittedAnswers!.push(mcSubmittedAnswer); }, this); // for drag-and-drop questions this.dragAndDropMappings.forEach((mappings, questionId) => { // find the question object for the given question id const question = this.quizExercise.quizQuestions?.find((localQuestion) => { return localQuestion.id === questionId; }); if (!question) { console.error('question not found for ID: ' + questionId); return; } // generate the submittedAnswer object const dndSubmittedAnswer = new DragAndDropSubmittedAnswer(); dndSubmittedAnswer.quizQuestion = question; dndSubmittedAnswer.mappings = mappings; this.submission.submittedAnswers!.push(dndSubmittedAnswer); }, this); // for short-answer questions this.shortAnswerSubmittedTexts.forEach((submittedTexts, questionId) => { // find the question object for the given question id const question = this.quizExercise.quizQuestions?.find((localQuestion) => { return localQuestion.id === questionId; }); if (!question) { console.error('question not found for ID: ' + questionId); return; } // generate the submittedAnswer object const shortAnswerSubmittedAnswer = new ShortAnswerSubmittedAnswer(); shortAnswerSubmittedAnswer.quizQuestion = question; shortAnswerSubmittedAnswer.submittedTexts = submittedTexts; this.submission.submittedAnswers!.push(shortAnswerSubmittedAnswer); }, this); } /** * Apply the data of the participation, replacing all old data */ updateParticipationFromServer(participation: StudentParticipation) { if (participation) { this.applyQuizFull(participation.exercise as QuizExercise); } // apply submission if it exists if (participation?.results?.length) { this.submission = participation.results[0].submission as QuizSubmission; // update submission time this.updateSubmissionTime(); // show submission answers in UI this.applySubmission(); if (participation.results[0].resultString && this.quizExercise.ended) { // quiz has ended and results are available this.showResult(participation.results[0]); } } else { this.submission = new QuizSubmission(); } } /** * apply the data of the quiz, replacing all old data and enabling reconnect if necessary * @param quizExercise */ applyQuizFull(quizExercise: QuizExercise) { this.quizExercise = quizExercise; this.initQuiz(); // check if quiz has started if (this.quizExercise.started) { // quiz has started this.waitingForQuizStart = false; // update timeDifference this.quizExercise.adjustedDueDate = dayjs().add(this.quizExercise.remainingTime!, 'seconds'); this.timeDifference = dayjs(this.quizExercise.dueDate!).diff(this.quizExercise.adjustedDueDate, 'seconds'); // check if quiz hasn't ended if (!this.quizExercise.ended) { // enable automatic websocket reconnect this.jhiWebsocketService.enableReconnect(); // apply randomized order where necessary this.quizService.randomizeOrder(this.quizExercise); } } else { // quiz hasn't started yet this.waitingForQuizStart = true; // enable automatic websocket reconnect this.jhiWebsocketService.enableReconnect(); if (this.quizExercise.isPlannedToStart) { // synchronize time with server this.quizExercise.releaseDate = dayjs(this.quizExercise.releaseDate!); this.quizExercise.adjustedReleaseDate = dayjs().add(this.quizExercise.timeUntilPlannedStart!, 'seconds'); } } } /* * This method only handles the update of the quiz after the quiz has ended */ showQuizResultAfterQuizEnd(participation: StudentParticipation) { const quizExercise = participation.exercise as QuizExercise; if (participation.results?.length && participation.results[0].resultString && quizExercise.ended) { // quiz has ended and results are available this.submission = participation.results[0].submission as QuizSubmission; // update submission time this.updateSubmissionTime(); this.transferInformationToQuizExercise(quizExercise); this.applySubmission(); this.showResult(participation.results[0]); } } /** * Transfer additional information (explanations, correct answers) from the given full quiz exercise to quizExercise. * This method is typically invoked after the quiz has ended and makes sure that the (random) order of the quiz * questions and answer options for the particular user is respected * * @param fullQuizExerciseFromServer {object} the quizExercise containing additional information */ transferInformationToQuizExercise(fullQuizExerciseFromServer: QuizExercise) { this.quizExercise.quizQuestions!.forEach((clientQuestion) => { // find updated question const fullQuestionFromServer = fullQuizExerciseFromServer.quizQuestions?.find((fullQuestion) => { return clientQuestion.id === fullQuestion.id; }); if (fullQuestionFromServer) { clientQuestion.explanation = fullQuestionFromServer.explanation; if (clientQuestion.type === QuizQuestionType.MULTIPLE_CHOICE) { const mcClientQuestion = clientQuestion as MultipleChoiceQuestion; const mcFullQuestionFromServer = fullQuestionFromServer as MultipleChoiceQuestion; const answerOptions = mcClientQuestion.answerOptions!; answerOptions.forEach((clientAnswerOption) => { // find updated answerOption const fullAnswerOptionFromServer = mcFullQuestionFromServer.answerOptions!.find((option) => { return clientAnswerOption.id === option.id; }); if (fullAnswerOptionFromServer) { clientAnswerOption.explanation = fullAnswerOptionFromServer.explanation; clientAnswerOption.isCorrect = fullAnswerOptionFromServer.isCorrect; } }); } else if (clientQuestion.type === QuizQuestionType.DRAG_AND_DROP) { const dndClientQuestion = clientQuestion as DragAndDropQuestion; const dndFullQuestionFromServer = fullQuestionFromServer as DragAndDropQuestion; dndClientQuestion.correctMappings = dndFullQuestionFromServer.correctMappings; } else if (clientQuestion.type === QuizQuestionType.SHORT_ANSWER) { const shortAnswerClientQuestion = clientQuestion as ShortAnswerQuestion; const shortAnswerFullQuestionFromServer = fullQuestionFromServer as ShortAnswerQuestion; shortAnswerClientQuestion.correctMappings = shortAnswerFullQuestionFromServer.correctMappings; } else { captureException(new Error('Unknown question type: ' + clientQuestion)); } } }, this); // make sure that a possible explanation is updated correctly in all sub components this.mcQuestionComponents.forEach((mcQuestionComponent) => { mcQuestionComponent.watchCollection(); }); this.dndQuestionComponents.forEach((dndQuestionComponent) => { dndQuestionComponent.watchCollection(); }); this.shortAnswerQuestionComponents.forEach((shortAnswerQuestionComponent) => { shortAnswerQuestionComponent.watchCollection(); }); } /** * Display results of the quiz for the user * @param result */ showResult(result: Result) { this.result = result; if (this.result) { this.showingResult = true; // at the moment, this is always enabled // disable automatic websocket reconnect // this.jhiWebsocketService.disableReconnect(); const course = this.quizExercise.course || this.quizExercise?.exerciseGroup?.exam?.course; // assign user score (limit decimal places to 2) this.userScore = this.submission.scoreInPoints ? roundScoreSpecifiedByCourseSettings(this.submission.scoreInPoints, course) : 0; // create dictionary with scores for each question this.questionScores = {}; this.submission.submittedAnswers!.forEach((submittedAnswer) => { // limit decimal places to 2 this.questionScores[submittedAnswer.quizQuestion!.id!] = roundScoreSpecifiedByCourseSettings(submittedAnswer.scoreInPoints!, course); }, this); } } /** * Callback method to be triggered when the user changes any of the answers in the quiz (in sub components based on the question type) */ onSelectionChanged() { this.applySelection(); if (this.sendWebsocket) { if (!this.disconnected) { // this.isSaving = true; this.submission.submissionDate = dayjs().add(this.timeDifference, 'seconds'); this.sendWebsocket(this.submission); this.unsavedChanges = false; this.updateSubmissionTime(); } else { this.unsavedChanges = true; } } } /** * update the value for adjustedSubmissionDate in submission */ updateSubmissionTime() { if (this.submission.submissionDate) { this.submission.adjustedSubmissionDate = dayjs(this.submission.submissionDate).subtract(this.timeDifference, 'seconds').toDate(); if (Math.abs(dayjs(this.submission.adjustedSubmissionDate).diff(dayjs(), 'seconds')) < 2) { this.justSaved = true; this.timeoutJustSaved(); } } } /** * Callback function for handling quiz submission after saving submission to server * @param error a potential error during save */ onSaveError(error: string) { if (error) { const errorMessage = 'Saving answers failed: ' + error; // TODO: this is a workaround to avoid translation not found issues. Provide proper translations const jhiAlert = this.alertService.error(errorMessage); jhiAlert.message = errorMessage; this.unsavedChanges = true; this.isSubmitting = false; } } /** * Checks if the student has interacted with each question of the quiz: * - for a Multiple Choice Questions it checks if an answer option was selected * - for a Drag and Drop Questions it checks if at least one mapping has been made * - for a Short Answer Questions it checks if at least one field has been clicked in * @return {boolean} true when student interacted with every question, false when not with every questions has an interaction */ areAllQuestionsAnswered(): boolean { if (!this.quizExercise.quizQuestions) { return true; } for (const question of this.quizExercise.quizQuestions) { if (question.type === QuizQuestionType.MULTIPLE_CHOICE) { const options = this.selectedAnswerOptions.get(question.id!); if (options && options.length === 0) { return false; } } else if (question.type === QuizQuestionType.DRAG_AND_DROP) { const mappings = this.dragAndDropMappings.get(question.id!); if (mappings && mappings.length === 0) { return false; } } else if (question.type === QuizQuestionType.SHORT_ANSWER) { const submittedTexts = this.shortAnswerSubmittedTexts.get(question.id!); if (submittedTexts && submittedTexts.length === 0) { return false; } } } return true; } /** * This function is called when the user clicks the 'Submit' button */ onSubmit() { const translationBasePath = 'artemisApp.quizExercise.'; this.applySelection(); let confirmSubmit = true; if (this.remainingTimeSeconds > 15 && !this.areAllQuestionsAnswered()) { const warningText = this.translateService.instant(translationBasePath + 'submissionWarning'); confirmSubmit = window.confirm(warningText); } if (confirmSubmit) { this.isSubmitting = true; switch (this.mode) { case 'practice': if (!this.submission.id) { this.quizParticipationService.submitForPractice(this.submission, this.quizId).subscribe( (response: HttpResponse<Result>) => { this.onSubmitPracticeOrPreviewSuccess(response.body!); }, (error: HttpErrorResponse) => this.onSubmitError(error), ); } break; case 'preview': if (!this.submission.id) { this.quizParticipationService.submitForPreview(this.submission, this.quizId).subscribe( (response: HttpResponse<Result>) => { this.onSubmitPracticeOrPreviewSuccess(response.body!); }, (error: HttpErrorResponse) => this.onSubmitError(error), ); } break; case 'live': // copy submission and send it through websocket with 'submitted = true' const quizSubmission = new QuizSubmission(); quizSubmission.submittedAnswers = this.submission.submittedAnswers; this.quizParticipationService.submitForLiveMode(quizSubmission, this.quizId).subscribe( (response: HttpResponse<QuizSubmission>) => { this.submission = response.body!; this.isSubmitting = false; this.updateSubmissionTime(); this.applySubmission(); }, (error: HttpErrorResponse) => this.onSubmitError(error), ); break; } } } /** * Callback function for handling response after submitting for practice or preview * @param result */ onSubmitPracticeOrPreviewSuccess(result: Result) { this.isSubmitting = false; this.submission = result.submission as QuizSubmission; // make sure the additional information (explanations, correct answers) is available const quizExercise = (result.participation! as StudentParticipation).exercise as QuizExercise; this.transferInformationToQuizExercise(quizExercise); this.applySubmission(); this.showResult(result); } /** * Callback function for handling error when submitting * @param error */ onSubmitError(error: HttpErrorResponse) { const errorMessage = 'Submitting the quiz was not possible. ' + error.headers?.get('X-artemisApp-message') || error.message; // TODO: this is a workaround to avoid translation not found issues. Provide proper translations const jhiAlert = this.alertService.error(errorMessage); jhiAlert.message = errorMessage; this.isSubmitting = false; } /** * By clicking on the bubble of the progress navigation towards the corresponding question of the quiz is triggered * @param questionIndex */ navigateToQuestion(questionIndex: number): void { document.getElementById('question' + questionIndex)!.scrollIntoView({ behavior: 'smooth', }); } /** * Determines if the current device is a mobile device */ isMobile(): boolean { return this.deviceService.isMobile(); } /** * Refresh quiz */ refreshQuiz(refresh = false) { this.refreshingQuiz = refresh; this.quizExerciseService.findForStudent(this.quizId).subscribe( (res: HttpResponse<QuizExercise>) => { const quizExercise = res.body!; if (quizExercise.started) { this.quizExercise = quizExercise; this.initLiveMode(); } setTimeout(() => (this.refreshingQuiz = false), 500); // ensure min animation duration }, () => { // error case setTimeout(() => (this.refreshingQuiz = false), 500); // ensure min animation duration }, ); } }
the_stack
import localVarRequest = require('request'); import http = require('http'); import fs = require('fs'); /* tslint:disable:no-unused-locals */ import { ChargeType } from '../model/projects/chargeType'; import { Project } from '../model/projects/project'; import { ProjectCreateOrUpdate } from '../model/projects/projectCreateOrUpdate'; import { ProjectPatch } from '../model/projects/projectPatch'; import { ProjectUsers } from '../model/projects/projectUsers'; import { Projects } from '../model/projects/projects'; import { Task } from '../model/projects/task'; import { Tasks } from '../model/projects/tasks'; import { TimeEntries } from '../model/projects/timeEntries'; import { TimeEntry } from '../model/projects/timeEntry'; import { TimeEntryCreateOrUpdate } from '../model/projects/timeEntryCreateOrUpdate'; import { ObjectSerializer, Authentication, VoidAuth } from '../model/projects/models'; import { OAuth } from '../model/projects/models'; let defaultBasePath = 'https://api.xero.com/projects.xro/2.0'; // =============================================== // This file is autogenerated - Please do not edit // =============================================== export enum ProjectApiApiKeys { } export class ProjectApi { protected _basePath = defaultBasePath; protected defaultHeaders : any = {'user-agent': 'xero-node-4.16.0'}; protected _useQuerystring : boolean = false; protected binaryHeaders : any = {}; protected authentications = { 'default': <Authentication>new VoidAuth(), 'OAuth2': new OAuth(), } constructor(basePath?: string); constructor(basePathOrUsername: string, password?: string, basePath?: string) { if (password) { if (basePath) { this.basePath = basePath; } } else { if (basePathOrUsername) { this.basePath = basePathOrUsername } } } set useQuerystring(value: boolean) { this._useQuerystring = value; } set basePath(basePath: string) { this._basePath = basePath; } get basePath() { return this._basePath; } public setDefaultAuthentication(auth: Authentication) { this.authentications.default = auth; } public setApiKey(key: ProjectApiApiKeys, value: string) { (this.authentications as any)[ProjectApiApiKeys[key]].apiKey = value; } set accessToken(token: string) { this.authentications.OAuth2.accessToken = token; } /** * * @summary Create one or more new projects * @param xeroTenantId Xero identifier for Tenant * @param projectCreateOrUpdate Create a new project with ProjectCreateOrUpdate object */ public async createProject (xeroTenantId: string, projectCreateOrUpdate: ProjectCreateOrUpdate, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: Project; }> { const localVarPath = this.basePath + '/Projects'; let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'xeroTenantId' is not null or undefined if (xeroTenantId === null || xeroTenantId === undefined) { throw new Error('Required parameter xeroTenantId was null or undefined when calling createProject.'); } // verify required parameter 'projectCreateOrUpdate' is not null or undefined if (projectCreateOrUpdate === null || projectCreateOrUpdate === undefined) { throw new Error('Required parameter projectCreateOrUpdate was null or undefined when calling createProject.'); } localVarHeaderParams['Xero-Tenant-Id'] = ObjectSerializer.serialize(xeroTenantId, "string"); (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'POST', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(projectCreateOrUpdate, "ProjectCreateOrUpdate") }; let authenticationPromise = Promise.resolve(); authenticationPromise = authenticationPromise.then(() => this.authentications.OAuth2.applyToRequest(localVarRequestOptions)); authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); return authenticationPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body: Project; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Project"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); }); } /** * Allows you to create a specific task * @summary Creates a time entry for a specific project * @param xeroTenantId Xero identifier for Tenant * @param projectId You can specify an individual project by appending the projectId to the endpoint * @param timeEntryCreateOrUpdate The time entry object you are creating */ public async createTimeEntry (xeroTenantId: string, projectId: string, timeEntryCreateOrUpdate: TimeEntryCreateOrUpdate, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: TimeEntry; }> { const localVarPath = this.basePath + '/Projects/{projectId}/Time' .replace('{' + 'projectId' + '}', encodeURIComponent(String(projectId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'xeroTenantId' is not null or undefined if (xeroTenantId === null || xeroTenantId === undefined) { throw new Error('Required parameter xeroTenantId was null or undefined when calling createTimeEntry.'); } // verify required parameter 'projectId' is not null or undefined if (projectId === null || projectId === undefined) { throw new Error('Required parameter projectId was null or undefined when calling createTimeEntry.'); } // verify required parameter 'timeEntryCreateOrUpdate' is not null or undefined if (timeEntryCreateOrUpdate === null || timeEntryCreateOrUpdate === undefined) { throw new Error('Required parameter timeEntryCreateOrUpdate was null or undefined when calling createTimeEntry.'); } localVarHeaderParams['Xero-Tenant-Id'] = ObjectSerializer.serialize(xeroTenantId, "string"); (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'POST', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(timeEntryCreateOrUpdate, "TimeEntryCreateOrUpdate") }; let authenticationPromise = Promise.resolve(); authenticationPromise = authenticationPromise.then(() => this.authentications.OAuth2.applyToRequest(localVarRequestOptions)); authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); return authenticationPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body: TimeEntry; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "TimeEntry"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); }); } /** * Allows you to delete a specific time entry * @summary Deletes a time entry for a specific project * @param xeroTenantId Xero identifier for Tenant * @param projectId You can specify an individual project by appending the projectId to the endpoint * @param timeEntryId You can specify an individual task by appending the id to the endpoint */ public async deleteTimeEntry (xeroTenantId: string, projectId: string, timeEntryId: string, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body?: any; }> { const localVarPath = this.basePath + '/Projects/{projectId}/Time/{timeEntryId}' .replace('{' + 'projectId' + '}', encodeURIComponent(String(projectId))) .replace('{' + 'timeEntryId' + '}', encodeURIComponent(String(timeEntryId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'xeroTenantId' is not null or undefined if (xeroTenantId === null || xeroTenantId === undefined) { throw new Error('Required parameter xeroTenantId was null or undefined when calling deleteTimeEntry.'); } // verify required parameter 'projectId' is not null or undefined if (projectId === null || projectId === undefined) { throw new Error('Required parameter projectId was null or undefined when calling deleteTimeEntry.'); } // verify required parameter 'timeEntryId' is not null or undefined if (timeEntryId === null || timeEntryId === undefined) { throw new Error('Required parameter timeEntryId was null or undefined when calling deleteTimeEntry.'); } localVarHeaderParams['Xero-Tenant-Id'] = ObjectSerializer.serialize(xeroTenantId, "string"); (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'DELETE', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; let authenticationPromise = Promise.resolve(); authenticationPromise = authenticationPromise.then(() => this.authentications.OAuth2.applyToRequest(localVarRequestOptions)); authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); return authenticationPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); }); } /** * Allows you to retrieve a specific project using the projectId * @summary Retrieves a single project * @param xeroTenantId Xero identifier for Tenant * @param projectId You can specify an individual project by appending the projectId to the endpoint */ public async getProject (xeroTenantId: string, projectId: string, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: Project; }> { const localVarPath = this.basePath + '/Projects/{projectId}' .replace('{' + 'projectId' + '}', encodeURIComponent(String(projectId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'xeroTenantId' is not null or undefined if (xeroTenantId === null || xeroTenantId === undefined) { throw new Error('Required parameter xeroTenantId was null or undefined when calling getProject.'); } // verify required parameter 'projectId' is not null or undefined if (projectId === null || projectId === undefined) { throw new Error('Required parameter projectId was null or undefined when calling getProject.'); } localVarHeaderParams['Xero-Tenant-Id'] = ObjectSerializer.serialize(xeroTenantId, "string"); (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; let authenticationPromise = Promise.resolve(); authenticationPromise = authenticationPromise.then(() => this.authentications.OAuth2.applyToRequest(localVarRequestOptions)); authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); return authenticationPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body: Project; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Project"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); }); } /** * Allows you to retrieve the users on a projects. * @summary Retrieves a list of all project users * @param xeroTenantId Xero identifier for Tenant * @param page set to 1 by default. The requested number of the page in paged response - Must be a number greater than 0. * @param pageSize Optional, it is set to 50 by default. The number of items to return per page in a paged response - Must be a number between 1 and 500. */ public async getProjectUsers (xeroTenantId: string, page?: number, pageSize?: number, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: ProjectUsers; }> { const localVarPath = this.basePath + '/ProjectsUsers'; let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'xeroTenantId' is not null or undefined if (xeroTenantId === null || xeroTenantId === undefined) { throw new Error('Required parameter xeroTenantId was null or undefined when calling getProjectUsers.'); } if (page !== undefined) { localVarQueryParameters['page'] = ObjectSerializer.serialize(page, "number"); } if (pageSize !== undefined) { localVarQueryParameters['pageSize'] = ObjectSerializer.serialize(pageSize, "number"); } localVarHeaderParams['Xero-Tenant-Id'] = ObjectSerializer.serialize(xeroTenantId, "string"); (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; let authenticationPromise = Promise.resolve(); authenticationPromise = authenticationPromise.then(() => this.authentications.OAuth2.applyToRequest(localVarRequestOptions)); authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); return authenticationPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body: ProjectUsers; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "ProjectUsers"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); }); } /** * Allows you to retrieve, create and update projects. * @summary Retrieves all projects * @param xeroTenantId Xero identifier for Tenant * @param projectIds Search for all projects that match a comma separated list of projectIds * @param contactID Filter for projects for a specific contact * @param states Filter for projects in a particular state (INPROGRESS or CLOSED) * @param page set to 1 by default. The requested number of the page in paged response - Must be a number greater than 0. * @param pageSize Optional, it is set to 50 by default. The number of items to return per page in a paged response - Must be a number between 1 and 500. */ public async getProjects (xeroTenantId: string, projectIds?: Array<string>, contactID?: string, states?: string, page?: number, pageSize?: number, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: Projects; }> { const localVarPath = this.basePath + '/Projects'; let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'xeroTenantId' is not null or undefined if (xeroTenantId === null || xeroTenantId === undefined) { throw new Error('Required parameter xeroTenantId was null or undefined when calling getProjects.'); } if (projectIds !== undefined) { localVarQueryParameters['projectIds'] = ObjectSerializer.serialize(projectIds, "Array<string>"); } if (contactID !== undefined) { localVarQueryParameters['contactID'] = ObjectSerializer.serialize(contactID, "string"); } if (states !== undefined) { localVarQueryParameters['states'] = ObjectSerializer.serialize(states, "string"); } if (page !== undefined) { localVarQueryParameters['page'] = ObjectSerializer.serialize(page, "number"); } if (pageSize !== undefined) { localVarQueryParameters['pageSize'] = ObjectSerializer.serialize(pageSize, "number"); } localVarHeaderParams['Xero-Tenant-Id'] = ObjectSerializer.serialize(xeroTenantId, "string"); (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; let authenticationPromise = Promise.resolve(); authenticationPromise = authenticationPromise.then(() => this.authentications.OAuth2.applyToRequest(localVarRequestOptions)); authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); return authenticationPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body: Projects; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Projects"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); }); } /** * Allows you to retrieve a specific project * @summary Retrieves a single project task * @param xeroTenantId Xero identifier for Tenant * @param projectId You can specify an individual project by appending the projectId to the endpoint * @param taskId You can specify an individual task by appending the taskId to the endpoint, i.e. GET https://.../tasks/{taskID} */ public async getTask (xeroTenantId: string, projectId: string, taskId: string, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: Task; }> { const localVarPath = this.basePath + '/Projects/{projectId}/Tasks/{taskId}' .replace('{' + 'projectId' + '}', encodeURIComponent(String(projectId))) .replace('{' + 'taskId' + '}', encodeURIComponent(String(taskId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'xeroTenantId' is not null or undefined if (xeroTenantId === null || xeroTenantId === undefined) { throw new Error('Required parameter xeroTenantId was null or undefined when calling getTask.'); } // verify required parameter 'projectId' is not null or undefined if (projectId === null || projectId === undefined) { throw new Error('Required parameter projectId was null or undefined when calling getTask.'); } // verify required parameter 'taskId' is not null or undefined if (taskId === null || taskId === undefined) { throw new Error('Required parameter taskId was null or undefined when calling getTask.'); } localVarHeaderParams['Xero-Tenant-Id'] = ObjectSerializer.serialize(xeroTenantId, "string"); (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; let authenticationPromise = Promise.resolve(); authenticationPromise = authenticationPromise.then(() => this.authentications.OAuth2.applyToRequest(localVarRequestOptions)); authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); return authenticationPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body: Task; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Task"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); }); } /** * Allows you to retrieve a specific project * @summary Retrieves all project tasks * @param xeroTenantId Xero identifier for Tenant * @param projectId You can specify an individual project by appending the projectId to the endpoint * @param page Set to 1 by default. The requested number of the page in paged response - Must be a number greater than 0. * @param pageSize Optional, it is set to 50 by default. The number of items to return per page in a paged response - Must be a number between 1 and 500. * @param taskIds taskIdsSearch for all tasks that match a comma separated list of taskIds, i.e. GET https://.../tasks?taskIds&#x3D;{taskID},{taskID} * @param chargeType */ public async getTasks (xeroTenantId: string, projectId: string, page?: number, pageSize?: number, taskIds?: string, chargeType?: ChargeType, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: Tasks; }> { const localVarPath = this.basePath + '/Projects/{projectId}/Tasks' .replace('{' + 'projectId' + '}', encodeURIComponent(String(projectId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'xeroTenantId' is not null or undefined if (xeroTenantId === null || xeroTenantId === undefined) { throw new Error('Required parameter xeroTenantId was null or undefined when calling getTasks.'); } // verify required parameter 'projectId' is not null or undefined if (projectId === null || projectId === undefined) { throw new Error('Required parameter projectId was null or undefined when calling getTasks.'); } if (page !== undefined) { localVarQueryParameters['page'] = ObjectSerializer.serialize(page, "number"); } if (pageSize !== undefined) { localVarQueryParameters['pageSize'] = ObjectSerializer.serialize(pageSize, "number"); } if (taskIds !== undefined) { localVarQueryParameters['taskIds'] = ObjectSerializer.serialize(taskIds, "string"); } if (chargeType !== undefined) { localVarQueryParameters['chargeType'] = ObjectSerializer.serialize(chargeType, "ChargeType"); } localVarHeaderParams['Xero-Tenant-Id'] = ObjectSerializer.serialize(xeroTenantId, "string"); (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; let authenticationPromise = Promise.resolve(); authenticationPromise = authenticationPromise.then(() => this.authentications.OAuth2.applyToRequest(localVarRequestOptions)); authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); return authenticationPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body: Tasks; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "Tasks"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); }); } /** * Allows you to retrieve the time entries associated with a specific project * @summary Retrieves all time entries associated with a specific project * @param xeroTenantId Xero identifier for Tenant * @param projectId Identifier of the project, that the task (which the time entry is logged against) belongs to. * @param userId The xero user identifier of the person who logged time. * @param taskId Identifier of the task that time entry is logged against. * @param invoiceId Finds all time entries for this invoice. * @param contactId Finds all time entries for this contact identifier. * @param page Set to 1 by default. The requested number of the page in paged response - Must be a number greater than 0. * @param pageSize Optional, it is set to 50 by default. The number of items to return per page in a paged response - Must be a number between 1 and 500. * @param states Comma-separated list of states to find. Will find all time entries that are in the status of whatever is specified. * @param isChargeable Finds all time entries which relate to tasks with the charge type &#x60;TIME&#x60; or &#x60;FIXED&#x60;. * @param dateAfterUtc ISO 8601 UTC date. Finds all time entries on or after this date filtered on the &#x60;dateUtc&#x60; field. * @param dateBeforeUtc ISO 8601 UTC date. Finds all time entries on or before this date filtered on the &#x60;dateUtc&#x60; field. */ public async getTimeEntries (xeroTenantId: string, projectId: string, userId?: string, taskId?: string, invoiceId?: string, contactId?: string, page?: number, pageSize?: number, states?: Array<string>, isChargeable?: boolean, dateAfterUtc?: Date, dateBeforeUtc?: Date, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: TimeEntries; }> { const localVarPath = this.basePath + '/Projects/{projectId}/Time' .replace('{' + 'projectId' + '}', encodeURIComponent(String(projectId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'xeroTenantId' is not null or undefined if (xeroTenantId === null || xeroTenantId === undefined) { throw new Error('Required parameter xeroTenantId was null or undefined when calling getTimeEntries.'); } // verify required parameter 'projectId' is not null or undefined if (projectId === null || projectId === undefined) { throw new Error('Required parameter projectId was null or undefined when calling getTimeEntries.'); } if (userId !== undefined) { localVarQueryParameters['userId'] = ObjectSerializer.serialize(userId, "string"); } if (taskId !== undefined) { localVarQueryParameters['taskId'] = ObjectSerializer.serialize(taskId, "string"); } if (invoiceId !== undefined) { localVarQueryParameters['invoiceId'] = ObjectSerializer.serialize(invoiceId, "string"); } if (contactId !== undefined) { localVarQueryParameters['contactId'] = ObjectSerializer.serialize(contactId, "string"); } if (page !== undefined) { localVarQueryParameters['page'] = ObjectSerializer.serialize(page, "number"); } if (pageSize !== undefined) { localVarQueryParameters['pageSize'] = ObjectSerializer.serialize(pageSize, "number"); } if (states !== undefined) { localVarQueryParameters['states'] = ObjectSerializer.serialize(states, "Array<string>"); } if (isChargeable !== undefined) { localVarQueryParameters['isChargeable'] = ObjectSerializer.serialize(isChargeable, "boolean"); } if (dateAfterUtc !== undefined) { localVarQueryParameters['dateAfterUtc'] = ObjectSerializer.serialize(dateAfterUtc, "Date"); } if (dateBeforeUtc !== undefined) { localVarQueryParameters['dateBeforeUtc'] = ObjectSerializer.serialize(dateBeforeUtc, "Date"); } localVarHeaderParams['Xero-Tenant-Id'] = ObjectSerializer.serialize(xeroTenantId, "string"); (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; let authenticationPromise = Promise.resolve(); authenticationPromise = authenticationPromise.then(() => this.authentications.OAuth2.applyToRequest(localVarRequestOptions)); authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); return authenticationPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body: TimeEntries; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "TimeEntries"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); }); } /** * Allows you to get a single time entry in a project * @summary Retrieves a single time entry for a specific project * @param xeroTenantId Xero identifier for Tenant * @param projectId You can specify an individual project by appending the projectId to the endpoint * @param timeEntryId You can specify an individual time entry by appending the id to the endpoint */ public async getTimeEntry (xeroTenantId: string, projectId: string, timeEntryId: string, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: TimeEntry; }> { const localVarPath = this.basePath + '/Projects/{projectId}/Time/{timeEntryId}' .replace('{' + 'projectId' + '}', encodeURIComponent(String(projectId))) .replace('{' + 'timeEntryId' + '}', encodeURIComponent(String(timeEntryId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'xeroTenantId' is not null or undefined if (xeroTenantId === null || xeroTenantId === undefined) { throw new Error('Required parameter xeroTenantId was null or undefined when calling getTimeEntry.'); } // verify required parameter 'projectId' is not null or undefined if (projectId === null || projectId === undefined) { throw new Error('Required parameter projectId was null or undefined when calling getTimeEntry.'); } // verify required parameter 'timeEntryId' is not null or undefined if (timeEntryId === null || timeEntryId === undefined) { throw new Error('Required parameter timeEntryId was null or undefined when calling getTimeEntry.'); } localVarHeaderParams['Xero-Tenant-Id'] = ObjectSerializer.serialize(xeroTenantId, "string"); (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; let authenticationPromise = Promise.resolve(); authenticationPromise = authenticationPromise.then(() => this.authentications.OAuth2.applyToRequest(localVarRequestOptions)); authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); return authenticationPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body: TimeEntry; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "TimeEntry"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); }); } /** * Allows you to update a specific projects. * @summary creates a project for the specified contact * @param xeroTenantId Xero identifier for Tenant * @param projectId You can specify an individual project by appending the projectId to the endpoint * @param projectPatch Update the status of an existing Project */ public async patchProject (xeroTenantId: string, projectId: string, projectPatch: ProjectPatch, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body?: any; }> { const localVarPath = this.basePath + '/Projects/{projectId}' .replace('{' + 'projectId' + '}', encodeURIComponent(String(projectId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'xeroTenantId' is not null or undefined if (xeroTenantId === null || xeroTenantId === undefined) { throw new Error('Required parameter xeroTenantId was null or undefined when calling patchProject.'); } // verify required parameter 'projectId' is not null or undefined if (projectId === null || projectId === undefined) { throw new Error('Required parameter projectId was null or undefined when calling patchProject.'); } // verify required parameter 'projectPatch' is not null or undefined if (projectPatch === null || projectPatch === undefined) { throw new Error('Required parameter projectPatch was null or undefined when calling patchProject.'); } localVarHeaderParams['Xero-Tenant-Id'] = ObjectSerializer.serialize(xeroTenantId, "string"); (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'PATCH', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(projectPatch, "ProjectPatch") }; let authenticationPromise = Promise.resolve(); authenticationPromise = authenticationPromise.then(() => this.authentications.OAuth2.applyToRequest(localVarRequestOptions)); authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); return authenticationPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); }); } /** * Allows you to update a specific projects. * @summary Updates a specific project * @param xeroTenantId Xero identifier for Tenant * @param projectId You can specify an individual project by appending the projectId to the endpoint * @param projectCreateOrUpdate Request of type ProjectCreateOrUpdate */ public async updateProject (xeroTenantId: string, projectId: string, projectCreateOrUpdate: ProjectCreateOrUpdate, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body?: any; }> { const localVarPath = this.basePath + '/Projects/{projectId}' .replace('{' + 'projectId' + '}', encodeURIComponent(String(projectId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'xeroTenantId' is not null or undefined if (xeroTenantId === null || xeroTenantId === undefined) { throw new Error('Required parameter xeroTenantId was null or undefined when calling updateProject.'); } // verify required parameter 'projectId' is not null or undefined if (projectId === null || projectId === undefined) { throw new Error('Required parameter projectId was null or undefined when calling updateProject.'); } // verify required parameter 'projectCreateOrUpdate' is not null or undefined if (projectCreateOrUpdate === null || projectCreateOrUpdate === undefined) { throw new Error('Required parameter projectCreateOrUpdate was null or undefined when calling updateProject.'); } localVarHeaderParams['Xero-Tenant-Id'] = ObjectSerializer.serialize(xeroTenantId, "string"); (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'PUT', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(projectCreateOrUpdate, "ProjectCreateOrUpdate") }; let authenticationPromise = Promise.resolve(); authenticationPromise = authenticationPromise.then(() => this.authentications.OAuth2.applyToRequest(localVarRequestOptions)); authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); return authenticationPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); }); } /** * Allows you to update time entry in a project * @summary Updates a time entry for a specific project * @param xeroTenantId Xero identifier for Tenant * @param projectId You can specify an individual project by appending the projectId to the endpoint * @param timeEntryId You can specify an individual time entry by appending the id to the endpoint * @param timeEntryCreateOrUpdate The time entry object you are updating */ public async updateTimeEntry (xeroTenantId: string, projectId: string, timeEntryId: string, timeEntryCreateOrUpdate: TimeEntryCreateOrUpdate, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body?: any; }> { const localVarPath = this.basePath + '/Projects/{projectId}/Time/{timeEntryId}' .replace('{' + 'projectId' + '}', encodeURIComponent(String(projectId))) .replace('{' + 'timeEntryId' + '}', encodeURIComponent(String(timeEntryId))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'xeroTenantId' is not null or undefined if (xeroTenantId === null || xeroTenantId === undefined) { throw new Error('Required parameter xeroTenantId was null or undefined when calling updateTimeEntry.'); } // verify required parameter 'projectId' is not null or undefined if (projectId === null || projectId === undefined) { throw new Error('Required parameter projectId was null or undefined when calling updateTimeEntry.'); } // verify required parameter 'timeEntryId' is not null or undefined if (timeEntryId === null || timeEntryId === undefined) { throw new Error('Required parameter timeEntryId was null or undefined when calling updateTimeEntry.'); } // verify required parameter 'timeEntryCreateOrUpdate' is not null or undefined if (timeEntryCreateOrUpdate === null || timeEntryCreateOrUpdate === undefined) { throw new Error('Required parameter timeEntryCreateOrUpdate was null or undefined when calling updateTimeEntry.'); } localVarHeaderParams['Xero-Tenant-Id'] = ObjectSerializer.serialize(xeroTenantId, "string"); (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'PUT', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(timeEntryCreateOrUpdate, "TimeEntryCreateOrUpdate") }; let authenticationPromise = Promise.resolve(); authenticationPromise = authenticationPromise.then(() => this.authentications.OAuth2.applyToRequest(localVarRequestOptions)); authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); return authenticationPromise.then(() => { if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); }); } }
the_stack
import { expect } from "chai"; import sinon from "sinon"; import * as moq from "typemoq"; import { AccessToken, BeEvent } from "@itwin/core-bentley"; import { AuthorizationClient, InternetConnectivityStatus } from "@itwin/core-common"; import { IModelApp } from "@itwin/core-frontend"; import { configureForPromiseResult, ResolvablePromise } from "@itwin/presentation-common/lib/cjs/test"; import { SettingsAdmin, SettingsStatus } from "@bentley/product-settings-client"; import { IConnectivityInformationProvider } from "../../presentation-frontend/ConnectivityInformationProvider"; import { FavoritePropertiesOrderInfo, PropertyFullName } from "../../presentation-frontend/favorite-properties/FavoritePropertiesManager"; import { BrowserLocalFavoritePropertiesStorage, createFavoritePropertiesStorage, DefaultFavoritePropertiesStorageTypes, IModelAppFavoritePropertiesStorage, NoopFavoritePropertiesStorage, OfflineCachingFavoritePropertiesStorage, } from "../../presentation-frontend/favorite-properties/FavoritePropertiesStorage"; describe("IModelAppFavoritePropertiesStorage", () => { let storage: IModelAppFavoritePropertiesStorage; let settingsAdminMock: moq.IMock<SettingsAdmin>; let authorizationClientMock: moq.IMock<AuthorizationClient>; beforeEach(async () => { const requestConextMock = moq.Mock.ofType<AccessToken>(); configureForPromiseResult(requestConextMock); sinon.stub(IModelApp, "settings").get(() => settingsAdminMock.object); authorizationClientMock = moq.Mock.ofType<AuthorizationClient>(); const accessToken: AccessToken = "TestToken"; authorizationClientMock.setup(async (x) => x.getAccessToken()).returns(async () => Promise.resolve(accessToken)); IModelApp.authorizationClient = authorizationClientMock.object; storage = new IModelAppFavoritePropertiesStorage(); }); afterEach(() => { sinon.restore(); }); describe("loadProperties", () => { it("returns favorite properties", async () => { settingsAdminMock = moq.Mock.ofType<SettingsAdmin>(); settingsAdminMock.setup(async (x) => x.getUserSetting(moq.It.isAny(), moq.It.isAny(), moq.It.isAny(), moq.It.isAny(), moq.It.isAny(), moq.It.isAny())).returns(async () => ({ status: SettingsStatus.Success, setting: [], })); const properties = await storage.loadProperties(); expect(properties).to.be.not.undefined; expect(properties!.size).to.eq(0); }); it("is backwards compatible", async () => { settingsAdminMock = moq.Mock.ofType<SettingsAdmin>(); settingsAdminMock.setup(async (x) => x.getUserSetting(moq.It.isAny(), "imodeljs.presentation", moq.It.isAny(), moq.It.isAny(), moq.It.isAny(), moq.It.isAny())).returns(async () => ({ status: SettingsStatus.Success, setting: undefined, })); settingsAdminMock.setup(async (x) => x.getUserSetting(moq.It.isAny(), "Properties", moq.It.isAny(), moq.It.isAny(), moq.It.isAny(), moq.It.isAny())).returns(async () => ({ status: SettingsStatus.Success, setting: { nestedContentInfos: new Set<string>(["nestedContentInfo"]), propertyInfos: new Set<string>(["propertyInfo"]), baseFieldInfos: new Set<string>(["baseFieldInfo"]), }, })); const properties = await storage.loadProperties(); expect(properties).to.be.not.undefined; expect(properties!.size).to.eq(3); }); it("returns undefined", async () => { settingsAdminMock.setup(async (x) => x.getUserSetting(moq.It.isAny(), "imodeljs.presentation", moq.It.isAny(), moq.It.isAny(), moq.It.isAny(), moq.It.isAny())).returns(async () => ({ status: SettingsStatus.UnknownError, setting: undefined, })); settingsAdminMock.setup(async (x) => x.getUserSetting(moq.It.isAny(), "Properties", moq.It.isAny(), moq.It.isAny(), moq.It.isAny(), moq.It.isAny())).returns(async () => ({ status: SettingsStatus.UnknownError, setting: undefined, })); const properties = await storage.loadProperties(); expect(properties).to.be.undefined; }); it("throws when not signed in", async () => { authorizationClientMock.reset(); authorizationClientMock.setup(async (x) => x.getAccessToken()).returns(async () => Promise.resolve("")); await expect(storage.loadProperties()).to.eventually.be.rejected; }); }); describe("saveProperties", () => { it("saves favorite properties", async () => { settingsAdminMock.setup(async (x) => x.saveUserSetting(moq.It.isAny(), moq.It.isAny(), moq.It.isAny(), moq.It.isAny(), moq.It.isAny())).returns(async () => ({ status: SettingsStatus.Success, })); const properties = new Set<PropertyFullName>(["propertyInfo1", "propertyInfo2"]); await storage.saveProperties(properties); settingsAdminMock.verify(async (x) => x.saveUserSetting(moq.It.isAny(), moq.It.isAny(), moq.It.isAny(), moq.It.isAny(), moq.It.isAny(), undefined, undefined), moq.Times.once()); }); it("throws when not signed in", async () => { authorizationClientMock.reset(); authorizationClientMock.setup(async (x) => x.getAccessToken()).returns(async () => Promise.resolve("")); await expect(storage.saveProperties(new Set())).to.eventually.be.rejected; }); }); describe("loadPropertiesOrder", () => { it("returns properties order", async () => { const orderInfo: FavoritePropertiesOrderInfo = { parentClassName: undefined, name: "orderInfoName", priority: 5, orderedTimestamp: new Date(), }; settingsAdminMock = moq.Mock.ofType<SettingsAdmin>(); settingsAdminMock.setup(async (x) => x.getUserSetting(moq.It.isAny(), "imodeljs.presentation", "FavoritePropertiesOrderInfo", moq.It.isAny(), moq.It.isAny(), moq.It.isAny())).returns(async () => ({ status: SettingsStatus.Success, setting: [orderInfo], })); const properties = await storage.loadPropertiesOrder("iTwinId", "imodelId"); expect(properties).to.be.not.undefined; expect(properties!.length).to.eq(1); expect(properties![0]).to.eq(orderInfo); }); it("returns undefined", async () => { settingsAdminMock.setup(async (x) => x.getUserSetting(moq.It.isAny(), "imodeljs.presentation", "FavoritePropertiesOrderInfo", moq.It.isAny(), moq.It.isAny(), moq.It.isAny())).returns(async () => ({ status: SettingsStatus.UnknownError, setting: undefined, })); sinon.stub(IModelApp, "settings").get(() => settingsAdminMock.object); const properties = await storage.loadPropertiesOrder("iTwinId", "imodelId"); expect(properties).to.be.undefined; }); it("throws when not signed in", async () => { authorizationClientMock.reset(); authorizationClientMock.setup(async (x) => x.getAccessToken()).returns(async () => Promise.resolve("")); await expect(storage.loadPropertiesOrder("iTwinId", "imodelId")).to.eventually.be.rejected; }); }); describe("savePropertiesOrder", () => { it("saves properties order", async () => { settingsAdminMock.setup(async (x) => x.saveUserSetting(moq.It.isAny(), moq.It.isAny(), "imodeljs.presentation", "FavoritePropertiesOrderInfo", moq.It.isAny())).returns(async () => ({ status: SettingsStatus.Success, })); const orderInfo: FavoritePropertiesOrderInfo = { parentClassName: undefined, name: "orderInfoName", priority: 5, orderedTimestamp: new Date(), }; await storage.savePropertiesOrder([orderInfo], "iTwinId", "imodelId"); settingsAdminMock.verify(async (x) => x.saveUserSetting(moq.It.isAny(), moq.It.isAny(), "imodeljs.presentation", "FavoritePropertiesOrderInfo", moq.It.isAny(), moq.It.isAny(), moq.It.isAny()), moq.Times.once()); }); it("throws when not signed in", async () => { authorizationClientMock.reset(); authorizationClientMock.setup(async (x) => x.getAccessToken()).returns(async () => Promise.resolve("")); await expect(storage.savePropertiesOrder([], "iTwinId", "imodelId")).to.eventually.be.rejected; }); }); }); describe("OfflineCachingFavoritePropertiesStorage", () => { const impl = { loadProperties: sinon.stub(), saveProperties: sinon.stub(), loadPropertiesOrder: sinon.stub(), savePropertiesOrder: sinon.stub(), }; const connectivityInfo: IConnectivityInformationProvider = { onInternetConnectivityChanged: new BeEvent(), status: InternetConnectivityStatus.Offline, }; let storage: OfflineCachingFavoritePropertiesStorage; beforeEach(() => { impl.loadProperties.reset(); impl.loadPropertiesOrder.reset(); impl.saveProperties.reset(); impl.savePropertiesOrder.reset(); connectivityInfo.onInternetConnectivityChanged.clear(); storage = new OfflineCachingFavoritePropertiesStorage({ impl, connectivityInfo }); }); afterEach(() => { storage.dispose(); sinon.restore(); }); describe("saveProperties", () => { describe("when offline", () => { beforeEach(() => { sinon.stub(connectivityInfo, "status").get(() => InternetConnectivityStatus.Offline); }); it("saves properties to cache", async () => { await storage.saveProperties(new Set()); expect(impl.saveProperties).to.not.be.called; }); }); describe("when online", () => { beforeEach(() => { sinon.stub(connectivityInfo, "status").get(() => InternetConnectivityStatus.Online); }); it("saves properties and clears offline cache when `impl` succeeds", async () => { // add something to offline cache await offline(async () => storage.saveProperties(new Set(["a"]), "b", "c")); expect(await offline(async () => storage.loadProperties("b", "c"))).to.not.be.undefined; // call save while online const set = new Set(["d"]); await storage.saveProperties(set, "b", "c"); expect(impl.saveProperties).to.be.calledOnceWith(set, "b", "c"); // verify the offline cache is empty expect(await offline(async () => storage.loadProperties("b", "c"))).to.be.undefined; }); it("saves properties and doesn't clear offline cache when `impl` request succeeds after offline call", async () => { const implPromise = new ResolvablePromise<void>(); impl.saveProperties.returns(implPromise); const result = Promise.all([ online(async () => storage.saveProperties(new Set(["1"]), "x", "z")), offline(async () => storage.saveProperties(new Set(["2"]), "x", "z")), ]); expect(impl.saveProperties).to.be.calledOnce; await implPromise.resolve(); await result; // verify the offline cache now contains value of the most recent `saveProperties` call expect(await offline(async () => storage.loadProperties("x", "z"))).to.contain("2"); }); it("saves properties and puts them to offline cache when `impl` fails", async () => { // add something to offline cache await offline(async () => storage.saveProperties(new Set(["a"]), "b", "c")); expect(await offline(async () => storage.loadProperties("b", "c"))).to.not.be.undefined; // call save while online impl.saveProperties.returns(Promise.reject()); const set = new Set(["d"]); await storage.saveProperties(set, "b", "c"); expect(impl.saveProperties).to.be.calledOnceWith(set, "b", "c"); // verify the offline cache now contains value of the most recent `saveProperties` call const result = await offline(async () => storage.loadProperties("b", "c")); expect(result?.size).to.eq(1); expect(result).to.contain("d"); }); it("stores properties to offline cache the last value when two `impl` requests fail in sequence", async () => { const implPromises = [0, 1].map(() => new ResolvablePromise<void>()); impl.saveProperties.resetBehavior(); impl.saveProperties.onFirstCall().returns(implPromises[0]); impl.saveProperties.onSecondCall().returns(implPromises[1]); const result = Promise.all([ storage.saveProperties(new Set(["1"]), "x", "z"), storage.saveProperties(new Set(["2"]), "x", "z"), ]); expect(impl.saveProperties).to.be.calledTwice; implPromises.forEach(async (promise) => promise.reject()); await result; // verify the offline cache now contains value of the most recent `saveProperties` call expect(await offline(async () => storage.loadProperties("x", "z"))).to.contain("2"); }); it("stores properties to offline cache the last value when two `impl` requests fail in opposite order", async () => { const implPromises = [0, 1].map(() => new ResolvablePromise<void>()); impl.saveProperties.resetBehavior(); impl.saveProperties.onFirstCall().returns(implPromises[0]); impl.saveProperties.onSecondCall().returns(implPromises[1]); const result = Promise.all([ storage.saveProperties(new Set(["1"]), "x", "z"), storage.saveProperties(new Set(["2"]), "x", "z"), ]); expect(impl.saveProperties).to.be.calledTwice; implPromises.reverse().forEach(async (promise) => promise.reject()); await result; // verify the offline cache now contains value of the most recent `saveProperties` call expect(await offline(async () => storage.loadProperties("x", "z"))).to.contain("2"); }); it("stores properties to offline cache the last value when `impl` request fails before offline call", async () => { impl.saveProperties.returns(Promise.reject()); const result = Promise.all([ online(async () => storage.saveProperties(new Set(["1"]), "x", "z")), offline(async () => storage.saveProperties(new Set(["2"]), "x", "z")), ]); expect(impl.saveProperties).to.be.calledOnce; await result; // verify the offline cache now contains value of the most recent `saveProperties` call expect(await offline(async () => storage.loadProperties("x", "z"))).to.contain("2"); }); it("stores properties to offline cache the last value when `impl` request fails after offline call", async () => { const implPromise = new ResolvablePromise<void>(); impl.saveProperties.returns(implPromise); const result = Promise.all([ online(async () => storage.saveProperties(new Set(["1"]), "x", "z")), offline(async () => storage.saveProperties(new Set(["2"]), "x", "z")), ]); expect(impl.saveProperties).to.be.calledOnce; await implPromise.reject(); await result; // verify the offline cache now contains value of the most recent `saveProperties` call expect(await offline(async () => storage.loadProperties("x", "z"))).to.contain("2"); }); }); }); describe("loadProperties", () => { describe("when offline", () => { beforeEach(() => { sinon.stub(connectivityInfo, "status").get(() => InternetConnectivityStatus.Offline); }); it("returns `undefined`and there's no cached value", async () => { const result = await storage.loadProperties("a", "b"); expect(result).to.be.undefined; }); it("loads from cache and there's cached value", async () => { await storage.saveProperties(new Set(["test1", "test2"]), "a", "b"); const result = await storage.loadProperties("a", "b"); expect(impl.loadProperties).to.not.be.called; expect(result?.size).to.eq(2); expect(result).to.contain("test1"); expect(result).to.contain("test2"); }); }); describe("when online", () => { beforeEach(() => { sinon.stub(connectivityInfo, "status").get(() => InternetConnectivityStatus.Online); }); it("loads properties from `impl`", async () => { impl.loadProperties.returns(Promise.resolve(undefined)); await storage.loadProperties("a", "b"); expect(impl.loadProperties).to.be.calledOnce; }); it("loads from cache if `impl` load fails", async () => { await offline(async () => storage.saveProperties(new Set(["cached"]), "a", "b")); impl.loadProperties.returns(Promise.reject()); const result = await storage.loadProperties("a", "b"); expect(impl.loadProperties).to.be.calledOnce; expect(result?.size).to.eq(1); expect(result).to.contain("cached"); }); }); }); describe("savePropertiesOrder", () => { describe("when offline", () => { beforeEach(() => { sinon.stub(connectivityInfo, "status").get(() => InternetConnectivityStatus.Offline); }); it("saves properties order to cache", async () => { await storage.savePropertiesOrder([createRandomPropertiesOrderInfo()], "a", "b"); expect(impl.savePropertiesOrder).to.not.be.called; }); }); describe("when online", () => { beforeEach(() => { sinon.stub(connectivityInfo, "status").get(() => InternetConnectivityStatus.Online); }); it("saves properties order and clears offline cache when `impl` succeeds", async () => { // add something to offline cache await offline(async () => storage.savePropertiesOrder([createRandomPropertiesOrderInfo()], "b", "c")); expect(await offline(async () => storage.loadPropertiesOrder("b", "c"))).to.not.be.undefined; // call save while online const order = createRandomPropertiesOrderInfo(); await storage.savePropertiesOrder([order], "b", "c"); expect(impl.savePropertiesOrder).to.be.calledOnceWith([order], "b", "c"); // verify the offline cache is empty expect(await offline(async () => storage.loadPropertiesOrder("b", "c"))).to.be.undefined; }); it("saves properties order and doesn't clear offline cache when `impl` request succeeds after offline call", async () => { const orderInfos = [0, 1].map(() => createRandomPropertiesOrderInfo()); const implPromise = new ResolvablePromise<void>(); impl.saveProperties.returns(implPromise); const result = Promise.all([ online(async () => storage.savePropertiesOrder([orderInfos[0]], "x", "z")), offline(async () => storage.savePropertiesOrder([orderInfos[1]], "x", "z")), ]); expect(impl.savePropertiesOrder).to.be.calledOnce; await implPromise.resolve(); await result; // verify the offline cache now contains value of the most recent `savePropertiesOrder` call expect(await offline(async () => storage.loadPropertiesOrder("x", "z"))).to.contain(orderInfos[1]); }); it("saves properties order and puts them to offline cache when `impl` fails", async () => { // add something to offline cache await offline(async () => storage.savePropertiesOrder([createRandomPropertiesOrderInfo()], "b", "c")); expect(await offline(async () => storage.loadPropertiesOrder("b", "c"))).to.not.be.undefined; // call save while online impl.savePropertiesOrder.returns(Promise.reject()); const order = createRandomPropertiesOrderInfo(); await storage.savePropertiesOrder([order], "b", "c"); expect(impl.savePropertiesOrder).to.be.calledOnceWith([order], "b", "c"); // verify the offline cache now contains value of the most recent `savePropertiesOrder` call const result = await offline(async () => storage.loadPropertiesOrder("b", "c")); expect(result?.length).to.eq(1); expect(result).to.contain(order); }); it("stores properties order to offline cache the last value when two `impl` requests fail in sequence", async () => { const orderInfos = [0, 1].map(() => createRandomPropertiesOrderInfo()); const implPromises = [0, 1].map(() => new ResolvablePromise<void>()); impl.savePropertiesOrder.resetBehavior(); impl.savePropertiesOrder.onFirstCall().returns(implPromises[0]); impl.savePropertiesOrder.onSecondCall().returns(implPromises[1]); const result = Promise.all(orderInfos.map(async (order) => storage.savePropertiesOrder([order], "x", "z"))); expect(impl.savePropertiesOrder).to.be.calledTwice; implPromises.forEach(async (promise) => promise.reject()); await result; // verify the offline cache now contains value of the most recent `savePropertiesOrder` call expect(await offline(async () => storage.loadPropertiesOrder("x", "z"))).to.contain(orderInfos[1]); }); it("stores properties order to offline cache the last value when two `impl` requests fail in opposite order", async () => { const orderInfos = [0, 1].map(() => createRandomPropertiesOrderInfo()); const implPromises = [0, 1].map(() => new ResolvablePromise<void>()); impl.savePropertiesOrder.resetBehavior(); impl.savePropertiesOrder.onFirstCall().returns(implPromises[0]); impl.savePropertiesOrder.onSecondCall().returns(implPromises[1]); const result = Promise.all(orderInfos.map(async (order) => storage.savePropertiesOrder([order], "x", "z"))); expect(impl.savePropertiesOrder).to.be.calledTwice; implPromises.reverse().forEach(async (promise) => promise.reject()); await result; // verify the offline cache now contains value of the most recent `savePropertiesOrder` call expect(await offline(async () => storage.loadPropertiesOrder("x", "z"))).to.contain(orderInfos[1]); }); it("stores properties order to offline cache the last value when `impl` request fails before offline call", async () => { const orderInfos = [0, 1].map(() => createRandomPropertiesOrderInfo()); impl.savePropertiesOrder.returns(Promise.reject()); const result = Promise.all([ online(async () => storage.savePropertiesOrder([orderInfos[0]], "x", "z")), offline(async () => storage.savePropertiesOrder([orderInfos[1]], "x", "z")), ]); expect(impl.savePropertiesOrder).to.be.calledOnce; await result; // verify the offline cache now contains value of the most recent `savePropertiesOrder` call expect(await offline(async () => storage.loadPropertiesOrder("x", "z"))).to.contain(orderInfos[1]); }); it("stores properties order to offline cache the last value when `impl` request fails after offline call", async () => { const orderInfos = [0, 1].map(() => createRandomPropertiesOrderInfo()); const implPromise = new ResolvablePromise<void>(); impl.savePropertiesOrder.returns(implPromise); const result = Promise.all([ online(async () => storage.savePropertiesOrder([orderInfos[0]], "x", "z")), offline(async () => storage.savePropertiesOrder([orderInfos[1]], "x", "z")), ]); expect(impl.savePropertiesOrder).to.be.calledOnce; await implPromise.reject(); await result; // verify the offline cache now contains value of the most recent `savePropertiesOrder` call expect(await offline(async () => storage.loadPropertiesOrder("x", "z"))).to.contain(orderInfos[1]); }); }); }); describe("loadPropertiesOrder", () => { describe("when offline", () => { beforeEach(() => { sinon.stub(connectivityInfo, "status").get(() => InternetConnectivityStatus.Offline); }); it("returns `undefined` and there's no cached value", async () => { const result = await storage.loadPropertiesOrder("a", "b"); expect(result).to.be.undefined; }); it("loads from cache and there's cached value", async () => { const orderInfo = createRandomPropertiesOrderInfo(); await storage.savePropertiesOrder([orderInfo], "a", "b"); const result = await storage.loadPropertiesOrder("a", "b"); expect(impl.loadPropertiesOrder).to.not.be.called; expect(result?.length).to.eq(1); expect(result).to.contain(orderInfo); }); }); describe("when online", () => { beforeEach(() => { sinon.stub(connectivityInfo, "status").get(() => InternetConnectivityStatus.Online); }); it("loads properties from `impl`", async () => { impl.loadPropertiesOrder.returns(Promise.resolve(undefined)); await storage.loadPropertiesOrder("a", "b"); expect(impl.loadPropertiesOrder).to.be.calledOnce; }); it("loads from cache if `impl` load fails", async () => { const order = createRandomPropertiesOrderInfo(); await offline(async () => storage.savePropertiesOrder([order], "a", "b")); impl.loadPropertiesOrder.returns(Promise.reject()); const result = await storage.loadPropertiesOrder("a", "b"); expect(impl.loadPropertiesOrder).to.be.calledOnce; expect(result?.length).to.eq(1); expect(result).to.contain(order); }); }); }); describe("reacting to connectivity status changes", () => { it("saves cached offline properties and order when comes online", async () => { // store some data to offline cache const propertiesSet = new Set(["a"]); const orderInfo = createRandomPropertiesOrderInfo(); await offline(async () => storage.saveProperties(propertiesSet, "b", "c")); await offline(async () => storage.savePropertiesOrder([orderInfo], "b", "c")); expect(impl.saveProperties).to.not.be.called; expect(impl.savePropertiesOrder).to.not.be.called; // notify the connection status changed to 'online' sinon.stub(connectivityInfo, "status").get(() => InternetConnectivityStatus.Online); connectivityInfo.onInternetConnectivityChanged.raiseEvent({ status: InternetConnectivityStatus.Online }); // expect properties and order to be synced with `impl` and removed from offline cache expect(impl.saveProperties).to.be.calledOnceWith(propertiesSet, "b", "c"); expect(impl.savePropertiesOrder).to.be.calledOnceWith([orderInfo], "b", "c"); expect(await offline(async () => storage.loadProperties("b", "c"))).to.be.undefined; expect(await offline(async () => storage.loadPropertiesOrder("b", "c"))).to.be.undefined; }); }); it("disposes IConnectivityInformationProvider", () => { const disposableConnectivityInfo = { onInternetConnectivityChanged: new BeEvent(), status: InternetConnectivityStatus.Offline, dispose: sinon.spy(), }; storage = new OfflineCachingFavoritePropertiesStorage({ impl, connectivityInfo: disposableConnectivityInfo }); storage.dispose(); expect(disposableConnectivityInfo.dispose).to.be.calledOnce; }); const callInConnectivityContext = async <T>(cb: (() => Promise<T>), connectivityStatus: InternetConnectivityStatus) => { const stub = sinon.stub(connectivityInfo, "status").get(() => connectivityStatus); const result = await cb(); stub.restore(); return result; }; const offline = async <T>(cb: (() => Promise<T>)) => { return callInConnectivityContext(cb, InternetConnectivityStatus.Offline); }; const online = async <T>(cb: (() => Promise<T>)) => { return callInConnectivityContext(cb, InternetConnectivityStatus.Online); }; }); describe("BrowserLocalFavoritePropertiesStorage", () => { let storage: BrowserLocalFavoritePropertiesStorage; let storageMock: moq.IMock<Storage>; beforeEach(() => { storageMock = moq.Mock.ofType<Storage>(); storage = new BrowserLocalFavoritePropertiesStorage({ localStorage: storageMock.object }); }); afterEach(() => { sinon.restore(); }); describe("saveProperties", () => { it("saves properties to local storage", async () => { await storage.saveProperties(new Set(["test"]), "a", "b"); storageMock.verify((x) => x.setItem(storage.createFavoritesSettingItemKey("a", "b"), `["test"]`), moq.Times.once()); }); }); describe("loadProperties", () => { it("returns `undefined`and there's no cached value", async () => { storageMock.setup((x) => x.getItem(moq.It.isAny())).returns(() => null); const result = await storage.loadProperties("a", "b"); expect(result).to.be.undefined; }); it("loads from local storage where there's a value", async () => { storageMock.setup((x) => x.getItem(storage.createFavoritesSettingItemKey("a", "b"))).returns(() => `["abc", "def"]`).verifiable(); const result = await storage.loadProperties("a", "b"); storageMock.verifyAll(); expect(result?.size).to.eq(2); expect(result).to.contain("abc"); expect(result).to.contain("def"); }); }); describe("savePropertiesOrder", () => { it("saves properties order to local storage", async () => { const orderInfos = [createRandomPropertiesOrderInfo()]; await storage.savePropertiesOrder(orderInfos, "a", "b"); storageMock.verify((x) => x.setItem(storage.createOrderSettingItemKey("a", "b"), JSON.stringify(orderInfos)), moq.Times.once()); }); }); describe("loadPropertiesOrder", () => { it("returns `undefined` and there's no cached value", async () => { storageMock.setup((x) => x.getItem(moq.It.isAny())).returns(() => null); const result = await storage.loadPropertiesOrder("a", "b"); expect(result).to.be.undefined; }); it("loads from cache and there's cached value", async () => { const orderInfos = [createRandomPropertiesOrderInfo()]; storageMock.setup((x) => x.getItem(storage.createOrderSettingItemKey("a", "b"))).returns(() => JSON.stringify(orderInfos)).verifiable(); const result = await storage.loadPropertiesOrder("a", "b"); storageMock.verifyAll(); expect(result).to.deep.eq(orderInfos); }); }); }); const createRandomPropertiesOrderInfo = () => ({ parentClassName: "parent.class.name", name: "full.property.name", priority: 9999, orderedTimestamp: new Date(), }); describe("createFavoritePropertiesStorage", () => { afterEach(() => { sinon.restore(); }); it("creates noop storage", () => { const result = createFavoritePropertiesStorage(DefaultFavoritePropertiesStorageTypes.Noop); expect(result).to.be.instanceOf(NoopFavoritePropertiesStorage); }); it("creates browser local storage", () => { sinon.stub(window, "localStorage").get(() => moq.Mock.ofType<Storage>().object); const result = createFavoritePropertiesStorage(DefaultFavoritePropertiesStorageTypes.BrowserLocalStorage); expect(result).to.be.instanceOf(BrowserLocalFavoritePropertiesStorage); }); it("creates user settings service storage", () => { const result = createFavoritePropertiesStorage(DefaultFavoritePropertiesStorageTypes.UserSettingsServiceStorage); expect(result).to.be.instanceOf(OfflineCachingFavoritePropertiesStorage); expect((result as OfflineCachingFavoritePropertiesStorage).impl).to.be.instanceOf(IModelAppFavoritePropertiesStorage); }); });
the_stack
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef, ViewChild } from '@angular/core'; import { OverlayContainer } from '@angular/cdk/overlay'; import { GUIGlobal } from '../../providers/GUIGlobal'; import { MatGridList, MatGridTile } from '@angular/material'; import { NbTabsetComponent } from '@nebular/theme/components/tabset/tabset.component'; import { NbSelectComponent } from '@nebular/theme/components/select/select.component'; import { NbDialogService } from '@nebular/theme'; import { ColorPickerModule } from 'ngx-color-picker'; import { ngfModule, ngf } from "angular-file"; import { GUITooltip } from './guiTooltip/guiTooltip.component'; import { ProgressWindow } from './progressWindow/progressWindow.component'; import { DialogWindow } from './dialogWindow/dialogWindow.component'; import { ErrorDetailsWindow } from './errorDetailsWindow/errorDetailsWindow.component'; import { ConfirmationWindow } from './confirmationWindow/confirmationWindow.component'; import { TextInputWindow } from './textInputWindow/textInputWindow.component'; @Component({ selector: 'app-generator', styleUrls: ['./generator.component.scss'], templateUrl: './generator.component.html', changeDetection: ChangeDetectionStrategy.OnPush }) export class GeneratorComponent implements OnInit { tooltipComponent = GUITooltip; @ViewChild('refTabSet') tabSet: NbTabsetComponent; @ViewChild('refTabFooter') tabSetFooter: NbTabsetComponent; activeTab: string = ""; activeFooterTab: string = ""; settingsLocked: boolean = false; //Busy Spinners generatorBusy: boolean = true; settingsBusy: boolean = false; settingsBusySaveOnly: boolean = true; //Local (non persistent) Variables seedString: string = ""; generateSeedButtonEnabled: boolean = true; inputOldValue: any = null; //Used to manage input field backup/restore //Static settings generateFromSeedTabTitle: string = "Generate New Seed"; generateFromFileTabTitle: string = "Generate From Patch File"; repatchCosmeticsCheckboxText: string = "Override Original Cosmetics"; repatchCosmeticsCheckboxTooltipPatch: string = "Replaces the cosmetic and sound settings generated in the patch file<br>with those selected on this page."; repatchCosmeticsCheckboxTooltipSeedPageWeb: string = "Replaces the cosmetic and sound settings generated in the seed<br>with those selected on this page."; constructor(private overlayContainer: OverlayContainer, private cd: ChangeDetectorRef, public global: GUIGlobal, private dialogService: NbDialogService) { } ngOnInit() { if ((<any>window).apiTestMode) { console.log("Test mode is active!"); } //Refresh/render GUI on startup if ready or wait until ready event is fired if (this.global.getGlobalVar("appReady")) { this.generatorReady(); } else { let eventSub = this.global.globalEmitter.subscribe(eventObj => { if (eventObj.name == "init_finished") { console.log("Init finished event"); this.generatorReady(); eventSub.unsubscribe(); } }); } } generatorReady() { this.generatorBusy = false; //Set active tab on boot this.activeTab = this.global.getGlobalVar('generatorSettingsArray')[0].text; //Set active footer tab on boot if (this.global.getGlobalVar('appType') == 'generator') { this.activeFooterTab = this.generateFromSeedTabTitle; this.global.generator_settingsMap["generate_from_file"] = false; } else { this.activeFooterTab = this.generateFromFileTabTitle; this.global.generator_settingsMap["generate_from_file"] = true; } this.recheckAllSettings(); this.cd.markForCheck(); this.cd.detectChanges(); this.runEventListeners(); //Electron only: Ensure settings string is up-to-date on app launch if (this.global.getGlobalVar('electronAvailable')) this.getSettingsString(); else //Web only: Check if we should auto import settings/presets from a prior version this.checkAutoImportSettings(); } runEventListeners() { //Subscribe to event listeners after initial rendering has concluded setTimeout(() => { this.tabSet.changeTab.subscribe(eventObj => { this.activeTab = eventObj.tabTitle; }); this.tabSetFooter.changeTab.subscribe(eventObj => { this.activeFooterTab = eventObj.tabTitle; }); this.global.globalEmitter.subscribe(eventObj => { if (eventObj.name == "refresh_gui") { this.cd.markForCheck(); this.cd.detectChanges(); } else if (eventObj.name == "dialog_error") { this.dialogService.open(DialogWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Error", dialogMessage: eventObj.message } }); } }); }, 0); } getTabList(footer: boolean) { let filteredTabList = []; this.global.getGlobalVar('generatorSettingsArray').forEach(tab => { if (!footer) { if (!("footer" in tab) || !tab.footer) filteredTabList.push(tab); } else { if ("footer" in tab && tab.footer) filteredTabList.push(tab); } }); return filteredTabList; } generateSeed(fromPatchFile: boolean = false, webRaceSeed: boolean = false, goalHintsConfirmed: boolean = false) { this.generateSeedButtonEnabled = false; this.seedString = this.seedString.trim().replace(/[^a-zA-Z0-9_-]/g, ''); //console.log("fromPatchFile:", fromPatchFile); //console.log(this.global.generator_settingsMap); //console.log(this.global.generator_customColorMap); //Delay the generation if settings are currently locked to avoid race conditions. //Do this here so the goal hint confirmation dialog can be defined once for //Electron and Web if (this.global.getGlobalVar('electronAvailable')) { if (this.settingsLocked) { setTimeout(() => { this.generateSeed(fromPatchFile, webRaceSeed); }, 50); return; } } let goalErrorText = "The selected hint distribution includes the Goal hint type. This can drastically increase generation time for large multiworld seeds. Continue?"; let goalDistros = this.global.getGlobalVar('generatorGoalDistros'); if (!goalHintsConfirmed && goalDistros.indexOf(this.global.generator_settingsMap["hint_dist"]) > -1 && this.global.generator_settingsMap["world_count"] > 5) { this.dialogService.open(ConfirmationWindow, { autoFocus: true, closeOnBackdropClick: false, closeOnEsc: false, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Goal Hint Warning", dialogMessage: goalErrorText } }).onClose.subscribe(confirmed => { //User acknowledged increased generation time for multiworld seeds with goal hints if (confirmed) { this.generateSeed(fromPatchFile, webRaceSeed, true); } }); this.generateSeedButtonEnabled = true; this.cd.markForCheck(); this.cd.detectChanges(); return; } if (this.global.getGlobalVar('electronAvailable')) { //Electron //Hack: Fix Generation Count being None occasionally if (!this.global.generator_settingsMap["count"] || this.global.generator_settingsMap["count"] < 1) this.global.generator_settingsMap["count"] = 1; //Error if no patch file was entered in fromPatchFile mode if (fromPatchFile && !this.global.generator_settingsMap['patch_file']) { this.dialogService.open(DialogWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Error", dialogMessage: "You didn't enter a patch file!" } }); this.generateSeedButtonEnabled = true; this.cd.markForCheck(); this.cd.detectChanges(); return; } //Hack: fromPatchFile forces generation count to 1 to avoid wrong count on progress window let generationCount = fromPatchFile ? 1 : this.global.generator_settingsMap["count"]; let dialogRef = this.dialogService.open(ProgressWindow, { autoFocus: true, closeOnBackdropClick: false, closeOnEsc: false, hasBackdrop: true, hasScroll: false, context: { dashboardRef: this, totalGenerationCount: generationCount } }); this.global.generateSeedElectron(dialogRef && dialogRef.componentRef && dialogRef.componentRef.instance ? dialogRef.componentRef.instance : null, fromPatchFile, fromPatchFile == false && this.seedString.length > 0 ? this.seedString : "").then(res => { console.log('[Electron] Gen Success'); this.generateSeedButtonEnabled = true; this.cd.markForCheck(); this.cd.detectChanges(); if (dialogRef && dialogRef.componentRef && dialogRef.componentRef.instance) { dialogRef.componentRef.instance.progressStatus = 1; dialogRef.componentRef.instance.progressPercentageCurrent = 100; dialogRef.componentRef.instance.progressPercentageTotal = 100; dialogRef.componentRef.instance.progressMessage = "Done. Enjoy."; dialogRef.componentRef.instance.progressErrorDetails = ""; dialogRef.componentRef.instance.refreshLayout(); } }).catch((err) => { console.log('[Electron] Gen Error'); this.generateSeedButtonEnabled = true; this.cd.markForCheck(); this.cd.detectChanges(); if (dialogRef && dialogRef.componentRef && dialogRef.componentRef.instance) { dialogRef.componentRef.instance.progressStatus = -1; dialogRef.componentRef.instance.progressPercentageCurrent = 100; dialogRef.componentRef.instance.progressPercentageTotal = 100; dialogRef.componentRef.instance.progressMessage = err.short; dialogRef.componentRef.instance.progressErrorDetails = err.short === err.long ? "" : err.long; dialogRef.componentRef.instance.refreshLayout(); } }); } else { //Web this.global.generateSeedWeb(webRaceSeed, this.seedString.length > 0 ? this.seedString : "").then(seedID => { try { //Save last seed id in browser cache localStorage.setItem("lastSeed", seedID); //Save up to 10 seed ids in a sliding array in browser cache let seedHistory = localStorage.getItem("seedHistory"); if (seedHistory == null || seedHistory.length < 1) { //First entry localStorage.setItem("seedHistory", JSON.stringify([seedID])); } else { //Update array (10 entries max) let seedHistoryArray = JSON.parse(seedHistory); if (seedHistoryArray && typeof (seedHistoryArray) == "object" && Array.isArray(seedHistoryArray)) { if (seedHistoryArray.length > 9) { seedHistoryArray.shift(); } seedHistoryArray.push(seedID); localStorage.setItem("seedHistory", JSON.stringify(seedHistoryArray)); } } } catch (e) { //Browser doesn't allow localStorage access } //Re-direct to seed (waiting) page let seedURL = (<any>window).location.protocol + "//" + (<any>window).location.host + "/seed/get?id=" + seedID; console.log('[Web] Success, will re-direct to:', seedURL); setTimeout(() => { (<any>window).location.href = seedURL; }, 250); }).catch((err) => { console.log('[Web] Gen Error:', err); if (err.status == 403) { //Rate Limited this.dialogService.open(DialogWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Error", dialogMessage: "You may only generate one seed per minute to prevent spam!" } }); } else if (err.hasOwnProperty('error_rom_in_plando')) { this.dialogService.open(ConfirmationWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Your ROM doesn't belong here!", dialogMessage: err.error_rom_in_plando } }).onClose.subscribe(confirmed => { if (confirmed) { if (err.type == "distribution_file") { this.global.generator_settingsMap["enable_distribution_file"] = false; this.global.generator_settingsMap["distribution_file"] = ""; let setting = this.global.findSettingByName("enable_distribution_file"); this.checkVisibility(false, setting, this.findOption(setting.options, false)); } else if (err.type == "cosmetic_file") { this.global.generator_settingsMap["enable_cosmetic_file"] = false; this.global.generator_settingsMap["cosmetic_file"] = ""; let setting = this.global.findSettingByName("enable_cosmetic_file"); this.checkVisibility(false, setting, this.findOption(setting.options, false)); } this.generateSeed(fromPatchFile, webRaceSeed); } }); } else if (err.hasOwnProperty('error_spoiler_log_disabled')) { this.dialogService.open(ConfirmationWindow, { autoFocus: true, closeOnBackdropClick: false, closeOnEsc: false, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Spoiler Log Warning", dialogMessage: err.error_spoiler_log_disabled } }).onClose.subscribe(confirmed => { //Enable spoiler log if user accepts and save changed setting if (confirmed) { this.global.generator_settingsMap["create_spoiler"] = true; this.afterSettingChange(); } this.generateSeed(fromPatchFile, webRaceSeed); }); } else { this.dialogService.open(DialogWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Error", dialogMessage: err.error && typeof (err.error) == "string" ? err.error : err.message } }); } this.generateSeedButtonEnabled = true; this.cd.markForCheck(); this.cd.detectChanges(); }); } } async cancelGeneration() { //Electron only return await this.global.cancelGenerateSeedElectron(); } patchROM() { //Web only this.generateSeedButtonEnabled = false; console.log("Patch ROM"); this.global.patchROMWeb().then(() => { //No actual callback, just deactivate button for 1 second setTimeout(() => { this.generateSeedButtonEnabled = true; this.cd.markForCheck(); this.cd.detectChanges(); }, 1000); }).catch ((err) => { console.log('[Web] Patching Error:', err); if (err.hasOwnProperty('error_rom_in_plando')) { this.dialogService.open(ConfirmationWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Your ROM doesn't belong here!", dialogMessage: err.error_rom_in_plando } }).onClose.subscribe(confirmed => { if (confirmed) { if (err.type == "cosmetic_file") { this.global.generator_settingsMap["enable_cosmetic_file"] = false; this.global.generator_settingsMap["cosmetic_file"] = ""; let setting = this.global.findSettingByName("enable_cosmetic_file"); this.checkVisibility(false, setting, this.findOption(setting.options, false)); } this.patchROM(); } }); } else { this.dialogService.open(DialogWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Error", dialogMessage: err.error && typeof (err.error) == "string" ? err.error : err.message } }); } this.generateSeedButtonEnabled = true; this.cd.markForCheck(); this.cd.detectChanges(); }); } copySettingsString() { this.global.copyToClipboard(this.global.generator_settingsMap["settings_string"]); } getSettingsString() { this.settingsLocked = true; this.global.convertSettingsToString().then(res => { //console.log("String got:", res); this.global.generator_settingsMap["settings_string"] = res; this.global.saveCurrentSettingsToFile(); this.settingsLocked = false; if (this.settingsBusy) { //Execute delayed task this.settingsBusy = false; this.afterSettingChange(this.settingsBusySaveOnly); this.settingsBusySaveOnly = true; } this.cd.markForCheck(); this.cd.detectChanges(); }).catch((err) => { this.settingsLocked = false; if (this.settingsBusy) { //Execute delayed task this.settingsBusy = false; this.afterSettingChange(this.settingsBusySaveOnly); this.settingsBusySaveOnly = true; } this.cd.markForCheck(); this.cd.detectChanges(); this.dialogService.open(ErrorDetailsWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { errorMessage: err } }); }); } importSettingsString() { this.generatorBusy = true; this.global.convertStringToSettings(this.global.generator_settingsMap["settings_string"]).then(res => { //console.log(res); this.global.applySettingsObject(res); this.global.saveCurrentSettingsToFile(); this.recheckAllSettings("", false, true); this.generatorBusy = false; this.cd.markForCheck(); this.cd.detectChanges(); }).catch((err) => { this.generatorBusy = false; this.cd.markForCheck(); this.cd.detectChanges(); this.dialogService.open(DialogWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Error", dialogMessage: "The entered settings string seems to be invalid!" } }); }); } getPresetArray() { if (typeof (this.global.generator_presets) == "object") return Object.keys(this.global.generator_presets); else return []; } loadPreset() { let targetPreset = this.global.generator_presets[this.global.generator_settingsMap["presets"]]; if (targetPreset) { if (("isNewPreset" in targetPreset) && targetPreset.isNewPreset == true) { this.dialogService.open(DialogWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Warning", dialogMessage: "You can not load this preset!" } }); } else { if (("isDefaultPreset" in targetPreset) && targetPreset.isDefaultPreset == true) { //RESTORE DEFAULTS this.global.applyDefaultSettings(); } else { this.global.applyDefaultSettings(); //Restore defaults first in case the user loads an old preset that misses settings this.global.applySettingsObject(this.global.generator_presets[this.global.generator_settingsMap["presets"]].settings); } this.recheckAllSettings("", false, true); this.afterSettingChange(); //console.log("Preset loaded"); } } } savePreset(refPresetSelect: NbSelectComponent<string>) { let targetPreset = this.global.generator_presets[this.global.generator_settingsMap["presets"]]; if (targetPreset) { if ((("isNewPreset" in targetPreset) && targetPreset.isNewPreset == true)) { //NEW PRESET this.dialogService.open(TextInputWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Create new preset", dialogMessage: "Enter preset name:" } }).onClose.subscribe(name => { if (name && typeof (name) == "string" && name.trim().length > 0) { let trimmedName = name.trim(); if (trimmedName in this.global.generator_presets) { this.dialogService.open(DialogWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Error", dialogMessage: "A preset with this name already exists! If you wish to overwrite an existing preset, please select it from the list and hit Save instead." } }); } else { this.global.generator_presets[trimmedName] = { settings: this.global.createSettingsFileObject(false, true, !this.global.getGlobalVar('electronAvailable')) }; this.global.generator_settingsMap["presets"] = trimmedName; this.global.saveCurrentPresetsToFile(); this.cd.markForCheck(); this.cd.detectChanges(); refPresetSelect.setSelected = trimmedName; //console.log("Preset created"); } } }); } else if (("isDefaultPreset" in targetPreset) && targetPreset.isDefaultPreset == true) { //DEFAULT this.dialogService.open(DialogWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Warning", dialogMessage: "System presets can not be overwritten!" } }); } else if (("isProtectedPreset" in targetPreset) && targetPreset.isProtectedPreset == true) { //BUILT IN this.dialogService.open(DialogWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Warning", dialogMessage: "Built in presets are protected and can not be overwritten!" } }); } else { //USER PRESETS this.dialogService.open(ConfirmationWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Confirm?", dialogMessage: "Do you want to overwrite the preset '" + this.global.generator_settingsMap["presets"] + "' ?" } }).onClose.subscribe(confirmed => { if (confirmed) { this.global.generator_presets[this.global.generator_settingsMap["presets"]] = { settings: this.global.createSettingsFileObject(false, true, !this.global.getGlobalVar('electronAvailable')) }; this.global.saveCurrentPresetsToFile(); console.log("Preset overwritten"); } }); } } } deletePreset() { let targetPreset = this.global.generator_presets[this.global.generator_settingsMap["presets"]]; if (targetPreset) { if ((("isNewPreset" in targetPreset) && targetPreset.isNewPreset == true) || (("isDefaultPreset" in targetPreset) && targetPreset.isDefaultPreset == true)) { this.dialogService.open(DialogWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Warning", dialogMessage: "System presets can not be deleted!" } }); } else if (("isProtectedPreset" in targetPreset) && targetPreset.isProtectedPreset == true) { this.dialogService.open(DialogWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Warning", dialogMessage: "Built in presets are protected and can not be deleted!" } }); } else { this.dialogService.open(ConfirmationWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Confirm?", dialogMessage: "Do you really want to delete the preset '" + this.global.generator_settingsMap["presets"] + "' ?" } }).onClose.subscribe(confirmed => { if (confirmed) { delete this.global.generator_presets[this.global.generator_settingsMap["presets"]]; this.global.generator_settingsMap["presets"] = "[New Preset]"; this.global.saveCurrentPresetsToFile(); this.cd.markForCheck(); this.cd.detectChanges(); //console.log("Preset deleted"); } }); } } } openOutputDir() { //Electron only var path = ""; if (!this.global.generator_settingsMap["output_dir"] || this.global.generator_settingsMap["output_dir"].length < 1) path = "Output"; else path = this.global.generator_settingsMap["output_dir"]; this.global.createAndOpenPath(path).then(() => { console.log("Output dir opened"); }).catch(err => { console.error("Error:", err); if (err.message.includes("no such file or directory")) { this.dialogService.open(DialogWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Error", dialogMessage: "The specified output directory does not exist!" } }); } else { this.dialogService.open(DialogWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Error", dialogMessage: err } }); } }); } openPythonDir() { //Electron only this.global.createAndOpenPath("").then(() => { console.log("Python dir opened"); }).catch(err => { console.error("Error:", err); this.dialogService.open(DialogWindow, { autoFocus: true, closeOnBackdropClick: true, closeOnEsc: true, hasBackdrop: true, hasScroll: false, context: { dialogHeader: "Error", dialogMessage: err } }); }); } browseForFile(setting: any) { //Electron only this.global.browseForFile(setting.file_types).then(res => { this.global.generator_settingsMap[setting.name] = res; this.cd.markForCheck(); this.afterSettingChange(); }).catch(err => { console.log(err); }); } browseForDirectory(setting: any) { //Electron only this.global.browseForDirectory().then(res => { this.global.generator_settingsMap[setting.name] = res; this.cd.markForCheck(); this.afterSettingChange(); }).catch(err => { console.log(err); }); } browseForPatchFile() { //Electron only this.global.browseForFile([{ name: 'Patch File Archive', 'extensions': ['zpfz', 'zpf'] }, { 'name': 'All Files', 'extensions': ['*'] }]).then(res => { this.global.generator_settingsMap['patch_file'] = res; this.cd.markForCheck(); this.afterSettingChange(true); }).catch(err => { console.log(err); }); } changeFooterTabSelection(event) { let title = ""; let value = false; if (event) { title = event.tabTitle; this.activeFooterTab = title; } else { title = this.activeFooterTab; } if (title === this.generateFromFileTabTitle) { value = true; } this.global.generator_settingsMap['generate_from_file'] = value; let setting = this.global.findSettingByName("generate_from_file"); this.checkVisibility(value, setting, this.findOption(setting.options, value)); } updateCosmeticsCheckboxChange(value) { let setting = this.global.findSettingByName("repatch_cosmetics"); this.checkVisibility(value, setting, this.findOption(setting.options, value)); } calculateRowHeight(listRef: MatGridList, tab: any) { let columnCount = this.verifyColumnCount(listRef.cols); let absoluteRowCount = 0; let absoluteRowIndex = 0; let gutterPercentage = 0; for (let i = 0; i < tab.sections.length; i++) { let section = tab.sections[i]; absoluteRowIndex += this.getColumnWidth(null, tab.sections, i, tab.sections.length, section['col_span'] ? section['col_span'] : 0, columnCount); if (absoluteRowIndex >= columnCount) { absoluteRowIndex = 0; let columnRowCount = this.getColumnHeight(null, section, columnCount); absoluteRowCount += columnRowCount; gutterPercentage += (columnRowCount * 0.5); } } let heightPerRow = (100 - gutterPercentage) / absoluteRowCount; return heightPerRow + "%"; } getColumnCount(tileRef: MatGridTile) { return this.verifyColumnCount(tileRef._gridList.cols); } verifyColumnCount(count: number) { if (count != 1 && count != 2 && count != 12) { return 1; } return count; } getColumnWidth(tileRef: MatGridTile, sections: any, index: number, length: number, colSpan: number = 0, columnCount: number = -1) { if (columnCount == -1) { columnCount = this.getColumnCount(tileRef); } //col_span override if (colSpan > 0) if (columnCount == 12) //Treat 12x1 column setup as 4x1 internally return 4 >= colSpan ? colSpan * 3 : 12; else return columnCount >= colSpan ? colSpan : columnCount; //Account for col_span override sections in a special way let searchIndex = 0; let sectionIndex = index; sections.forEach(section => { if (section.col_span > 0) { let sectionsToAdd; if (columnCount == 12) //Treat 12x1 column setup as 4x1 internally sectionsToAdd = (4 >= section.col_span ? section.col_span : 4) - 1; else sectionsToAdd = (columnCount >= section.col_span ? section.col_span : columnCount) - 1; length += sectionsToAdd; if (searchIndex < sectionIndex) index += sectionsToAdd; } searchIndex++; }); if (columnCount == 2 && length % 2 != 0 && index == length - 1) { //If an odd number of cols exist with 2 cols length, make last col take the entire row size return 2; } else if (columnCount == 3 && length % 3 != 0 && index == length - 1) { //Make final column size 3 if it is on its row alone. If there are 2 columns, make the last column size 2 if (index % 3 == 0) return 3; else return 2; } else if (columnCount == 4 && length % 4 != 0) { //Make final column size 4 if it is on its row alone. If there are 2 columns, make both size 2. Else just make the final one size 2 if (index == length - 1) { if (index % 4 == 0) return 4; else if (index % 4 == 1) return 2; else return 2; } else if (index + 1 == length - 1) { if (index % 4 == 0) return 2; } } else if (columnCount == 12) { //We limit max sections per line at 4 in a 12x1 column setup if (index == length - 1) { if (index % 4 == 0) return 12; else if (index % 4 == 1) return 6; else if (index % 4 == 2) return 4; } else if (index + 1 == length - 1) { if (index % 4 == 0) return 6; else if (index % 4 == 1) return 4; } else if (index + 2 == length - 1) { if (index % 4 == 0) return 4; } return 3; } return 1; } getColumnHeight(tileRef: MatGridTile, section: any, columnCount: number = -1) { if (columnCount == -1) { columnCount = this.getColumnCount(tileRef); } let spanIndex = 0; switch (columnCount) { case 2: spanIndex = 1; break; case 12: spanIndex = 2; break; } return section.row_span[spanIndex]; } findOption(options: any, optionName: any) { return options.find(option => { return option.name == optionName }); } getVariableType(variable: any) { return typeof (variable); } getNextVisibleSetting(settings: any, startingIndex: number) { if (settings.length > startingIndex) { for (let i = startingIndex; i < settings.length; i++) { let setting = settings[i]; if (this.global.generator_settingsVisibilityMap[setting.name] || !setting.hide_when_disabled) return setting; } } return null; } checkVisibility(newValue: any, setting: any, option: any = null, refColorPicker: HTMLInputElement = null, disableOnly: boolean = false, noValueChange: boolean = false) { if (!disableOnly && !noValueChange) this.afterSettingChange(); //Array of settings that should have its visibility altered var targetSettings = []; if (setting["type"] === "Checkbutton" || setting["type"] === "Radiobutton" || setting["type"] === "Combobox" || setting["type"] === "SearchBox") { let value = (typeof (newValue) == "object") && ("value" in newValue) ? newValue.value : newValue; //Open color picker if custom color is selected if (refColorPicker && value == "Custom Color") { if (this.global.generator_customColorMap[setting.name].length < 1) this.global.generator_customColorMap[setting.name] = "#ffffff"; refColorPicker.click(); } if (setting["type"] === "SearchBox") { //Special handling for type "SearchBox" let optionsSelected = value && typeof (value) == "object" && Array.isArray(value) && value.length > 0; //First build a complete list consisting of every option that hasn't been selected yet with a true value setting.options.forEach(optionToAdd => { //Ensure option isn't selected before adding it if (optionsSelected) { let alreadySelected = value.find(selectedItem => selectedItem.name == optionToAdd.name); if (alreadySelected) return; } targetSettings.push({ target: optionToAdd, value: true }); }); //Push every selected option last with a false value if (optionsSelected) { value.forEach(selectedItem => { targetSettings.push({ target: selectedItem, value: false }); }); } } else { //Every other settings type //Build list of options setting.options.forEach(optionToAdd => { if (optionToAdd.name === option.name) //Add currently selected item last for priority return; targetSettings.push({ target: optionToAdd, value: optionToAdd.name != value }); }); targetSettings.push({ target: option, value: false }); //Selected setting uses false as it can disable settings now } } //Handle activations/deactivations this.toggleVisibility(targetSettings, disableOnly, setting.name); } toggleVisibility(targetSettings: any, disableOnly: boolean, skipSetting: string = "") { var triggeredChange = false; targetSettings.forEach(setting => { let targetSetting = setting.target; let targetValue = setting.value; if (disableOnly && targetValue == true) return; if (this.executeVisibilityForSetting(targetSetting, targetValue)) triggeredChange = true; }); //Re-run function with every single setting to ensure integrity (nothing gets re-activated when it shouldn't) if (triggeredChange) { this.recheckAllSettings(skipSetting); } } executeVisibilityForSetting(targetSetting: any, targetValue: boolean) { var triggeredChange = false; if ("controls_visibility_tab" in targetSetting) { //console.log(targetSetting, setting); targetSetting["controls_visibility_tab"].split(",").forEach(tab => { //Ignore tabs that don't exist in this specific app if (!(tab in this.global.generator_tabsVisibilityMap)) return; this.global.generator_tabsVisibilityMap[tab] = targetValue; //Kick user out of active tab and go back to root if it gets disabled here if (!targetValue && this.global.getGlobalVar("generatorSettingsObj")) { if (this.activeTab == this.global.getGlobalVar("generatorSettingsObj")[tab].text) { //console.log("Kick user out of tab"); this.tabSet.selectTab(this.tabSet.tabs.first); } } }); } if ("controls_visibility_section" in targetSetting) { targetSetting["controls_visibility_section"].split(",").forEach(section => { let targetSection = null; //Find section for (let i = 0; i < this.global.getGlobalVar('generatorSettingsArray').length; i++) { let tab = this.global.getGlobalVar('generatorSettingsArray')[i]; for (let n = 0; n < tab.sections.length; n++) { if (tab.sections[n].name === section) { targetSection = tab.sections[n]; break; } } if (targetSection) break; } //Disable/Enable entire section if (targetSection) { targetSection.settings.forEach(setting => { //Ignore settings that don't exist in this specific app if (!(setting.name in this.global.generator_settingsVisibilityMap)) return; let enabledChildren = false; //If a setting gets disabled, re-enable all the settings that this setting caused to deactivate. The later full check will fix any potential issues if (targetValue == false && this.global.generator_settingsVisibilityMap[setting.name] == true) { enabledChildren = this.clearDeactivationsOfSetting(setting); } if ((targetValue == true && this.global.generator_settingsVisibilityMap[setting.name] == false) || (enabledChildren)) //Only trigger change if a (sub) setting gets re-enabled triggeredChange = true; this.global.generator_settingsVisibilityMap[setting.name] = targetValue; }); } }); } if ("controls_visibility_setting" in targetSetting) { targetSetting["controls_visibility_setting"].split(",").forEach(setting => { //Ignore settings that don't exist in this specific app if (!(setting in this.global.generator_settingsVisibilityMap)) return; let enabledChildren = false; if (targetValue == false && this.global.generator_settingsVisibilityMap[setting] == true) { enabledChildren = this.clearDeactivationsOfSetting(this.global.findSettingByName(setting)); } if ((targetValue == true && this.global.generator_settingsVisibilityMap[setting] == false) || (enabledChildren)) //Only trigger change if a (sub) setting gets re-enabled triggeredChange = true; this.global.generator_settingsVisibilityMap[setting] = targetValue; }); } return triggeredChange; } clearDeactivationsOfSetting(setting: any) { let enabledChildren = false; if (setting["type"] === "Checkbutton" || setting["type"] === "Radiobutton" || setting["type"] === "Combobox" || setting["type"] === "SearchBox") { if (setting["type"] === "SearchBox") { //Special handling for type "SearchBox" //Get every option currently added to the list if (this.global.generator_settingsMap[setting.name] && this.global.generator_settingsMap[setting.name].length > 0) { this.global.generator_settingsMap[setting.name].forEach(selectedItem => { if (this.executeVisibilityForSetting(selectedItem, true)) enabledChildren = true; }); } } else { //Every other settings type //Get currently selected option let currentOption = this.findOption(setting.options, this.global.generator_settingsMap[setting.name]); if (currentOption) { if (this.executeVisibilityForSetting(currentOption, true)) enabledChildren = true; } } } return enabledChildren; } recheckAllSettings(skipSetting: string = "", disableOnly: boolean = true, noValueChange: boolean = false) { this.global.getGlobalVar('generatorSettingsArray').forEach(tab => tab.sections.forEach(section => section.settings.forEach(checkSetting => { if (skipSetting && checkSetting.name === skipSetting || !this.global.generator_settingsVisibilityMap[checkSetting.name]) //Disabled settings can not alter visibility anymore return; if (checkSetting["type"] === "Checkbutton" || checkSetting["type"] === "Radiobutton" || checkSetting["type"] === "Combobox" || checkSetting["type"] === "SearchBox") { if (checkSetting["type"] === "SearchBox") { //Special handling for type "SearchBox" //Call checkVisibility right away which will perform a full list check this.checkVisibility({ value: this.global.generator_settingsMap[checkSetting.name] }, checkSetting, null, null, disableOnly, noValueChange); } else { //Every other settings type let targetOption = checkSetting.options.find(option => { if (option.name === this.global.generator_settingsMap[checkSetting.name]) return true; return false; }); if (targetOption) { this.checkVisibility({ value: this.global.generator_settingsMap[checkSetting.name] }, checkSetting, targetOption, null, disableOnly, noValueChange); } } } }))); } revertToPriorValue(settingName: string, forceChangeDetection: boolean, forcePriorValue: any = null) { let priorValue = forcePriorValue != null ? forcePriorValue : this.global.generator_settingsMap[settingName]; setTimeout(() => { this.global.generator_settingsMap[settingName] = priorValue; if (forceChangeDetection) this.cd.markForCheck(); }, 0); } inputFocusIn(settingName: string) { //Save current value on entering any input field this.inputOldValue = this.global.generator_settingsMap[settingName]; } inputFocusOut(settingName: string, saveOnly: boolean, forceNewValue: any = null) { let newValue = forceNewValue != null ? forceNewValue : this.global.generator_settingsMap[settingName]; //Only update if the value actually changed if (newValue != this.inputOldValue) { setTimeout(() => { this.global.generator_settingsMap[settingName] = newValue; this.afterSettingChange(saveOnly); }, 0); } } numberInputFocusOut(setting: object, forceAdjust: boolean) { let newValue = this.global.generator_settingsMap[setting["name"]]; let settingName = setting["name"]; //Existence check if (!newValue || newValue.length == 0) { if (forceAdjust) this.revertToPriorValue(settingName, true, this.inputOldValue); return; } //Number check if (Number(parseInt(newValue)) != newValue) { if (forceAdjust) this.revertToPriorValue(settingName, true, this.inputOldValue); return; } //Min/Max check let settingMin: number = setting["min"]; let settingMax: number = setting["max"]; if (("min" in setting) && newValue < settingMin) { if (forceAdjust) { setTimeout(() => { this.global.generator_settingsMap[setting["name"]] = settingMin; this.cd.markForCheck(); this.afterSettingChange(); }, 0); } } else if (("max" in setting) && newValue > settingMax) { if (forceAdjust) { setTimeout(() => { this.global.generator_settingsMap[setting["name"]] = settingMax; this.cd.markForCheck(); this.afterSettingChange(); }, 0); } } else { //Update setting with new number value this.inputFocusOut(settingName, false, parseInt(newValue)); } } afterSettingChange(saveOnly: boolean = false) { if (this.global.getGlobalVar('electronAvailable')) { //Electron //Show waiting spinner if another settings action is currently running and delay the task if (this.settingsLocked) { this.settingsBusy = true; if (!saveOnly) this.settingsBusySaveOnly = false; this.cd.markForCheck(); this.cd.detectChanges(); return; } this.settingsLocked = true; setTimeout(() => { //console.log(this.global.generator_settingsMap); //console.log(this.global.generator_customColorMap); if (saveOnly) { this.global.saveCurrentSettingsToFile(); this.settingsLocked = false; if (this.settingsBusy) { //Execute delayed task this.settingsBusy = false; this.afterSettingChange(this.settingsBusySaveOnly); this.settingsBusySaveOnly = true; } this.cd.markForCheck(); this.cd.detectChanges(); } else { this.getSettingsString(); } }, 0); } else { //Web setTimeout(() => { //console.log(this.global.generator_settingsMap); //console.log(this.global.generator_customColorMap); this.global.saveCurrentSettingsToFile(); this.settingsLocked = false; this.cd.markForCheck(); this.cd.detectChanges(); }, 0); } } checkAutoImportSettings() { //Web only let userSettings = null; let isGenerator = this.global.getGlobalVar("appType") == "generator"; let storageSettingsKey = isGenerator ? "generatorSettings_" : "patcherSettings_"; let currentVersion = this.global.getGlobalVar("webSourceVersion"); let currentBranch = currentVersion.startsWith("dev") && currentVersion.includes("_") ? currentVersion.split("_")[0] : "master"; try { userSettings = localStorage.getItem(storageSettingsKey + currentVersion); } catch (err) { console.error("Local storage not available"); return; } if (!userSettings) { //Check if we have a prior version settings map and find the closest one from the same branch (master/dev are compatible with each other) if (localStorage.length) { let closestFoundVersion = ""; for (let i = 0; i < localStorage.length; i++) { let key = localStorage.key(i); if (key && key.startsWith(storageSettingsKey)) { let version = key.replace(storageSettingsKey, ""); let branch = version.startsWith("dev") && version.includes("_") ? version.split("_")[0] : "master"; if ((branch === currentBranch) || (branch === "master" && currentBranch === "dev") || (branch === "dev" && currentBranch === "master")) { if (this.global.isVersionNewer(version, currentVersion) == false) if (!closestFoundVersion || this.global.isVersionNewer(version, closestFoundVersion)) closestFoundVersion = version; } } } if (closestFoundVersion) { //Import settings let importedSettings = JSON.parse(localStorage.getItem(storageSettingsKey + closestFoundVersion)); this.global.applySettingsObject(importedSettings); this.recheckAllSettings("", false, true); console.log("Imported settings from prior version:", closestFoundVersion, importedSettings); //Import presets from the found version in generator mode (if present and current version has none) if (isGenerator) { let userPresets = localStorage.getItem("generatorPresets_" + currentVersion); if (!userPresets) { let importedPresets = localStorage.getItem("generatorPresets_" + closestFoundVersion); if (importedPresets && importedPresets.length > 0) { importedPresets = JSON.parse(importedPresets); //Only import user presets that don't exist yet globally Object.keys(importedPresets).forEach(presetName => { if (!(presetName in this.global.generator_presets)) this.global.generator_presets[presetName] = { settings: importedPresets[presetName] }; }); this.global.saveCurrentPresetsToFile(); console.log("Imported presets from prior version:", closestFoundVersion, importedPresets); } } } //Refresh GUI this.afterSettingChange(); } } } } }
the_stack
import { Post } from 'src/core/domain/posts' import { SocialError } from 'src/core/domain/common' import { Map, fromJS } from 'immutable' // - Import utility components import moment from 'moment/moment' // - Import action types import { PostActionType } from 'constants/postActionType' // - Import actions import * as globalActions from 'store/actions/globalActions' import { IPostService } from 'src/core/services/posts' import { SocialProviderTypes } from 'src/core/socialProviderTypes' import { provider } from 'src/socialEngine' /** * Get service providers */ const postService: IPostService = provider.get<IPostService>(SocialProviderTypes.PostService) /* _____________ CRUD DB _____________ */ /** * Add a normal post */ export let dbAddPost = (newPost: Post, callBack: Function) => { return (dispatch: any, getState: Function) => { const state: Map<string, any> = getState() let uid: string = state.getIn(['authorize', 'uid']) let post: Post = { postTypeId: 0, creationDate: moment().unix(), deleteDate: 0, score: 0, viewCount: 0, body: newPost.body, ownerUserId: uid, ownerDisplayName: newPost.ownerDisplayName, ownerAvatar: newPost.ownerAvatar, lastEditDate: 0, tags: newPost.tags || [], commentCounter: 0, comments: {}, votes: {}, image: '', imageFullPath: '', video: '', disableComments: newPost.disableComments, disableSharing: newPost.disableSharing, deleted: false } return postService.addPost(post).then((postKey: string) => { dispatch(addPost(uid, { ...post, id: postKey })) callBack() }) .catch((error: SocialError) => dispatch(globalActions.showMessage(error.message))) } } /** * Add a post with image */ export const dbAddImagePost = (newPost: Post, callBack: Function) => { return (dispatch: any, getState: Function) => { dispatch(globalActions.showTopLoading()) const state: Map<string, any> = getState() let uid: string = state.getIn(['authorize', 'uid']) let post: Post = { postTypeId: 1, creationDate: moment().unix(), deleteDate: 0, score: 0, viewCount: 0, body: newPost.body, ownerUserId: uid, ownerDisplayName: newPost.ownerDisplayName, ownerAvatar: newPost.ownerAvatar, lastEditDate: 0, tags: newPost.tags || [], commentCounter: 0, image: newPost.image || '', imageFullPath: newPost.imageFullPath || '', video: '', disableComments: newPost.disableComments ? newPost.disableComments : false, disableSharing: newPost.disableSharing ? newPost.disableSharing : false, deleted: false } return postService.addPost(post).then((postKey: string) => { dispatch(addPost(uid, { ...post, id: postKey })) callBack() dispatch(globalActions.hideTopLoading()) }) .catch((error: SocialError) => dispatch(globalActions.showMessage(error.message))) } } /** * Update a post from database */ export const dbUpdatePost = (updatedPost: Map<string, any>, callBack: Function) => { return (dispatch: any, getState: Function) => { dispatch(globalActions.showTopLoading()) return postService.updatePost(updatedPost.toJS()).then(() => { dispatch(updatePost(updatedPost)) callBack() dispatch(globalActions.hideTopLoading()) }) .catch((error: SocialError) => { dispatch(globalActions.showMessage(error.message)) dispatch(globalActions.hideTopLoading()) }) } } /** * Delete a post from database * @param {string} id is post identifier */ export const dbDeletePost = (id: string) => { return (dispatch: any, getState: Function) => { dispatch(globalActions.showTopLoading()) const state: Map<string, any> = getState() // Get current user id let uid: string = state.getIn(['authorize', 'uid']) return postService.deletePost(id).then(() => { dispatch(deletePost(uid, id)) dispatch(globalActions.hideTopLoading()) }) .catch((error: SocialError) => { dispatch(globalActions.showMessage(error.message)) dispatch(globalActions.hideTopLoading()) }) } } /** * Get all user posts from data base */ export const dbGetPosts = (page: number = 0, limit: number = 10) => { return (dispatch: any, getState: Function) => { const state: Map<string, any> = getState() const stream: Map<string, any> = state.getIn(['post', 'stream']) const lastPageRequest = stream.get('lastPageRequest') const lastPostId = stream.get('lastPostId') let uid: string = state.getIn(['authorize', 'uid']) if (uid && lastPageRequest !== page) { return postService.getPosts(uid, lastPostId, page, limit).then((result) => { if (!result.posts || !(result.posts.length > 0)) { return dispatch(notMoreDataStream()) } // Store last post Id dispatch(lastPostStream(result.newLastPostId)) let parsedData: Map<string, Map<string, any>> = Map({}) result.posts.forEach((post) => { const postId = Object.keys(post)[0] const postData = post[postId] const ownerId = postData.ownerUserId! parsedData = parsedData.setIn([ownerId, postId], fromJS(postData)) }) dispatch(addPosts(parsedData)) }) .catch((error: SocialError) => { dispatch(globalActions.showMessage(error.message)) }) } } } /** * Get all user posts from data base */ export const dbGetPostsByUserId = (userId: string, page: number = 0, limit: number = 10) => { return (dispatch: any, getState: Function) => { const state: Map<string, any> = getState() const { profile } = state.get('post') const lastPageRequest = state.getIn(['post', 'profile', userId, 'lastPageRequest'], -1) const lastPostId = state.getIn(['post', 'profile', userId, 'lastPostId'], '') let uid: string = state.getIn(['authorize', 'uid']) if (uid && lastPageRequest !== page) { return postService.getPostsByUserId(userId, lastPostId, page, limit).then((result) => { if (!result.posts || !(result.posts.length > 0)) { return dispatch(notMoreDataProfile(userId)) } // Store last post Id dispatch(lastPostProfile(userId, result.newLastPostId)) let parsedData: Map<string, Map<string, any>> = Map({}) result.posts.forEach((post) => { const postId = Object.keys(post)[0] const postData = post[postId] const ownerId = postData.ownerUserId! parsedData = parsedData.setIn([ownerId, postId], fromJS(postData)) }) dispatch(addPosts(parsedData)) }) .catch((error: SocialError) => { dispatch(globalActions.showMessage(error.message)) }) } } } /** * Get all user posts from data base */ export const dbGetPostById = (uid: string, postId: string) => { return (dispatch: any, getState: Function) => { if (uid) { return postService.getPostById(postId).then((post: Post) => { dispatch(addPost(uid, post)) }) .catch((error: SocialError) => { dispatch(globalActions.showMessage(error.message)) }) } } } /* _____________ CRUD State _____________ */ /** * Add a normal post */ export const addPost = (uid: string, post: Post) => { return { type: PostActionType.ADD_POST, payload: { uid, post } } } /** * Update a post */ export const updatePost = (post: Map<string, any>) => { return { type: PostActionType.UPDATE_POST, payload: { post } } } /** * Update the comments of post */ export const updatePostComments = (comments: Map<string, any>) => { return { type: PostActionType.UPDATE_POST, payload: comments } } /** * Update the votes of post */ export const updatePostVotes = (votes: Map<string, any>) => { return { type: PostActionType.UPDATE_POST, payload: votes } } /** * Delete a post */ export const deletePost = (uid: string, id: string) => { return { type: PostActionType.DELETE_POST, payload: { uid, id } } } /** * Add a list of post */ export const addPosts = (userPosts: Map<string, Map<string, any>>) => { return { type: PostActionType.ADD_LIST_POST, payload: { userPosts } } } /** * Clea all data in post store */ export const clearAllData = () => { return { type: PostActionType.CLEAR_ALL_DATA_POST } } /** * Add a post with image */ export const addImagePost = (uid: string, post: any) => { return { type: PostActionType.ADD_IMAGE_POST, payload: { uid, post } } } /** * Set stream has more data to show */ export const hasMoreDataStream = () => { return { type: PostActionType.HAS_MORE_DATA_STREAM } } /** * Set stream has not data any more to show */ export const notMoreDataStream = () => { return { type: PostActionType.NOT_MORE_DATA_STREAM } } /** * Set last page request of stream */ export const requestPageStream = (page: number) => { return { type: PostActionType.REQUEST_PAGE_STREAM, payload: { page } } } /** * Set last post identification of stream */ export const lastPostStream = (lastPostId: string) => { return { type: PostActionType.LAST_POST_STREAM, payload: { lastPostId } } } /** * Set profile posts has more data to show */ export const hasMoreDataProfile = () => { return { type: PostActionType.HAS_MORE_DATA_PROFILE } } /** * Set profile posts has not data any more to show */ export const notMoreDataProfile = (userId: string) => { return { type: PostActionType.NOT_MORE_DATA_PROFILE, payload: { userId } } } /** * Set last page request of profile posts */ export const requestPageProfile = (userId: string, page: number) => { return { type: PostActionType.REQUEST_PAGE_PROFILE, payload: { userId, page } } } /** * Set last post identification of profile posts */ export const lastPostProfile = (userId: string, lastPostId: string) => { return { type: PostActionType.LAST_POST_PROFILE, payload: { userId, lastPostId } } }
the_stack
import * as React from 'react'; import { IPropertyFieldDateTimePickerPropsInternal, TimeConvention, DateConvention, IDateTimeFieldValue } from './IPropertyFieldDateTimePicker'; import { DatePicker, IDatePickerStrings } from 'office-ui-fabric-react/lib/DatePicker'; import { Label } from 'office-ui-fabric-react/lib/Label'; import { IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown'; import { Async } from 'office-ui-fabric-react/lib/Utilities'; import * as strings from 'PropertyControlStrings'; import { IPropertyFieldDateTimePickerHostProps, IPropertyFieldDateTimePickerHostState, ITimeComponentProps, IHoursComponentProps } from './IPropertyFieldDateTimePickerHost'; import FieldErrorMessage from '../errorMessage/FieldErrorMessage'; import styles from './PropertyFieldDateTimePickerHost.module.scss'; import HoursComponent from './HoursComponent'; import MinutesComponent from './MinutesComponent'; import SecondsComponent from './SecondsComponent'; import * as telemetry from '../../common/telemetry'; import { setPropertyValue } from '../../helpers/GeneralHelper'; /** * Defines the labels of the DatePicker control (as months, days, etc.) */ class DatePickerStrings implements IDatePickerStrings { /** * An array of strings for the full names of months. * The array is 0-based, so months[0] should be the full name of January. */ public months: string[] = [ strings.DatePickerMonthLongJanuary, strings.DatePickerMonthLongFebruary, strings.DatePickerMonthLongMarch, strings.DatePickerMonthLongApril, strings.DatePickerMonthLongMay, strings.DatePickerMonthLongJune, strings.DatePickerMonthLongJuly, strings.DatePickerMonthLongAugust, strings.DatePickerMonthLongSeptember, strings.DatePickerMonthLongOctober, strings.DatePickerMonthLongNovember, strings.DatePickerMonthLongDecember ]; /** * An array of strings for the short names of months. * The array is 0-based, so shortMonths[0] should be the short name of January. */ public shortMonths: string[] = [ strings.DatePickerMonthShortJanuary, strings.DatePickerMonthShortFebruary, strings.DatePickerMonthShortMarch, strings.DatePickerMonthShortApril, strings.DatePickerMonthShortMay, strings.DatePickerMonthShortJune, strings.DatePickerMonthShortJuly, strings.DatePickerMonthShortAugust, strings.DatePickerMonthShortSeptember, strings.DatePickerMonthShortOctober, strings.DatePickerMonthShortNovember, strings.DatePickerMonthShortDecember ]; /** * An array of strings for the full names of days of the week. * The array is 0-based, so days[0] should be the full name of Sunday. */ public days: string[] = [ strings.DatePickerDayLongSunday, strings.DatePickerDayLongMonday, strings.DatePickerDayLongTuesday, strings.DatePickerDayLongWednesday, strings.DatePickerDayLongThursday, strings.DatePickerDayLongFriday, strings.DatePickerDayLongSaturday ]; /** * An array of strings for the initials of the days of the week. * The array is 0-based, so days[0] should be the initial of Sunday. */ public shortDays: string[] = [ strings.DatePickerDayShortSunday, strings.DatePickerDayShortMonday, strings.DatePickerDayShortTuesday, strings.DatePickerDayShortWednesday, strings.DatePickerDayShortThursday, strings.DatePickerDayShortFriday, strings.DatePickerDayShortSaturday ]; /** * String to render for button to direct the user to today's date. */ public goToToday: string = strings.DatepickerGoToToday; /** * Error message to render for TextField if isRequired validation fails. */ public isRequiredErrorMessage: string = ''; /** * Error message to render for TextField if input date string parsing fails. */ public invalidInputErrorMessage: string = ''; } /** * Renders the controls for PropertyFieldDateTimePicker component */ export default class PropertyFieldDateTimePickerHost extends React.Component<IPropertyFieldDateTimePickerHostProps, IPropertyFieldDateTimePickerHostState> { public static defaultProps = { showLabels: true }; private _latestValidateValue: string; private async: Async; private delayedValidate: (value: IDateTimeFieldValue) => void; private _crntDate: Date; private _crntHours: number; private _crntMinutes: number; private _crntSeconds: number; /** * Constructor */ constructor(props: IPropertyFieldDateTimePickerHostProps) { super(props); telemetry.track('PropertyFieldDateTimePicker', { dateConvention: props.dateConvention ? DateConvention[props.dateConvention] : '', formatDate: !!props.formatDate, timeConvention: props.timeConvention ? TimeConvention[props.timeConvention] : '', disabled: props.disabled }); // Bind the current object to the external called onSelectDate method this._onSelectDate = this._onSelectDate.bind(this); this._dropdownHoursChanged = this._dropdownHoursChanged.bind(this); this._dropdownMinutesChanged = this._dropdownMinutesChanged.bind(this); this._dropdownSecondsChanged = this._dropdownSecondsChanged.bind(this); // Initiate the current date values this._crntDate = this._getDateValue(); // Intiate the time values (only when date and time convention is active) this._crntHours = this.props.dateConvention === DateConvention.DateTime && this._getDateValue() !== null ? this._getDateValue().getHours() : 0; this._crntMinutes = this.props.dateConvention === DateConvention.DateTime && this._getDateValue() !== null ? this._getDateValue().getMinutes() : 0; this._crntSeconds = this.props.dateConvention === DateConvention.DateTime && this._getDateValue() !== null ? this._getDateValue().getSeconds() : 0; // Set the current state this.state = { day: this._crntDate, hours: this._crntHours, minutes: this._crntMinutes, seconds: this._crntSeconds, errorMessage: '' }; this.async = new Async(this); this.validate = this.validate.bind(this); this.notifyAfterValidate = this.notifyAfterValidate.bind(this); this.delayedValidate = this.async.debounce(this.validate, this.props.deferredValidationTime); } /** * Function to retrieve the initial date */ private _getDateValue() { if (typeof this.props.initialDate !== 'undefined' && this.props.initialDate !== null) { if (typeof this.props.initialDate.value !== 'undefined' && this.props.initialDate.value !== null) { return new Date(this.props.initialDate.value.toString()); } } return null; } /** * Function called when the DatePicker Office UI Fabric component selected date changed */ private _onSelectDate(date: Date): void { if (date === null) { return; } this._crntDate = date; this._saveDate(); } /** * Function called when hours value have been changed * @param element Hours dropdown value */ private _dropdownHoursChanged(element?: IDropdownOption): void { this._crntHours = parseInt(element.key.toString()); this._saveDate(); } /** * Function called when minutes value have been changed * @param element Minutes dropdown value */ private _dropdownMinutesChanged(element?: IDropdownOption): void { this._crntMinutes = parseInt(element.key.toString()); this._saveDate(); } /** * Function called when seconds value have been changed * @param element Seconds dropdown value */ private _dropdownSecondsChanged(element?: IDropdownOption): void { this._crntSeconds = parseInt(element.key.toString()); this._saveDate(); } /** * Save the new date */ private _saveDate(): void { // Check if the current date object exists if (this._crntDate === null) { return; } // Set the current date state for the component this.setState({ day: this._crntDate, hours: this._crntHours, minutes: this._crntMinutes, seconds: this._crntSeconds }); // Create the final date object const finalDate = new Date(this._crntDate.toISOString()); finalDate.setHours(this._crntHours); finalDate.setMinutes(this._crntMinutes); finalDate.setSeconds(this._crntSeconds); if (finalDate !== null) { let finalDateAsString: string = ''; if (this.props.formatDate) { finalDateAsString = this.props.formatDate(finalDate); } else { finalDateAsString = finalDate.toString(); } this.delayedValidate({ value: finalDate, displayValue: finalDateAsString }); } } /** * Validates the new custom field value */ private validate(dateVal: IDateTimeFieldValue): void { if (typeof this.props.onGetErrorMessage === 'undefined' || this.props.onGetErrorMessage === null) { this.notifyAfterValidate(this.props.initialDate, dateVal); return; } if (this._latestValidateValue === dateVal.displayValue) { return; } this._latestValidateValue = dateVal.displayValue; const result: string | PromiseLike<string> = this.props.onGetErrorMessage(dateVal.displayValue || ''); if (typeof result !== 'undefined') { if (typeof result === 'string') { if (result === '') { this.notifyAfterValidate(this.props.initialDate, dateVal); } this.setState({ errorMessage: result }); } else { result.then((errorMessage: string) => { if (typeof errorMessage === 'undefined' || errorMessage === '') { this.notifyAfterValidate(this.props.initialDate, dateVal); } this.setState({ errorMessage: errorMessage }); }); } } else { this.notifyAfterValidate(this.props.initialDate, dateVal); } } /** * Notifies the parent Web Part of a property value change */ private notifyAfterValidate(oldValue: IDateTimeFieldValue, newValue: IDateTimeFieldValue) { if (this.props.onPropertyChange && newValue !== null) { setPropertyValue(this.props.properties, this.props.targetProperty, newValue); this.props.onPropertyChange(this.props.targetProperty, oldValue, newValue); // Trigger the apply button if (typeof this.props.onChange !== 'undefined' && this.props.onChange !== null) { this.props.onChange(this.props.targetProperty, newValue); } } } /** * Called when the component will unmount */ public componentWillUnmount() { this.async.dispose(); } /** * Renders the control */ public render(): JSX.Element { // Defines the DatePicker control labels const dateStrings: DatePickerStrings = new DatePickerStrings(); const { showLabels, disabled, timeConvention, dateConvention, label, formatDate } = this.props; // Check if the time element needs to be rendered let timeElm: JSX.Element = <tr />; if (dateConvention === DateConvention.DateTime) { timeElm = ( <tr> {showLabels && <td className={styles.labelCell}> <Label className={styles.fieldLabel}>{strings.DateTimePickerTime}</Label> </td>} <td> <table cellPadding='0' cellSpacing='0'> <tbody> <tr> <td> <HoursComponent disabled={disabled} timeConvention={timeConvention} value={this.state.hours} onChange={this._dropdownHoursChanged} /> </td> <td className={styles.seperator}><Label>:</Label></td> <td> <MinutesComponent disabled={disabled} value={this.state.minutes} onChange={this._dropdownMinutesChanged} /> </td> <td className={styles.seperator}><Label>:</Label></td> <td> <SecondsComponent disabled={disabled} value={this.state.seconds} onChange={this._dropdownSecondsChanged} /> </td> </tr> </tbody> </table> </td> </tr>); } // Renders content return ( <div className={styles.propertyFieldDateTimePicker}> {label && <Label>{label}</Label>} <table cellPadding='0' cellSpacing='0'> <tbody> <tr> {showLabels && <td className={styles.labelCell}> <Label className={styles.fieldLabel}>{strings.DateTimePickerDate}</Label> </td>} <td> <DatePicker formatDate={formatDate} disabled={disabled} value={this.state.day} strings={dateStrings} isMonthPickerVisible={true} onSelectDate={this._onSelectDate} allowTextInput={false} firstDayOfWeek={this.props.firstDayOfWeek} /> </td> </tr> {!!timeElm && <tr> <td className={styles.spacerRow} colSpan={showLabels ? 2 : 1}></td> </tr>} {timeElm} </tbody> </table> <FieldErrorMessage errorMessage={this.state.errorMessage} /> </div > ); } }
the_stack
import { assert } from "chai"; import "mocha"; import { promisify } from "util"; import { fakeClient } from "../helpers.spec"; import { AlternateMessageModifier, invisibleSuffix, } from "./alternate-message-modifier"; describe("./modules/alternate-message-modifier", function () { describe("AlternateMessageModifier", () => { it("should have the correct escape for the invisible suffix", () => { // 1 (space) + 2 (invisible character) assert.strictEqual(invisibleSuffix.length, 3); assert.strictEqual([...invisibleSuffix].length, 2); }); it("should append invisible character if last message is equal", async function () { const { client, emitAndEnd } = fakeClient(); client.configuration.username = "randers"; const messageModifier = new AlternateMessageModifier(client); client.use(messageModifier); assert.strictEqual( messageModifier.appendInvisibleCharacter( "forsen", "Kappa Keepo PogChamp", false ), "Kappa Keepo PogChamp" ); assert.strictEqual( messageModifier.appendInvisibleCharacter( "forsen", "Kappa Keepo PogChamp", true ), "Kappa Keepo PogChamp" ); // from a different user should be ignored emitAndEnd( "@badge-info=subscriber/13;badges=subscriber/12,glhf-p" + "ledge/1;color=#19E6E6;display-name=randers;emote-only=1;emotes=" + "25:0-4/1902:6-10/88:12-19;flags=;id=4556c83f-4dd6-4c6d-bb87-7a" + "b2472188e3;mod=0;room-id=22484632;subscriber=1;tmi-sent-ts=156" + "6127471330;turbo=0;user-id=40286300;user-type= :randers00!rander" + "s00@randers00.tmi.twitch.tv PRIVMSG #forsen :Kappa Keepo PogChamp" ); assert.strictEqual( messageModifier.appendInvisibleCharacter( "forsen", "Kappa Keepo PogChamp", false ), "Kappa Keepo PogChamp" ); assert.strictEqual( messageModifier.appendInvisibleCharacter( "forsen", "Kappa Keepo PogChamp", true ), "Kappa Keepo PogChamp" ); emitAndEnd( "@badge-info=subscriber/13;badges=subscriber/12,glhf-p" + "ledge/1;color=#19E6E6;display-name=randers;emote-only=1;emotes=" + "25:0-4/1902:6-10/88:12-19;flags=;id=4556c83f-4dd6-4c6d-bb87-7a" + "b2472188e3;mod=0;room-id=22484632;subscriber=1;tmi-sent-ts=156" + "6127471330;turbo=0;user-id=40286300;user-type= :randers!rander" + "s@randers.tmi.twitch.tv PRIVMSG #forsen :Kappa Keepo PogChamp" ); await promisify(setImmediate); assert.strictEqual( messageModifier.appendInvisibleCharacter( "forsen", "Kappa Keepo PogChamp", false ), "Kappa Keepo PogChamp \u{000e0000}" ); // /me makes it different assert.strictEqual( messageModifier.appendInvisibleCharacter( "forsen", "Kappa Keepo PogChamp", true ), "Kappa Keepo PogChamp" ); }); it("should not append invisible character if fast spam is enabled (mod, VIP, etc.)", async function () { const { client, emitAndEnd } = fakeClient(); client.configuration.username = "randers"; const messageModifier = new AlternateMessageModifier(client); client.use(messageModifier); assert.strictEqual( messageModifier.appendInvisibleCharacter( "pajlada", "Kappa Keepo PogChamp", false ), "Kappa Keepo PogChamp" ); assert.strictEqual( messageModifier.appendInvisibleCharacter( "pajlada", "Kappa Keepo PogChamp", true ), "Kappa Keepo PogChamp" ); // userstate tracker will register that we are moderator // in #pajlada emitAndEnd( "@badge-info=subscriber/11;badges=moderator/1,subscriber/6" + ";color=#19E6E6;display-name=randers;emote-sets=0,42,237,9" + "54,1349,3188,4236,13653,15961,19194,22197,103040,164050,5" + "40476,588170,669914,771849,1511995,1641460,1641461,164146" + "2,300206298;mod=1;subscriber=1;user-type=mod :tmi.twitch." + "tv USERSTATE #pajlada", "@badge-info=subscriber/11;badges=moderator/1,subscriber/6;" + "color=#19E6E6;display-name=randers;emote-only=1;emotes=25" + ":0-4/1902:6-10/88:12-19;flags=;id=7467aa03-de47-4841-a0e0" + "-d392f1ec1811;mod=1;room-id=11148817;subscriber=1;tmi-sent" + "-ts=1566137969595;turbo=0;user-id=40286300;user-type=mod :" + "randers!randers@randers.tmi.twitch.tv PRIVMSG #pajlada :Ka" + "ppa Keepo PogChamp" ); await promisify(setImmediate); // even though our last message was equal, // this should not append anything since fast spam // is enabled assert.strictEqual( messageModifier.appendInvisibleCharacter( "forsen", "Kappa Keepo PogChamp", false ), "Kappa Keepo PogChamp" ); assert.strictEqual( messageModifier.appendInvisibleCharacter( "forsen", "Kappa Keepo PogChamp", true ), "Kappa Keepo PogChamp" ); }); it("should append invisible character through the say() function (case where we are joined to channel)", async function () { const { client, end, transports } = fakeClient(); client.configuration.username = "randers"; client.connections[0].joinedChannels.add("forsen"); client.connections[0].wantedChannels.add("forsen"); const messageModifier = new AlternateMessageModifier(client); client.use(messageModifier); const sayPromise = client.say("forsen", "Kappa Keepo PogChamp"); await promisify(setImmediate); assert.deepStrictEqual(transports[1].data, [ "PRIVMSG #forsen :Kappa Keepo PogChamp\r\n", ]); transports[1].emit( "@badge-info=subscriber/13;badges=subscriber/12,glhf-ple" + "dge/1;color=#19E6E6;display-name=randers;emote-sets=0,42,237" + ",954,1349,3188,4236,13653,15961,19194,22197,103040,164050,540" + "476,588170,669914,771845,1537481,1641460,1641461,1641462,300" + "206310;mod=0;subscriber=1;user-type= :tmi.twitch.tv USERSTAT" + "E #forsen" ); await sayPromise; // we were joined to the channel we sent a message to, // so AlternateMessageModifier should NOT save the sent message // as the last message (since we expect to receive it back) assert.strictEqual( messageModifier.appendInvisibleCharacter( "forsen", "Kappa Keepo PogChamp", false ), "Kappa Keepo PogChamp" ); transports[1].emit( "@badge-info=subscriber/13;badges=subscriber/12," + "glhf-pledge/1;color=#19E6E6;display-name=randers;emote-o" + "nly=1;emotes=25:0-4/1902:6-10/88:12-19;flags=;id=bc4e1af" + "8-2226-4e2a-8b18-90b05edfb01e;mod=0;room-id=22484632;subs" + "criber=1;tmi-sent-ts=1566133801254;turbo=0;user-id=40286" + "300;user-type= :randers!randers@randers.tmi.twitch.tv PR" + "IVMSG #forsen :Kappa Keepo PogChamp" ); end(); await promisify(setImmediate); // now our own message was received so it should have been set // as the last message. assert.strictEqual( messageModifier.appendInvisibleCharacter( "forsen", "Kappa Keepo PogChamp", false ), "Kappa Keepo PogChamp \u{000e0000}" ); assert.strictEqual( messageModifier.appendInvisibleCharacter( "forsen", "Kappa Keepo PogChamp", true ), "Kappa Keepo PogChamp" ); }); it("should append invisible character through the say() function (case where we are not joined to channel)", async function () { const { client, end, transports } = fakeClient(); client.configuration.username = "randers"; const messageModifier = new AlternateMessageModifier(client); client.use(messageModifier); const sayPromise = client.say("forsen", "Kappa Keepo PogChamp"); await promisify(setImmediate); assert.deepStrictEqual(transports[0].data, [ "PRIVMSG #forsen :Kappa Keepo PogChamp\r\n", ]); transports[0].emit( "@badge-info=subscriber/13;badges=subscriber/12,glhf-ple" + "dge/1;color=#19E6E6;display-name=randers;emote-sets=0,42,237" + ",954,1349,3188,4236,13653,15961,19194,22197,103040,164050,540" + "476,588170,669914,771845,1537481,1641460,1641461,1641462,300" + "206310;mod=0;subscriber=1;user-type= :tmi.twitch.tv USERSTAT" + "E #forsen" ); await sayPromise; // we were NOT joined to the channel we sent a message to, // so AlternateMessageModifier SHOULD save the sent message // as the last message (since we WILL not receive it back as a PRIVMSG) assert.strictEqual( messageModifier.appendInvisibleCharacter( "forsen", "Kappa Keepo PogChamp", false ), "Kappa Keepo PogChamp \u{000e0000}" ); assert.strictEqual( messageModifier.appendInvisibleCharacter( "forsen", "Kappa Keepo PogChamp", true ), "Kappa Keepo PogChamp" ); end(); }); it("should append invisible character through the me() function (case where we are joined to channel)", async function () { const { client, end, transports } = fakeClient(); client.configuration.username = "randers"; client.connections[0].joinedChannels.add("forsen"); client.connections[0].wantedChannels.add("forsen"); const messageModifier = new AlternateMessageModifier(client); client.use(messageModifier); const mePromise = client.me("forsen", "Kappa Keepo PogChamp"); await promisify(setImmediate); assert.deepStrictEqual(transports[1].data, [ "PRIVMSG #forsen :/me Kappa Keepo PogChamp\r\n", ]); transports[1].emit( "@badge-info=subscriber/13;badges=subscriber/12,glhf-ple" + "dge/1;color=#19E6E6;display-name=randers;emote-sets=0,42,237" + ",954,1349,3188,4236,13653,15961,19194,22197,103040,164050,540" + "476,588170,669914,771845,1537481,1641460,1641461,1641462,300" + "206310;mod=0;subscriber=1;user-type= :tmi.twitch.tv USERSTAT" + "E #forsen" ); await mePromise; // we were joined to the channel we sent a message to, // so AlternateMessageModifier should NOT save the sent message // as the last message (since we expect to receive it back) assert.strictEqual( messageModifier.appendInvisibleCharacter( "forsen", "Kappa Keepo PogChamp", true ), "Kappa Keepo PogChamp" ); transports[1].emit( "@badge-info=subscriber/13;badges=subscriber/12," + "glhf-pledge/1;color=#19E6E6;display-name=randers;emote-o" + "nly=1;emotes=25:0-4/1902:6-10/88:12-19;flags=;id=bc4e1af" + "8-2226-4e2a-8b18-90b05edfb01e;mod=0;room-id=22484632;subs" + "criber=1;tmi-sent-ts=1566133801254;turbo=0;user-id=40286" + "300;user-type= :randers!randers@randers.tmi.twitch.tv PR" + "IVMSG #forsen :\u0001ACTION Kappa Keepo PogChamp\u0001" ); end(); await promisify(setImmediate); // now our own message was received so it should have been set // as the last message. assert.strictEqual( messageModifier.appendInvisibleCharacter( "forsen", "Kappa Keepo PogChamp", true ), "Kappa Keepo PogChamp \u{000e0000}" ); assert.strictEqual( messageModifier.appendInvisibleCharacter( "forsen", "Kappa Keepo PogChamp", false ), "Kappa Keepo PogChamp" ); }); it("should append invisible character through the me() function (case where we are not joined to channel)", async function () { const { client, end, transports } = fakeClient(); client.configuration.username = "randers"; const messageModifier = new AlternateMessageModifier(client); client.use(messageModifier); const mePromise = client.me("forsen", "Kappa Keepo PogChamp"); await promisify(setImmediate); assert.deepStrictEqual(transports[0].data, [ "PRIVMSG #forsen :/me Kappa Keepo PogChamp\r\n", ]); transports[0].emit( "@badge-info=subscriber/13;badges=subscriber/12,glhf-ple" + "dge/1;color=#19E6E6;display-name=randers;emote-sets=0,42,237" + ",954,1349,3188,4236,13653,15961,19194,22197,103040,164050,540" + "476,588170,669914,771845,1537481,1641460,1641461,1641462,300" + "206310;mod=0;subscriber=1;user-type= :tmi.twitch.tv USERSTAT" + "E #forsen" ); await mePromise; // we were NOT joined to the channel we sent a message to, // so AlternateMessageModifier SHOULD save the sent message // as the last message (since we WILL not receive it back as a PRIVMSG) assert.strictEqual( messageModifier.appendInvisibleCharacter( "forsen", "Kappa Keepo PogChamp", true ), "Kappa Keepo PogChamp \u{000e0000}" ); assert.strictEqual( messageModifier.appendInvisibleCharacter( "forsen", "Kappa Keepo PogChamp", false ), "Kappa Keepo PogChamp" ); end(); }); }); });
the_stack
import * as path from 'path'; import { GlobMatcher, GlobMatchOptions, MatcherMode } from './GlobMatcher'; import { GlobMatch, GlobPattern, GlobPatternNormalized, GlobPatternWithOptionalRoot, PathInterface, } from './GlobMatcherTypes'; import mm = require('micromatch'); const defaultCwdWin32 = 'C:\\user\\home\\project\\testing'; const defaultCwdPosix = '/user/home/project/testing'; const pathWin32: PathInterface = { ...path.win32, resolve: (...paths) => path.win32.resolve(defaultCwdWin32, ...paths), }; const pathPosix: PathInterface = { ...path.posix, resolve: (...paths) => path.posix.resolve(defaultCwdPosix, ...paths), }; const pathNames = new Map([ [pathWin32, 'Win32'], [pathPosix, 'Posix'], ]); describe('Validate assumptions', () => { test('path relative', () => { const relCrossDevice = path.win32.relative('C:\\user\\home\\project', 'D:\\projects'); expect(relCrossDevice).toEqual('D:\\projects'); const relSubDir = path.win32.relative('/User/home/project', '/User/home/project/fun/with/coding'); expect(relSubDir).toBe(path.win32.normalize('fun/with/coding')); const relSubDirPosix = path.posix.relative('/User/home/project', '/User/home/project/fun/with/coding'); expect(relSubDirPosix).toBe(path.posix.normalize('fun/with/coding')); }); test('path parse', () => { const res1 = path.win32.parse('/user/home/project'); expect(res1.root).toBe('/'); const res2 = path.win32.parse('user/home/project'); expect(res2.root).toBe(''); const res3 = path.win32.parse('C:\\user\\home\\project'); expect(res3.root).toBe('C:\\'); const res4 = path.win32.parse('C:user\\home\\project'); expect(res4.root).toBe('C:'); }); }); describe('Validate Micromatch assumptions', () => { test.each` glob | filename | expectedToMatch ${'*.json'} | ${'settings.json'} | ${true} ${'*.json'} | ${'/settings.json'} | ${false} ${'*.json'} | ${'src/settings.json'} | ${false} ${'*.json'} | ${'/src/settings.json'} | ${false} ${'**/*.json'} | ${'settings.json'} | ${true} ${'**/*.json'} | ${'/settings.json'} | ${true} ${'**/*.json'} | ${'src/settings.json'} | ${true} ${'**/*.json'} | ${'/src/settings.json'} | ${true} ${'**/temp'} | ${'/src/temp/data.json'} | ${false} ${'src/*.json'} | ${'src/settings.json'} | ${true} ${'**/{*.json,*.json/**}'} | ${'settings.json'} | ${true} ${'**/{*.json,*.json/**}'} | ${'/settings.json'} | ${true} ${'**/{*.json,*.json/**}'} | ${'src/settings.json'} | ${true} ${'**/{*.json,*.json/**}'} | ${'src/settings.json/config'} | ${true} ${'**/{*.json,*.json/**}'} | ${'settings.json/config'} | ${true} ${'src/*.{test,spec}.ts'} | ${'src/code.test.ts'} | ${true} ${'src/*.(test|spec).ts'} | ${'src/code.test.ts'} | ${true} ${'src/*.(test|spec).ts'} | ${'src/code.spec.ts'} | ${true} ${'src/*.(test|spec).ts'} | ${'src/deep.code.test.ts'} | ${true} ${'src/*.(test|spec).ts'} | ${'src/test.ts'} | ${false} `( `Test Micromatch glob: '$glob', filename: '$filename' expected: $expectedToMatch`, ({ glob, filename, expectedToMatch }) => { const reg1 = mm.makeRe(glob); expect(reg1.test(filename)).toEqual(expectedToMatch); } ); }); function resolveFilename(pathInstance: PathInterface, filename: string): string; function resolveFilename(pathInstance: PathInterface, filename: string | undefined): string | undefined; function resolveFilename(pathInstance: PathInterface, filename: string | undefined): string | undefined { if (filename === undefined) return filename; const usingWin32 = isWin32(pathInstance); const rootPrefix = usingWin32 ? 'C:\\' : ''; const cwd = usingWin32 ? defaultCwdWin32 : defaultCwdPosix; filename = filename.replace('${cwd}', cwd); filename = filename.startsWith('/') ? pathInstance.join(rootPrefix, filename) : filename; filename = pathInstance.resolve(pathInstance.normalize(filename)); return filename; } [pathPosix, pathWin32].forEach((pathInstance) => { describe(`Validate GlobMatcher ${pathInstance === pathWin32 ? 'Windows' : 'Posix'}`, () => { tests().forEach((curTest, index) => { const [patterns, _root, _filename, expected, description] = curTest; const root = resolveFilename(pathInstance, _root); const filename = resolveFilename(pathInstance, _filename); test(`test ${index} ${description}, pattern: [${patterns}] filename: "${filename}", root: "${root}", expected: ${ expected ? 'T' : 'F' }`, () => { const matcher = new GlobMatcher(patterns, root, pathInstance); try { expect(matcher.match(filename)).toEqual(expected); } catch (e) { console.error('Failed on %i %o', index, curTest); throw e; } }); }); }); }); describe('Tests .gitignore file contents', () => { const pattern = ` # This is a comment # ignore spec and test files. src/*.(test|spec).ts node_modules/** dist *.js !**/settings.js !!*.txt # *.py,cover `; const root = '/Users/code/project/cspell/'; // cspell:ignore nobrace // const matcher = new GlobMatcher(pattern, root); const matcher = new GlobMatcher(pattern, { root, nobrace: false }); interface TestCase { filename: string; expected: boolean | Partial<GlobMatch>; comment: string; } test.each` filename | expected | comment ${root + 'src/code.py'} | ${false} | ${'Ensure that .py files are allowed'} ${root + 'src/code.ts'} | ${false} | ${'Ensure that .ts files are allowed'} ${root + 'dist/code.ts'} | ${true} | ${'Ensure that `dest` .ts files are not allowed'} ${root + 'src/code.js'} | ${true} | ${'Ensure that no .js files are allowed'} ${root + 'src/code.test.ts'} | ${true} | ${'Ensure that test.ts files are not allowed'} ${root + 'src/code.spec.ts'} | ${true} | ${'Ensure that spec.ts files are not allowed'} ${'/Users/guest/code/' + 'src/code.test.ts'} | ${false} | ${'Ensure that test files in a different root are allowed'} ${'/Users/guest/code/' + 'src/code.js'} | ${false} | ${'Ensure *.js files are allowed under a different root.'} ${root + 'node_modules/cspell/code.ts'} | ${true} | ${'Ensure that node modules are not allowed in the current root.'} ${root + 'nested/node_modules/cspell/code.ts'} | ${false} | ${'Ensure that nested node modules are allowed in the current root.'} ${'/Users/guest/code/' + 'node_modules/cspell/code.ts'} | ${false} | ${'Ensure that node modules in a different root are allowed'} ${root + 'settings.js'} | ${false} | ${'Ensure that settings.js is kept'} ${root + 'dist/settings.js'} | ${false} | ${'Ensure that settings.js is kept'} ${root + 'node_modules/settings.js'} | ${false} | ${'Ensure that settings.js is kept'} ${root + 'src.txt'} | ${true} | ${'Ensure that double negative means block'} ${root + 'src/code.ts'} | ${{ matched: false }} | ${'Ensure that .ts files are allowed'} ${root + 'dist/code.ts'} | ${{ matched: true, pattern: p('**/dist/**'), isNeg: false }} | ${'Ensure that `dest` .ts files are not allowed'} ${root + 'src/code.js'} | ${{ matched: true, pattern: p('**/*.js'), isNeg: false }} | ${'Ensure that no .js files are allowed'} ${root + 'dist/settings.js'} | ${{ matched: false, pattern: p('!**/settings.js'), isNeg: true }} | ${'Ensure that settings.js is kept'} `('match && matchEx "$comment" File: "$filename" $expected', ({ filename, expected }: TestCase) => { expected = typeof expected === 'boolean' ? { matched: expected } : expected; expect(matcher.match(filename)).toBe(expected.matched); expect(matcher.matchEx(filename)).toEqual(expect.objectContaining(expected)); }); }); describe('Tests .gitignore like file contents', () => { const pattern = ` # This is a comment # ignore spec and test files. src/*.(test|spec).ts node_modules/** dist *.js !**/settings.js !!*.txt *.py,cover `; const root = '/Users/code/project/cspell/'; // cspell:ignore nobrace const matcher = new GlobMatcher(pattern, { root, nobrace: undefined }); interface TestCase { filename: string; expected: boolean | Partial<GlobMatch>; comment: string; } test.each` filename | expected | comment ${root + 'src/code.py'} | ${false} | ${'Broken match - .py files should be allowed'} ${root + 'src/code.ts'} | ${false} | ${'Ensure that .ts files are allowed'} ${root + 'dist/code.ts'} | ${true} | ${'Ensure that `dest` .ts files are not allowed'} ${root + 'src/code.js'} | ${true} | ${'Ensure that no .js files are allowed'} ${root + 'src/code.test.ts'} | ${true} | ${'Ensure that test.ts files are not allowed'} ${root + 'src/code.spec.ts'} | ${true} | ${'Ensure that spec.ts files are not allowed'} ${'/Users/guest/code/' + 'src/code.test.ts'} | ${false} | ${'Ensure that test files in a different root are allowed'} ${'/Users/guest/code/' + 'src/code.js'} | ${false} | ${'Ensure *.js files are allowed under a different root.'} ${root + 'node_modules/cspell/code.ts'} | ${true} | ${'Ensure that node modules are not allowed in the current root.'} ${root + 'nested/node_modules/cspell/code.ts'} | ${false} | ${'Ensure that nested node modules are allowed in the current root.'} ${'/Users/guest/code/' + 'node_modules/cspell/code.ts'} | ${false} | ${'Ensure that node modules in a different root are allowed'} ${root + 'settings.js'} | ${false} | ${'Ensure that settings.js is kept'} ${root + 'dist/settings.js'} | ${false} | ${'Ensure that settings.js is kept'} ${root + 'node_modules/settings.js'} | ${false} | ${'Ensure that settings.js is kept'} ${root + 'src.txt'} | ${true} | ${'Ensure that double negative means block'} ${root + 'src/code.ts'} | ${{ matched: false }} | ${'Ensure that .ts files are allowed'} ${root + 'dist/code.ts'} | ${{ matched: true, pattern: p('**/dist/**'), isNeg: false }} | ${'Ensure that `dest` .ts files are not allowed'} ${root + 'src/code.js'} | ${{ matched: true, pattern: p('**/*.js'), isNeg: false }} | ${'Ensure that no .js files are allowed'} ${root + 'dist/settings.js'} | ${{ matched: false, pattern: p('!**/settings.js'), isNeg: true }} | ${'Ensure that settings.js is kept'} `('match && matchEx "$comment" File: "$filename" $expected', ({ filename, expected }: TestCase) => { expected = typeof expected === 'boolean' ? { matched: expected } : expected; expect(matcher.match(filename)).toBe(expected.matched); expect(matcher.matchEx(filename)).toEqual(expect.objectContaining(expected)); }); }); describe('Validate Options', () => { interface TestCase { pattern: string; file: string; options: string | GlobMatchOptions | undefined; expected: Partial<GlobMatch> | boolean; } test.each` pattern | file | options | expected ${'*.yaml'} | ${'.github/workflows/test.yaml'} | ${{}} | ${{ matched: true }} ${'*.yaml'} | ${'.github/workflows/test.yaml'} | ${{ dot: false }} | ${{ matched: false }} ${'*.yaml'} | ${'.github/workflows/test.yaml'} | ${{ mode: 'include' }} | ${{ matched: false }} ${'*.yaml'} | ${'.github/workflows/test.yaml'} | ${{ dot: true }} | ${{ matched: true, pattern: p('**/*.yaml') }} ${'*.yaml'} | ${'.github/workflows/test.yaml'} | ${{ dot: true }} | ${true} ${'**/*.yaml'} | ${'.github/workflows/test.yaml'} | ${{ mode: 'exclude' }} | ${{ matched: true }} ${'**/*.yaml'} | ${'.github/workflows/test.yaml'} | ${{ mode: 'include' }} | ${{ matched: false }} ${'.github/**/*.yaml'} | ${'.github/workflows/test.yaml'} | ${{ dot: true }} | ${true} ${'.github/**/*.yaml'} | ${'.github/workflows/test.yaml'} | ${{ dot: false }} | ${true} ${'.github/**/*.yaml'} | ${'.github/workflows/test.yaml'} | ${{}} | ${true} ${'.github/**/*.yaml'} | ${'.github/test.yaml'} | ${{}} | ${true} ${'.github/**/*.yaml'} | ${'package/.github/workflows/test.yaml'} | ${{}} | ${false} ${'**/.github/**/*.yaml'} | ${'package/.github/workflows/test.yaml'} | ${{}} | ${true} ${'.github'} | ${'package/.github/workflows/test.yaml'} | ${{}} | ${true} ${'**/.github/**'} | ${'package/.github/workflows/test.yaml'} | ${{}} | ${true} ${'package/**'} | ${'package/.github/workflows/test.yaml'} | ${{}} | ${true} ${'package/**'} | ${'package/.github/workflows/test.yaml'} | ${{ dot: false }} | ${false} ${'package/**'} | ${'package/.github/workflows/test.yaml'} | ${{ mode: 'include' }} | ${false} ${'workflows'} | ${'package/.github/workflows/test.yaml'} | ${{}} | ${true} ${'workflows'} | ${'package/.github/workflows/test.yaml'} | ${{ dot: false }} | ${false} ${'package/'} | ${'package/src/test.yaml'} | ${{}} | ${true} ${'package/'} | ${'package/src/test.yaml'} | ${{ dot: false }} | ${true} ${'package/'} | ${'package/src/test.yaml'} | ${{ mode: 'include' }} | ${true} ${'package/'} | ${'repo/package/src/test.yaml'} | ${{}} | ${true} ${'package/'} | ${'repo/package/src/test.yaml'} | ${{ mode: 'include' }} | ${false} ${'/package/'} | ${'package/src/test.yaml'} | ${{}} | ${true} ${'/package/'} | ${'package/src/test.yaml'} | ${{ dot: false }} | ${true} ${'/package/'} | ${'package/src/test.yaml'} | ${{ mode: 'include' }} | ${true} ${'/package/'} | ${'repo/package/src/test.yaml'} | ${{}} | ${false} ${'/package/'} | ${'repo/package/src/test.yaml'} | ${{ mode: 'include' }} | ${false} ${'src'} | ${'package/src/test.yaml'} | ${{ mode: 'include' }} | ${false} ${'*.yaml|!test.yaml'} | ${'.github/workflows/test.yaml'} | ${{}} | ${{ matched: false, pattern: p('!**/test.yaml'), isNeg: true }} ${'*.yaml|!/test.yaml'} | ${'test.yaml'} | ${{}} | ${{ matched: false, pattern: p('!test.yaml'), isNeg: true }} ${'*.yaml|!/node_modules'} | ${'node_modules/test.yaml'} | ${{}} | ${{ matched: false, pattern: p('!node_modules/**'), isNeg: true }} ${'*.{!yaml}'} | ${'.github/workflows/test.yaml'} | ${{}} | ${false} ${'test.*|!*.{yaml,yml}'} | ${'.github/workflows/test.yaml'} | ${{}} | ${{ matched: false, isNeg: true }} ${'i18/nl_NL'} | ${'i18/nl_NL/file.txt'} | ${{ mode: 'exclude' }} | ${{ matched: true }} ${'i18/nl_NL'} | ${'code/i18/nl_NL/file.txt'} | ${{ mode: 'exclude' }} | ${{ matched: false }} `('Test options: $pattern, $file, $options', ({ pattern, file, options, expected }: TestCase) => { const root = '/Users/code/project/cspell/'; const filename = path.join(root, file); const patterns = pattern.split('|'); options == options ?? root; if (typeof options !== 'string' && typeof options !== 'undefined') { options.root = options.root ?? root; } expected = typeof expected === 'boolean' ? { matched: expected } : expected; const matcher = new GlobMatcher(patterns, options); const r = matcher.matchEx(filename); expect(r).toEqual(expect.objectContaining(expected)); }); }); describe('Validate GlobMatcher', () => { function g(glob: string, root?: string): GlobPatternWithOptionalRoot { return { glob, root, }; } interface TestCaseMatcher { patterns: GlobPattern | GlobPattern[]; root: string | undefined; filename: string; mode: MatcherMode; expected: boolean; description: string; } function runTestOn(pathInstance: PathInterface) { const os = pathNames.get(pathInstance); test.each` patterns | root | filename | mode | expected | description ${['*.json']} | ${undefined} | ${'./settings.json'} | ${'exclude'} | ${true} | ${'*.json'} ${['*.json']} | ${undefined} | ${'settings.json'} | ${'exclude'} | ${true} | ${'*.json'} ${['*.json']} | ${undefined} | ${'${cwd}/settings.json'} | ${'exclude'} | ${true} | ${'*.json'} ${'*.json'} | ${undefined} | ${'${cwd}/settings.json'} | ${'exclude'} | ${true} | ${'*.json'} ${'#.gitignore\n *.json'} | ${undefined} | ${'${cwd}/settings.json'} | ${'exclude'} | ${true} | ${'*.json'} ${['middle']} | ${''} | ${'${cwd}/packages/middle/settings.json'} | ${'exclude'} | ${true} | ${'match middle of path'} ${['.vscode']} | ${undefined} | ${'.vscode/settings.json'} | ${'exclude'} | ${true} | ${'.vscode'} ${['/*.json']} | ${'/'} | ${'/settings.json'} | ${'exclude'} | ${true} | ${'Matches root level files, /*.json'} ${['/*.json']} | ${undefined} | ${'/src/settings.json'} | ${'exclude'} | ${false} | ${'Matches pattern but not cwd /*.json'} ${['*.js']} | ${undefined} | ${'${cwd}/src/settings.js'} | ${'exclude'} | ${true} | ${'// Matches nested files, *.js'} ${'*.js'} | ${undefined} | ${'${cwd}/src/settings.js'} | ${'exclude'} | ${true} | ${'// Matches nested files, *.js'} ${g('*.js')} | ${'.'} | ${'${cwd}/src/settings.js'} | ${'exclude'} | ${true} | ${'// Matches nested files, *.js'} ${g('*.js', 'src')} | ${'.'} | ${'${cwd}/src/settings.js'} | ${'exclude'} | ${true} | ${'// Matches nested files, *.js'} ${g('*.js', 'a')} | ${'a/b'} | ${'a/b/src/settings.js'} | ${'exclude'} | ${true} | ${'// Matches nested files, *.js'} ${g('*.js', 'a')} | ${'a/b'} | ${'a/c/src/settings.js'} | ${'exclude'} | ${true} | ${'// Matches even if NOT under root.'} ${g('*.js', 'a')} | ${'a/b'} | ${'c/src/settings.js'} | ${'exclude'} | ${false} | ${'// Must match glob root'} ${['.vscode/']} | ${undefined} | ${'${cwd}/.vscode/settings.json'} | ${'exclude'} | ${true} | ${'.vscode/'} ${['.vscode/']} | ${undefined} | ${'${cwd}/.vscode'} | ${'exclude'} | ${false} | ${'.vscode/'} ${['/.vscode/']} | ${undefined} | ${'${cwd}/.vscode'} | ${'exclude'} | ${false} | ${'should not match file'} ${['/.vscode/']} | ${undefined} | ${'${cwd}/.vscode/settings.json'} | ${'exclude'} | ${true} | ${'should match root'} ${['/.vscode/']} | ${undefined} | ${'${cwd}/package/.vscode'} | ${'exclude'} | ${false} | ${'should only match root'} ${['.vscode/**']} | ${undefined} | ${'${cwd}/.vscode/settings.json'} | ${'exclude'} | ${true} | ${'should match root .vscode/**'} ${['.vscode/']} | ${undefined} | ${'${cwd}/src/.vscode/settings.json'} | ${'exclude'} | ${true} | ${'should match nested .vscode/'} ${['**/.vscode/']} | ${undefined} | ${'${cwd}/src/.vscode/settings.json'} | ${'exclude'} | ${true} | ${'should match nested .vscode/'} ${['**/.vscode/']} | ${undefined} | ${'${cwd}/src/.vscode'} | ${'exclude'} | ${false} | ${'should match nested .vscode'} ${['**/.vscode']} | ${undefined} | ${'${cwd}/src/.vscode/settings.json'} | ${'exclude'} | ${true} | ${'should match nested **/.vscode'} ${['**/.vscode/**']} | ${undefined} | ${'${cwd}/src/.vscode/settings.json'} | ${'exclude'} | ${true} | ${'should match nested **/.vscode'} ${['/User/user/Library/**']} | ${undefined} | ${'/src/User/user/Library/settings.json'} | ${'exclude'} | ${false} | ${'No match'} ${['/User/user/Library/**']} | ${undefined} | ${'${cwd}/User/user/Library/settings.json'} | ${'exclude'} | ${true} | ${'Match cwd root'} ${['/User/user/Library/**']} | ${'/'} | ${'/User/user/Library/settings.json'} | ${'exclude'} | ${true} | ${'Match system root'} ${g('*.js', 'a')} | ${'a/b'} | ${'a/b/src/settings.js'} | ${'exclude'} | ${true} | ${'// Matches nested files, *.js'} ${['*.json']} | ${undefined} | ${'./settings.json'} | ${'include'} | ${true} | ${'*.json'} ${['*.json']} | ${undefined} | ${'settings.json'} | ${'include'} | ${true} | ${'*.json'} ${['*.json']} | ${undefined} | ${'${cwd}/settings.json'} | ${'include'} | ${true} | ${'*.json'} ${'*.json'} | ${undefined} | ${'${cwd}/settings.json'} | ${'include'} | ${true} | ${'*.json'} ${'#.gitignore\n *.json'} | ${undefined} | ${'${cwd}/settings.json'} | ${'include'} | ${true} | ${'*.json'} ${['middle']} | ${''} | ${'${cwd}/packages/middle/settings.json'} | ${'include'} | ${false} | ${'match middle of path'} ${['.vscode']} | ${undefined} | ${'.vscode/settings.json'} | ${'include'} | ${false} | ${'.vscode'} ${['/*.json']} | ${'/'} | ${'/settings.json'} | ${'include'} | ${true} | ${'Matches root level files, /*.json'} ${['/*.json']} | ${undefined} | ${'/src/settings.json'} | ${'include'} | ${false} | ${'Matches pattern but not cwd /*.json'} ${['*.js']} | ${undefined} | ${'${cwd}/src/settings.js'} | ${'include'} | ${false} | ${'// Does NOT nested files, *.js'} ${'*.js'} | ${undefined} | ${'${cwd}/src/settings.js'} | ${'include'} | ${false} | ${'// Does NOT match nested files, *.js'} ${g('*.js')} | ${'.'} | ${'${cwd}/src/settings.js'} | ${'include'} | ${false} | ${'// Matches nested files, *.js'} ${g('*.js', 'src')} | ${'.'} | ${'${cwd}/src/settings.js'} | ${'include'} | ${true} | ${'// Matches nested files, *.js'} ${g('*.js', 'a')} | ${'a/b'} | ${'a/b/src/settings.js'} | ${'include'} | ${false} | ${'// Does NOT match nested files, *.js'} ${g('*.js', 'a')} | ${'a/b'} | ${'a/c/src/settings.js'} | ${'include'} | ${false} | ${'// Does NOT match if NOT under root.'} ${g('*.js', 'a')} | ${'a/b'} | ${'c/src/settings.js'} | ${'include'} | ${false} | ${'// Must match glob root'} ${['.vscode/']} | ${undefined} | ${'${cwd}/.vscode/settings.json'} | ${'include'} | ${true} | ${'.vscode/'} ${['.vscode/']} | ${undefined} | ${'${cwd}/.vscode'} | ${'include'} | ${false} | ${'.vscode/'} ${['/.vscode/']} | ${undefined} | ${'${cwd}/.vscode'} | ${'include'} | ${false} | ${'should not match file'} ${['/.vscode/']} | ${undefined} | ${'${cwd}/.vscode/settings.json'} | ${'include'} | ${true} | ${'should match root'} ${['/.vscode/']} | ${undefined} | ${'${cwd}/package/.vscode'} | ${'include'} | ${false} | ${'should only match root'} ${['.vscode/**']} | ${undefined} | ${'${cwd}/.vscode/settings.json'} | ${'include'} | ${true} | ${'should match root .vscode/**'} ${['.vscode/']} | ${undefined} | ${'${cwd}/src/.vscode/settings.json'} | ${'include'} | ${false} | ${'should not match nested .vscode/'} ${['**/.vscode/']} | ${undefined} | ${'${cwd}/src/.vscode/settings.json'} | ${'include'} | ${true} | ${'should match nested .vscode/'} ${['**/.vscode/']} | ${undefined} | ${'${cwd}/src/.vscode'} | ${'include'} | ${false} | ${'should match nested .vscode'} ${['**/.vscode']} | ${undefined} | ${'${cwd}/src/.vscode/settings.json'} | ${'include'} | ${false} | ${'should not match nested **/.vscode'} ${['**/.vscode/**']} | ${undefined} | ${'${cwd}/src/.vscode/settings.json'} | ${'include'} | ${true} | ${'should match nested **/.vscode'} ${['/User/user/Library/**']} | ${undefined} | ${'/src/User/user/Library/settings.json'} | ${'include'} | ${false} | ${'No match'} ${['/User/user/Library/**']} | ${undefined} | ${'${cwd}/User/user/Library/settings.json'} | ${'include'} | ${true} | ${'Match cwd root'} ${['/User/user/Library/**']} | ${'/'} | ${'/User/user/Library/settings.json'} | ${'include'} | ${true} | ${'Match system root'} ${g('*.js', 'a/b')} | ${'a'} | ${'a/b/settings.js'} | ${'include'} | ${true} | ${'Matches files, *.js'} ${g('*.js', 'a/b')} | ${'a'} | ${'a/settings.js'} | ${'include'} | ${false} | ${'Does not match parent files, *.js'} ${g('*.js', 'a')} | ${'a/b'} | ${'a/b/src/settings.js'} | ${'include'} | ${false} | ${'Does not match nested files, *.js'} `( `${os} $mode: $description, patterns: $patterns, filename: $filename, root: $root, $expected`, ({ filename, root, patterns, mode, expected }: TestCaseMatcher) => { root = resolveFilename(pathInstance, root); filename = resolveFilename(pathInstance, filename); patterns = resolvePattern(patterns, pathInstance); // console.log(`root: ${root}, filename: ${filename}, pattern: ${JSON.stringify(patterns)}`); const matcher = new GlobMatcher(patterns, { mode, root, nodePath: pathInstance }); // eslint-disable-next-line jest/no-standalone-expect expect(matcher.match(filename)).toEqual(expected); } ); } [pathWin32, pathPosix].forEach(runTestOn); }); describe('Validate GlobMatcher excludeMode patternsNormalizedToRoot', () => { function g(glob: string, root?: string): GlobPatternWithOptionalRoot { return { glob, root, }; } function ocg(g: Partial<GlobPatternNormalized>, path: PathInterface): GlobPatternNormalized { const { root, rawRoot, ...rest } = g; const gg: Partial<GlobPatternNormalized> = {}; if (root !== undefined) { gg.root = path.resolve(root); } if (rawRoot !== undefined) { gg.rawRoot = path.resolve(rawRoot); } return expect.objectContaining({ ...rest, ...gg }); } interface TestCaseNormalizedToRoot { patterns: GlobPattern | GlobPattern[]; root: string | undefined; pathInstance: PathInterface; mode: GlobMatchOptions['mode']; expected: Partial<GlobPatternNormalized>[]; description: string; } const expectedGlobs = { '*.json': [{ glob: '**/*.json' }, { glob: '**/*.json/**' }], '*.js': [{ glob: '**/*.js' }, { glob: '**/*.js/**' }], 'a/**/*.js': [{ glob: 'a/**/*.js' }, { glob: 'a/**/*.js/**' }], }; function gc(globs: Partial<GlobPatternWithOptionalRoot>[], ...toApply: Partial<GlobPatternWithOptionalRoot>[]) { return globs.map((glob) => toApply.reduce((a, b) => ({ ...a, ...b }), glob)); } test.each` patterns | root | mode | pathInstance | expected ${'*.json'} | ${''} | ${'exclude'} | ${pathPosix} | ${expectedGlobs['*.json']} ${'*.json'} | ${''} | ${'exclude'} | ${pathWin32} | ${expectedGlobs['*.json']} ${'*.json\n *.js'} | ${''} | ${'exclude'} | ${pathWin32} | ${[...expectedGlobs['*.json'], ...expectedGlobs['*.js']]} ${g('*.js', 'a')} | ${''} | ${'exclude'} | ${pathWin32} | ${gc(expectedGlobs['a/**/*.js'], { root: '' })} ${g('*.js', 'a')} | ${'a'} | ${'exclude'} | ${pathWin32} | ${gc(expectedGlobs['*.js'], { root: 'a' })} ${g('*.js', 'a')} | ${'a/b'} | ${'exclude'} | ${pathWin32} | ${gc(expectedGlobs['*.js'], { root: 'a/b' })} ${g('*.js', 'a/c')} | ${'a/b'} | ${'exclude'} | ${pathWin32} | ${[]} ${g('*.js', 'a/c')} | ${'a/b'} | ${'include'} | ${pathWin32} | ${[]} `( 'excludeMode patternsNormalizedToRoot $patterns $root', ({ patterns, root, pathInstance, expected, mode }: TestCaseNormalizedToRoot) => { root = resolveFilename(pathInstance, root); patterns = resolvePattern(patterns, pathInstance); const matcher = new GlobMatcher(patterns, { mode, root, nodePath: pathInstance }); expected = expected.map((e) => ocg(e, pathInstance)); expect(matcher.patternsNormalizedToRoot).toEqual(expected); } ); }); type TestCase = [string[] | string, string | undefined, string, boolean, string]; function tests(): TestCase[] { const from = 0; const limit = 0; const testCases: TestCase[] = [ [['*.json'], undefined, './settings.json', true, '*.json'], [['*.json'], undefined, 'settings.json', true, '*.json'], [['*.json'], undefined, '${cwd}/settings.json', true, '*.json'], [['.vscode'], undefined, '.vscode/settings.json', true, '.vscode'], [['/*.json'], '/', '/settings.json', true, 'Matches root level files, /*.json'], // . [['/*.json'], undefined, '/src/settings.json', false, 'Matches pattern but not cwd /*.json'], // . [['*.js'], undefined, '${cwd}/src/settings.js', true, '// Matches nested files, *.js'], [['.vscode/'], undefined, '${cwd}/.vscode/settings.json', true, '.vscode/'], [['.vscode/'], undefined, '${cwd}/.vscode', false, '.vscode/'], [['.vscode/'], undefined, '${cwd}/src/.vscode/settings.json', true, 'should match nested .vscode/'], [['**/.vscode/'], undefined, '${cwd}/src/.vscode/settings.json', true, 'should match nested .vscode/'], [['**/.vscode'], undefined, '${cwd}/src/.vscode/settings.json', true, 'should match nested **/.vscode'], [['**/.vscode/**'], undefined, '${cwd}/src/.vscode/settings.json', true, 'should match nested **/.vscode'], [['/User/user/Library/**'], undefined, '/src/User/user/Library/settings.json', false, 'No match'], [['/User/user/Library/**'], '/', '/User/user/Library/settings.json', true, 'Match system root'], [['*.json'], undefined, 'settings.json', true, '*.json'], [['.vscode'], undefined, '.vscode/settings.json', true, '.vscode'], [['/*.json'], undefined, 'settings.json', true, 'Matches only root level files, /*.json'], // . [['/*.json'], undefined, 'src/settings.json', false, 'Matches only root level files, /*.json'], // . [['*.js'], undefined, 'src/settings.js', true, '// Matches nested files, *.js'], [['.vscode/'], undefined, '.vscode/settings.json', true, '.vscode/'], [['.vscode/'], undefined, '.vscode', false, '.vscode/'], [['.vscode/'], undefined, 'src/.vscode/settings.json', true, 'should match nested .vscode/'], [['**/.vscode/'], undefined, 'src/.vscode/settings.json', true, 'should match nested .vscode/'], [['**/.vscode'], undefined, 'src/.vscode/settings.json', true, 'should match nested **/.vscode'], [['**/.vscode/**'], undefined, 'src/.vscode/settings.json', true, 'should match nested **/.vscode'], [['/User/user/Library/**'], undefined, 'src/User/user/Library/settings.json', false, 'No match'], [['/User/user/Library/**'], undefined, 'User/user/Library/settings.json', true, 'Match system root'], // With Root [['*.json'], '/User/code/src', '/User/code/src/settings.json', true, 'With Root *.json'], [['.vscode'], '/User/code/src', '/User/code/src/.vscode/settings.json', true, 'With Root .vscode'], [ ['/*.json'], '/User/code/src', '/User/code/src/settings.json', true, 'With Root Matches only root level files, /*.json', ], // . [['*.js'], '/User/code/src', '/User/code/src/src/settings.js', true, 'With Root Matches nested files, *.js'], [['.vscode/'], '/User/code/src', '/User/code/src/.vscode/settings.json', true, 'With Root .vscode/'], [['.vscode/'], '/User/code/src', '/User/code/src/.vscode', false, 'With Root .vscode/'], // This one shouldn't match, but micromatch says it should. :-( [ ['.vscode/'], '/User/code/src', '/User/code/src/src/.vscode/settings.json', true, 'With Root should match nested .vscode/', ], [ ['**/.vscode/'], '/User/code/src', '/User/code/src/src/.vscode/settings.json', true, 'With Root should match nested .vscode/', ], [ ['/User/user/Library/**'], '/User/code/src', '/src/User/user/Library/settings.json', false, 'With Root No match', ], [ ['/User/user/Library/**'], '/User/code/src', '/User/user/Library/settings.json', false, 'File has but does not match root', ], [['tests/*.test.ts'], '/User/code/src', 'tests/code.test.ts', false, 'Relative file with Root'], [['tests/**/*.test.ts'], '/User/code/src', 'tests/nested/code.test.ts', false, 'Relative file with Root'], [['tests/*.test.ts'], '${cwd}', 'tests/code.test.ts', true, 'Relative file with Root'], [['tests/**/*.test.ts'], '${cwd}', 'tests/nested/code.test.ts', true, 'Relative file with Root'], // With non matching Root [['*.json'], '/User/lib/src', '/User/code/src/settings.json', false, 'With non matching Root *.json'], [['.vscode'], '/User/lib/src', '/User/code/src/.vscode/settings.json', false, 'With non matching Root .vscode'], // Root with trailing / [['*.json'], '/User/code/src/', '/User/code/src/settings.json', true, '*.json'], [['.vscode'], '/User/code/src/', '/User/code/src/.vscode/settings.json', true, '.vscode'], [ ['/*.json'], '/User/code/src/', '/User/code/src/settings.json', true, 'Matches only root level files, /*.json', ], // . [['*.js'], '/User/code/src/', '/User/code/src/src/settings.js', true, '// Matches nested files, *.js'], [['.vscode/'], '/User/code/src/', '/User/code/src/.vscode/settings.json', true, '.vscode/'], [['.vscode/'], '/User/code/src/', '/User/code/src/.vscode', false, '.vscode/'], // This one shouldn't match, but micromatch says it should. :-( [ ['/.vscode/'], '/User/code/src/', '/User/code/src/src/.vscode/settings.json', false, "shouldn't match nested .vscode/", ], [ ['.vscode/'], '/User/code/src/', '/User/code/src/src/.vscode/settings.json', true, 'should match nested .vscode/', ], [['.vscode/'], '/User/code/src/', '/User/code/src/src/.vscode', false, 'should match nested file .vscode'], [ ['**/.vscode/'], '/User/code/src/', '/User/code/src/src/.vscode/settings.json', true, 'should match nested .vscode/', ], [['/User/user/Library/**'], '/User/code/src/', '/src/User/user/Library/settings.json', false, 'No match'], [['/User/user/Library/**'], '/User/code/src/', '/User/user/Library/settings.json', false, 'Match system root'], // System Root / [['*.json'], '/', '/User/code/src/settings.json', true, '*.json'], [['.vscode'], '/', '/.vscode/settings.json', true, '.vscode'], [['/*.json'], '/', '/settings.json', true, 'Matches only root level files, /*.json'], // . [['*.js'], '/', '/src/settings.js', true, '// Matches nested files, *.js'], [['.vscode/'], '/', '/.vscode/settings.json', true, '.vscode/'], [['.vscode/'], '/', '/.vscode', false, '.vscode/'], [['.vscode/'], '/', '/src/.vscode/settings.json', true, 'should match nested .vscode/'], [['**/.vscode/'], '/', '/src/.vscode/settings.json', true, 'should match nested .vscode/'], [['/User/user/Library/**'], '/', '/src/User/user/Library/settings.json', false, 'No match'], [['/User/user/Library/**'], '/', '/User/user/Library/settings.json', true, 'Match system root'], // Empty Root / [['*.json'], '', '${cwd}/User/code/src/settings.json', true, '*.json'], [['.vscode'], '', '${cwd}/.vscode/settings.json', true, '.vscode'], [['/*.json'], '', '${cwd}/settings.json', true, 'Matches only root level files, /*.json'], // . [['/*.json'], '', '${cwd}/src/settings.json', false, 'Matches only root level files, /*.json'], // . [['*.js'], '', '${cwd}/src/settings.js', true, '// Matches nested files, *.js'], [['.vscode/'], '', '${cwd}/.vscode/settings.json', true, '.vscode/'], [['.vscode/'], '', '${cwd}/.vscode', false, '.vscode/'], [['.vscode/'], '', '${cwd}/src/.vscode/settings.json', true, 'should match nested .vscode/'], [['/.vscode/'], '', '${cwd}/src/.vscode/settings.json', false, "shouldn't match nested .vscode/"], [['**/.vscode/'], '', '${cwd}/src/.vscode/settings.json', true, 'should match nested .vscode/'], [['/User/user/Library/**'], '', '${cwd}/src/User/user/Library/settings.json', false, 'No match'], [['/User/user/Library/**'], '', '${cwd}/User/user/Library/settings.json', true, 'Match system root'], // Special characters [['#'], '', '/User/code/src/settings.json', false, 'Only comments'], [[' #'], '', '/User/code/src/settings.json', false, 'Only comments'], [['#', '*.json', '#'], '', '${cwd}/User/code/src/settings.json', true, 'Comments'], [['#', '*.json', '*.js'], '', '${cwd}/User/code/src/settings.js', true, 'Multiple patterns'], ['#\n*.json\n*.js', '', '${cwd}/User/code/src/settings.js', true, 'Multiple patterns'], ['#\n*.json\n*.jsx', '', '${cwd}/User/code/src/settings.js', false, 'Multiple patterns'], [['#', '**/src/', '*.js'], '', '${cwd}/User/code/src/settings.js', true, 'Multiple patterns'], [['{*.js,*.json}'], '', '${cwd}/User/code/src/settings.js', true, 'Braces'], [['{src,dist}'], '', '${cwd}/User/code/src/settings.json', true, 'Braces'], [['{src,dist}'], '', '${cwd}/User/code/dist/settings.json', true, 'Braces'], [['{src,dist}'], '', '${cwd}/User/code/distribution/settings.json', false, 'Braces'], [['**/{src,dist}/**'], '', '${cwd}/User/code/src/settings.json', true, 'Braces'], [['**/{src,dist}/**'], '', '${cwd}/User/code/dist/settings.json', true, 'Braces'], [['**/{src,dist}/**'], '', '${cwd}/User/code/lib/settings.json', false, 'Braces'], [['{*.js,*.json}'], '', '${cwd}/User/code/src/settings.js', true, 'Braces'], [['(src|dist)'], '', '${cwd}/User/code/src/settings.json', true, 'Parens'], [['(src|dist)'], '', '${cwd}/User/code/dist/settings.json', true, 'Parens'], [['(src|dist)'], '', '${cwd}/User/code/distribution/settings.json', false, 'Parens'], [['**/(src|dist)/**'], '', '${cwd}/User/code/src/settings.json', true, 'Parens'], [['**/(src|dist)/**'], '', '${cwd}/User/code/dist/settings.json', true, 'Parens'], [['**/(src|dist)/**'], '', '${cwd}/User/code/lib/settings.json', false, 'Parens'], [['#', '**/dist/', '*.js'], '', '${cwd}/User/code/src/settings.js', true, 'Multiple patterns'], [['#', '**/dist/', '*.js'], '', '${cwd}/User/code/src/settings.json', false, 'Multiple patterns'], [['#', '**/dist/', '*.js*'], '', '${cwd}/User/code/src/settings.json', true, 'Multiple patterns'], [['settings.js'], '', '${cwd}/User/code/src/settings.js', true, 'settings.js'], [['!settings.js'], '', '${cwd}/User/code/src/settings.js', false, 'Negations'], [['!!settings.js'], '', '${cwd}/User/code/src/settings.js', true, 'Negations'], [['!!!settings.js'], '', '${cwd}/User/code/src/settings.js', false, 'Negations'], [['!/**/settings.js'], '', '${cwd}/User/code/src/settings.js', false, 'Negations'], [['!!/**/settings.js'], '', '${cwd}/User/code/src/settings.js', true, 'Negations'], [['!**/settings.js'], '', '${cwd}/User/code/src/settings.js', false, 'Negations'], [['#', '**/src/', '*.js', '!**/settings.js'], '', '${cwd}/User/code/src/settings.js', false, 'Negations'], ]; return limit ? testCases.slice(from, from + limit) : testCases; } function isWin32(pathInstance: PathInterface): boolean { if (pathInstance.normalize === path.win32.normalize) { return true; } if (pathInstance.normalize === path.posix.normalize) { return false; } throw new Error('Unknown pathInstance'); } /** alias for `expected.objectContaining` */ function eo<T>(obj: T): T { return expect.objectContaining(obj); } /** Helper for function for building expected GlobPatterns */ function p(glob: string, root?: string): GlobPatternWithOptionalRoot { return eo(root ? { glob, root } : { glob }); } function resolvePattern(p: GlobPattern, path: PathInterface): GlobPattern; function resolvePattern(p: GlobPattern[], path: PathInterface): GlobPattern[]; function resolvePattern(p: GlobPattern | GlobPattern[], path: PathInterface): GlobPattern | GlobPattern[]; function resolvePattern(p: GlobPattern | GlobPattern[], path: PathInterface): GlobPattern | GlobPattern[] { if (Array.isArray(p)) { return p.map((g) => resolvePattern(g, path)); } if (typeof p === 'string' || p.root === undefined) { return p; } return { ...p, root: path.resolve(p.root), }; }
the_stack
import { qs } from 'url-parse'; import matchRoute from '../../../../../common/utils/match-route'; import { matchRouteCache } from '../../../../../common/utils/match-route/utils'; const Noop = () => null; const DEFAULT_QUERY_PARAMS = {}; const { parse } = qs; describe('matchRoute', () => { beforeEach(() => { matchRouteCache.cache.clear(); }); describe('pathname', () => { it('should match a pathname without a query string', () => { const route = { path: '/foo/:bar', component: Noop }; // @ts-ignore expect(matchRoute([route], '/foo/abc', DEFAULT_QUERY_PARAMS)).toEqual({ route, match: { params: { bar: 'abc' }, isExact: true, path: '/foo/:bar', query: {}, url: '/foo/abc', }, }); // @ts-ignore expect(matchRoute([route], '/baz/abc', DEFAULT_QUERY_PARAMS)).toBeNull(); }); it('should return the first route that is a match', () => { const routeA = { path: '/foo/:bar', component: Noop }; const routeB = { path: '/foo/:baz', component: Noop }; expect( // @ts-ignore matchRoute([routeA, routeB], '/foo/abc', DEFAULT_QUERY_PARAMS) ).toMatchObject({ route: routeA, }); expect( // @ts-ignore matchRoute([routeB], '/foo/abc', DEFAULT_QUERY_PARAMS) ).toMatchObject({ route: routeB, }); }); }); describe('pathname with basePath', () => { it('should match a pathname when basePath is empty', () => { const route = { path: '/foo/:bar', component: Noop }; expect( // @ts-ignore matchRoute([route], '/foo/abc', DEFAULT_QUERY_PARAMS) ).toEqual({ route, match: { params: { bar: 'abc' }, isExact: true, path: '/foo/:bar', query: {}, url: '/foo/abc', }, }); expect( // @ts-ignore matchRoute([route], '/hello/foo/abc', DEFAULT_QUERY_PARAMS) ).toBeNull(); expect( // @ts-ignore matchRoute([route], '/baz/abc', DEFAULT_QUERY_PARAMS) ).toBeNull(); }); it('should match a basePath+pathname without a query string', () => { const route = { path: '/foo/:bar', component: Noop }; const basePath = '/base'; expect( // @ts-ignore matchRoute([route], '/base/foo/abc', DEFAULT_QUERY_PARAMS, basePath) ).toEqual({ route, match: { params: { bar: 'abc' }, isExact: true, path: '/base/foo/:bar', query: {}, url: '/base/foo/abc', }, }); expect( // @ts-ignore matchRoute([route], '/foo/abc', DEFAULT_QUERY_PARAMS, basePath) ).toBeNull(); expect( // @ts-ignore matchRoute([route], '/base/baz/abc', DEFAULT_QUERY_PARAMS, basePath) ).toBeNull(); }); it('should return the first route that is a match', () => { const routeA = { path: '/foo/:bar', component: Noop }; const routeB = { path: '/foo/:baz', component: Noop }; const basePath = '/base'; expect( matchRoute( // @ts-ignore [routeA, routeB], '/base/foo/abc', DEFAULT_QUERY_PARAMS, basePath ) ).toMatchObject({ route: routeA, }); expect( // @ts-ignore matchRoute([routeB], '/base/foo/abc', DEFAULT_QUERY_PARAMS, basePath) ).toMatchObject({ route: routeB, }); }); }); describe('query', () => { it('should match query config requiring query name to be present', () => { const route = { path: '/abc/:bar', query: ['foo'], component: Noop, }; expect( // @ts-ignore matchRoute([route], '/abc/def', parse('?foo=baz&spa=awesome')) ).toMatchObject({ route, match: { query: { foo: 'baz', }, }, }); // @ts-ignore expect(matchRoute([route], '/abc/def', DEFAULT_QUERY_PARAMS)).toBeNull(); // @ts-ignore expect(matchRoute([route], '/abc/def', parse('?spa=awesome'))).toBeNull(); }); it('should match query config with multiple query params if all of them match', () => { const multiple = { path: '/abc/:bar', query: ['foo', 'spa'], component: Noop, }; expect( // @ts-ignore matchRoute([multiple], '/abc/def', parse('?foo=baz&spa=awesome')) ).toMatchObject({ route: multiple, }); // @ts-ignore expect(matchRoute([multiple], '/abc/def', parse('?foo=baz'))).toBeNull(); expect( // @ts-ignore matchRoute([multiple], '/abc/def', parse('?spa=awesome')) ).toBeNull(); }); it('should return same match object as matching pathname but with additional query object containing all query params', () => { const route = { path: '/abc/:bar', query: ['foo'], component: Noop, }; expect( // @ts-ignore matchRoute([route], '/abc/def', parse('?foo=baz&spa=awesome')) ).toEqual({ route, match: { params: { bar: 'def', }, query: { foo: 'baz', }, isExact: true, path: '/abc/:bar', url: '/abc/def', }, }); }); it('should match query config requiring query param to equal specific value', () => { const route = { path: '/abc/:bar', query: ['foo=baz'], component: Noop, }; expect( // @ts-ignore matchRoute([route], '/abc/def', parse('?foo=baz&spa=awesome')) ).toMatchObject({ route, match: { query: { foo: 'baz', }, }, }); // @ts-ignore expect(matchRoute([route], '/abc/def', DEFAULT_QUERY_PARAMS)).toBeNull(); expect( // @ts-ignore matchRoute([route], '/abc/def', parse('?foo=abc&spa=awesome')) ).toBeNull(); }); it('should match query config requiring query param to equal a regex value', () => { const route = { path: '/abc/:bar', query: ['foo=(plan.*)'], component: Noop, }; expect( // @ts-ignore matchRoute([route], '/abc/def', parse('?foo=plan&spa=awesome')) ).toMatchObject({ route, match: { query: { foo: 'plan', }, }, }); expect( // @ts-ignore matchRoute([route], '/abc/def', parse('?foo=planning&spa=awesome')) ).toMatchObject({ route, match: { query: { foo: 'planning', }, }, }); // @ts-ignore expect(matchRoute([route], '/abc/def', DEFAULT_QUERY_PARAMS)).toBeNull(); // @ts-ignore expect(matchRoute([route], '/abc/def', parse('?foo=pla'))).toBeNull(); const numberRegexRoute = { path: '/abc/:bar', query: ['spaAwesomeFactor=(\\d)'], component: Noop, }; expect( // @ts-ignore matchRoute([numberRegexRoute], '/abc/def', parse('spaAwesomeFactor=9')) ).toMatchObject({ route: numberRegexRoute, }); // Should be only one number expect( matchRoute( // @ts-ignore [numberRegexRoute], '/abc/def', parse('spaAwesomeFactor=10') ) ).toBeNull(); // Should be a number expect( matchRoute( // @ts-ignore [numberRegexRoute], '/abc/def', parse('spaAwesomeFactor=abc') ) ).toBeNull(); }); it('should match query params literally instead of as a regex when value does not start with parentheses', () => { const route = { path: '/abc/:bar', query: ['foo=plan.detail'], component: Noop, }; expect( // @ts-ignore matchRoute([route], '/abc/def', parse('?foo=plan.detail')) ).toMatchObject({ route, match: { query: { foo: 'plan.detail', }, }, }); expect( // @ts-ignore matchRoute([route], '/abc/def', parse('?foo=plansdetail')) ).toBeNull(); }); it('should match query config requiring query param to not equal a specific value', () => { const route = { path: '/abc/:bar', query: ['foo!=bar'], component: Noop, }; expect( // @ts-ignore matchRoute([route], '/abc/def', parse('?foo=baz&spa=awesome')) ).toMatchObject({ route, match: { query: { foo: 'baz', }, }, }); expect( // @ts-ignore matchRoute([route], '/abc/def', parse('?spa=awesome')) ).toMatchObject({ route, match: { query: {}, }, }); // @ts-ignore expect(matchRoute([route], '/abc/def', parse('?foo=bar'))).toBeNull(); }); it('should match query config requiring alternative params', () => { const route = { path: '/abc/:bar', query: ['foo|foo2'], component: Noop, }; expect( // @ts-ignore matchRoute([route], '/abc/def', parse('?foo=bar&spa=awesome')) ).toMatchObject({ route, match: { query: { foo: 'bar', }, }, }); // @ts-ignore expect(matchRoute([route], '/abc/def', parse('?foo2=1'))).toMatchObject({ route, match: { query: { foo2: '1', }, }, }); expect( // @ts-ignore matchRoute([route], '/abc/def', parse('?foo=bar&foo2=1')) ).toMatchObject({ route, match: { query: { foo: 'bar', foo2: '1', }, }, }); // @ts-ignore expect(matchRoute([route], '/abc/def', parse('?spa=awesome'))).toBeNull(); }); it('should match query config including optional params', () => { const route = { path: '/abc/:bar', query: ['foo', 'baz?', 'bar?=(\\d+)'], component: Noop, }; // @ts-ignore expect(matchRoute([route], '/abc/def', parse('?foo'))).toMatchObject({ route, match: { query: { foo: '', }, }, }); expect( // @ts-ignore matchRoute([route], '/abc/def', parse('?foo&baz=cool')) ).toMatchObject({ route, match: { query: { foo: '', baz: 'cool', }, }, }); expect( // @ts-ignore matchRoute([route], '/abc/def', parse('?foo&bar=1&baz=cool')) ).toMatchObject({ route, match: { query: { foo: '', bar: '1', baz: 'cool', }, }, }); expect( // @ts-ignore matchRoute([route], '/abc/def', parse('?foo&baz=cool&bar=cool')) ).toBeNull(); }); it('should match when the third argument is a string', () => { const route = { path: '/abc/:bar', query: ['foo', 'baz?', 'bar?=(\\d+)'], component: Noop, }; expect( // @ts-ignore matchRoute([route], '/abc/def', '?foo&bar=1&baz=cool') ).toMatchObject({ route, match: { query: { foo: '', bar: '1', baz: 'cool', }, }, }); }); it('should fail gracefully if passed invalid query string', () => { const route = { path: '/abc/:bar', query: ['foo'], component: Noop, }; // @ts-ignore expect(matchRoute([route], '/abc/def', parse('?badstring=%'))).toBeNull(); // @ts-ignore expect(matchRoute([route], '/abc/def', parse('?foo=%'))).toBeNull(); // @ts-ignore expect(matchRoute([route], '/abc/def', parse('?foo=%2'))).toBeNull(); }); it('should handle non-standard characters', () => { const route = { path: '/abc/:bar', query: ['foo', 'bar?'], component: Noop, }; expect( // @ts-ignore matchRoute([route], '/abc/def', parse('?foo=a%0Ab&bar=3')) // %0A == line feed ).toMatchObject({ route, match: { query: { foo: 'a\nb', bar: '3', }, }, }); expect( // @ts-ignore matchRoute([route], '/abc/def', parse('?foo=a%00b&bar=3')) // %00 == null ).toMatchObject({ route, match: { query: { foo: 'a\0b', bar: '3', }, }, }); expect( // @ts-ignore matchRoute([route], '/abc/def', parse('?foo=prøve&bar=3')) // ø is non-ascii character ).toMatchObject({ route, match: { query: { foo: 'prøve', bar: '3', }, }, }); }); }); });
the_stack
import {promisifyAll, callbackifyAll} from '@google-cloud/promisify'; import {Instance} from './instance'; import { IOperation, LongRunningCallback, RequestCallback, ResourceCallback, NormalCallback, CLOUD_RESOURCE_HEADER, } from './common'; import {EnumKey, Spanner, RequestConfig, TranslateEnumKeys} from '.'; import { grpc, CallOptions, Metadata, Operation as GaxOperation, } from 'google-gax'; import {DateStruct, PreciseDate} from '@google-cloud/precise-date'; import {google as databaseAdmin} from '../protos/protos'; import {common as p} from 'protobufjs'; export type CreateBackupCallback = LongRunningCallback<Backup>; export interface CreateBackupGaxOperation extends GaxOperation { // Overridden with more specific type for CreateBackup operation metadata: Metadata & databaseAdmin.spanner.admin.database.v1.ICreateBackupMetadata; } export type CreateBackupResponse = [ Backup, CreateBackupGaxOperation, IOperation ]; export interface CreateBackupOptions { databasePath: string; expireTime: string | number | p.ITimestamp | PreciseDate; versionTime?: string | number | p.ITimestamp | PreciseDate; encryptionConfig?: databaseAdmin.spanner.admin.database.v1.ICreateBackupEncryptionConfig; gaxOptions?: CallOptions; } /** * IBackup structure with backup state enum translated to string form. */ type IBackupTranslatedEnum = TranslateEnumKeys< databaseAdmin.spanner.admin.database.v1.IBackup, 'state', typeof databaseAdmin.spanner.admin.database.v1.Backup.State >; export type GetMetadataResponse = [IBackupTranslatedEnum]; type GetMetadataCallback = RequestCallback<IBackupTranslatedEnum>; type UpdateExpireTimeCallback = RequestCallback<databaseAdmin.spanner.admin.database.v1.IBackup>; type DeleteCallback = RequestCallback<databaseAdmin.protobuf.IEmpty>; interface BackupRequest { ( config: RequestConfig, callback: ResourceCallback<GaxOperation, IOperation> ): void; <T>(config: RequestConfig, callback: RequestCallback<T>): void; } export type GetStateCallback = NormalCallback< EnumKey<typeof databaseAdmin.spanner.admin.database.v1.Backup.State> >; export type GetExpireTimeCallback = NormalCallback<PreciseDate>; export type ExistsCallback = NormalCallback<boolean>; /** * The {@link Backup} class represents a Cloud Spanner backup. * * Create a `Backup` object to interact with or create a Cloud Spanner backup. * * @class * * @example * ``` * const {Spanner} = require('@google-cloud/spanner'); * const spanner = new Spanner(); * const instance = spanner.instance('my-instance'); * const backup = instance.backup('my-backup'); * ``` */ class Backup { id: string; formattedName_: string; instanceFormattedName_: string; resourceHeader_: {[k: string]: string}; request: BackupRequest; metadata?: databaseAdmin.spanner.admin.database.v1.IBackup; constructor(instance: Instance, name: string) { this.request = instance.request; this.instanceFormattedName_ = instance.formattedName_; this.formattedName_ = Backup.formatName_(instance.formattedName_, name); this.id = this.formattedName_.split('/').pop() || ''; this.resourceHeader_ = { [CLOUD_RESOURCE_HEADER]: this.instanceFormattedName_, }; } /** * @typedef {object} CreateBackupOptions * @property {string} databasePath The database path. * @property {string|number|google.protobuf.Timestamp|external:PreciseDate} * expireTime The expire time of the backup. * @property {string|number|google.protobuf.Timestamp|external:PreciseDate} * versionTime Take a backup of the state of the database at this time. * @property {google.spanner.admin.database.v1.ICreateBackupEncryptionConfig} * encryptionConfig An encryption configuration describing the * encryption type and key resources in Cloud KMS to be used to encrypt * the backup. * @property {object} [gaxOptions] The request configuration options, * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. */ /** * @typedef {array} CreateBackupResponse * @property {Backup} 0 The new {@link Backup}. * @property {google.longrunning.Operation} 1 An {@link Operation} object that can be used to check * the status of the request. * @property {object} 2 The full API response. */ /** * @callback CreateBackupCallback * @param {?Error} err Request error, if any. * @param {Backup} backup The new {@link Backup}. * @param {google.longrunning.Operation} operation An {@link Operation} object that can be used to * check the status of the request. * @param {object} apiResponse The full API response. */ /** * Create a backup. * * @method Backup#create * @param {CreateBackupOptions} options Parameters for creating a backup. * @param {CallOptions} [options.gaxOptions] The request configuration * options, See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @param {CreateBackupCallback} [callback] Callback function. * @returns {Promise<CreateBackupResponse>} When resolved, the backup * operation will have started, but will not have necessarily completed. * * @example * ``` * const {Spanner} = require('@google-cloud/spanner'); * const spanner = new Spanner(); * const instance = spanner.instance('my-instance'); * const oneDay = 1000 * 60 * 60 * 24; * const expireTime = Date.now() + oneDay; * const versionTime = Date.now() - oneDay; * const backup = instance.backup('my-backup'); * const [, backupOperation] = await backup.create({ * databasePath: 'projects/my-project/instances/my-instance/databases/my-database', * expireTime: expireTime, * versionTime: versionTime, * encryptionConfig: { * encryptionType: 'CUSTOMER_MANAGED_ENCRYPTION', * kmsKeyName: 'projects/my-project-id/my-region/keyRings/my-key-ring/cryptoKeys/my-key', * }, * }); * // Await completion of the backup operation. * await backupOperation.promise(); * ``` */ create(options: CreateBackupOptions): Promise<CreateBackupResponse>; create(options: CreateBackupOptions, callback: CreateBackupCallback): void; create( options: CreateBackupOptions, callback?: CreateBackupCallback ): Promise<CreateBackupResponse> | void { const gaxOpts = options.gaxOptions; const reqOpts: databaseAdmin.spanner.admin.database.v1.ICreateBackupRequest = { parent: this.instanceFormattedName_, backupId: this.id, backup: { database: options.databasePath, expireTime: Spanner.timestamp(options.expireTime).toStruct(), name: this.formattedName_, }, }; if ('versionTime' in options) { reqOpts.backup!.versionTime = Spanner.timestamp( options.versionTime ).toStruct(); } if ( 'encryptionConfig' in options && (options as CreateBackupOptions).encryptionConfig ) { reqOpts.encryptionConfig = ( options as CreateBackupOptions ).encryptionConfig; } this.request( { client: 'DatabaseAdminClient', method: 'createBackup', reqOpts, gaxOpts, headers: this.resourceHeader_, }, (err, operation, resp) => { if (err) { callback!(err, null, null, resp); return; } callback!(null, this, operation, resp); } ); } /** * @typedef {array} GetMetadataResponse * @property {object} 0 The {@link Backup} metadata. * @property {object} 1 The full API response. */ /** * @callback GetMetadataCallback * @param {?Error} err Request error, if any. * @param {object} metadata The {@link Backup} metadata. * @param {object} apiResponse The full API response. */ /** * Retrieves backup's metadata. * * @see {@link #getState} * @see {@link #getExpireTime} * * @method Backup#getMetadata * @param {object} [gaxOptions] Request configuration options, * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @param {GetMetadataCallback} [callback] Callback function. * @returns {Promise<GetMetadataResponse>} * * @example * ``` * const {Spanner} = require('@google-cloud/spanner'); * const spanner = new Spanner(); * const instance = spanner.instance('my-instance'); * const backup = instance.backup('my-backup'); * const [backupInfo] = await backup.getMetadata(); * console.log(`${backupInfo.name}: size=${backupInfo.sizeBytes}`); * ``` */ getMetadata(gaxOptions?: CallOptions): Promise<GetMetadataResponse>; getMetadata(callback: GetMetadataCallback): void; getMetadata(gaxOptions: CallOptions, callback: GetMetadataCallback): void; getMetadata( gaxOptionsOrCallback?: CallOptions | GetMetadataCallback, cb?: GetMetadataCallback ): void | Promise<GetMetadataResponse> { const callback = typeof gaxOptionsOrCallback === 'function' ? (gaxOptionsOrCallback as GetMetadataCallback) : cb; const gaxOpts = typeof gaxOptionsOrCallback === 'object' ? (gaxOptionsOrCallback as CallOptions) : {}; const reqOpts: databaseAdmin.spanner.admin.database.v1.IGetBackupRequest = { name: this.formattedName_, }; this.request<IBackupTranslatedEnum>( { client: 'DatabaseAdminClient', method: 'getBackup', reqOpts, gaxOpts, headers: this.resourceHeader_, }, (err, response) => { if (response) { this.metadata = response; } callback!(err, response); } ); } /** * Retrieves the state of the backup. * * The backup state indicates if the backup has completed. * * @see {@link #getMetadata} * * @method Backup#getState * @param {GetStateCallback} [callback] Callback function. * @returns {Promise<EnumKey<typeof, databaseAdmin.spanner.admin.database.v1.Backup.State> | undefined>} * When resolved, contains the current state of the backup if it exists. * * @example * ``` * const {Spanner} = require('@google-cloud/spanner'); * const spanner = new Spanner(); * const instance = spanner.instance('my-instance'); * const backup = instance.backup('my-backup'); * const state = await backup.getState(); * const backupCompleted = (state === 'READY'); * ``` */ getState(): Promise< | EnumKey<typeof databaseAdmin.spanner.admin.database.v1.Backup.State> | undefined | null >; getState(callback: GetStateCallback): void; async getState(): Promise< | EnumKey<typeof databaseAdmin.spanner.admin.database.v1.Backup.State> | undefined | null > { const [backupInfo] = await this.getMetadata(); return backupInfo.state; } /** * Retrieves the expiry time of the backup. * * @see {@link #updateExpireTime} * @see {@link #getMetadata} * * @method Backup#getExpireTime * @returns {Promise<external:PreciseDate>} When resolved, contains the * current expire time of the backup if it exists. * * @example * ``` * const {Spanner} = require('@google-cloud/spanner'); * const spanner = new Spanner(); * const instance = spanner.instance('my-instance'); * const backup = instance.backup('my-backup'); * const expireTime = await backup.getExpireTime(); * console.log(`Backup expires on ${expireTime.toISOString()}`); * ``` */ getExpireTime(): Promise<PreciseDate | undefined>; getExpireTime(callback: GetExpireTimeCallback): void; async getExpireTime(): Promise<PreciseDate | undefined> { const [backupInfo] = await this.getMetadata(); return new PreciseDate(backupInfo.expireTime as DateStruct); } /** * Checks whether the backup exists. * * @see {@link #getMetadata} * * @method Backup#exists * @returns {Promise<boolean>} When resolved, contains true if the backup * exists and false if it does not exist. * * @example * ``` * const {Spanner} = require('@google-cloud/spanner'); * const spanner = new Spanner(); * const instance = spanner.instance('my-instance'); * const backup = instance.backup('my-backup'); * const alreadyExists = await backup.exists(); * console.log(`Does backup exist? ${alreadyExists}`); * ``` */ exists(): Promise<boolean>; exists(callback: ExistsCallback): void; async exists(): Promise<boolean> { try { // Attempt to read metadata to determine whether backup exists await this.getMetadata(); // Found therefore it exists return true; } catch (err) { if (err.code === grpc.status.NOT_FOUND) { return false; } // Some other error occurred, rethrow throw err; } } /** * @callback UpdateExpireTimeCallback * @param {?Error} err Request error, if any. * @param {google.spanner.admin.database.v1.IBackup} backup The updated * backup. */ /** * Sets the expiry time of a backup. * * @see {@link #getExpireTime} * * @method Backup#updateExpireTime * @param {string|number|google.protobuf.Timestamp|external:PreciseDate} * expireTime The expiry time to update with. * @param {object} [gaxOptions] Request configuration options, * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @param {UpdateExpireTimeCallback} [callback] Callback function. * @returns {Promise<google.spanner.admin.database.v1.IBackup>} When resolved, * the backup's expire time will have been updated. * * @example * ``` * const {Spanner} = require('@google-cloud/spanner'); * const spanner = new Spanner(); * const instance = spanner.instance('my-instance'); * const backup = instance.backup('my-backup'); * const oneDay = 1000 * 60 * 60 * 24; * const newExpireTime = Spanner.timestamp(Date.now() + oneDay); * await backup.updateExpireTime(newExpireTime); * ``` */ updateExpireTime( expireTime: string | number | p.ITimestamp | PreciseDate ): Promise<databaseAdmin.spanner.admin.database.v1.IBackup>; updateExpireTime( expireTime: string | number | p.ITimestamp | PreciseDate, gaxOptions?: CallOptions ): Promise<databaseAdmin.spanner.admin.database.v1.IBackup>; updateExpireTime( expireTime: string | number | p.ITimestamp | PreciseDate, callback: UpdateExpireTimeCallback ): void; updateExpireTime( expireTime: string | number | p.ITimestamp | PreciseDate, gaxOptions: CallOptions, callback: UpdateExpireTimeCallback ): void; updateExpireTime( expireTime: string | number | p.ITimestamp | PreciseDate, gaxOptionsOrCallback?: CallOptions | UpdateExpireTimeCallback, cb?: UpdateExpireTimeCallback ): void | Promise<databaseAdmin.spanner.admin.database.v1.IBackup> { const callback = typeof gaxOptionsOrCallback === 'function' ? (gaxOptionsOrCallback as UpdateExpireTimeCallback) : cb; const gaxOpts = typeof gaxOptionsOrCallback === 'object' ? (gaxOptionsOrCallback as CallOptions) : {}; const reqOpts: databaseAdmin.spanner.admin.database.v1.IUpdateBackupRequest = { backup: { name: this.formattedName_, expireTime: Spanner.timestamp(expireTime).toStruct(), }, updateMask: { paths: ['expire_time'], }, }; this.request<databaseAdmin.spanner.admin.database.v1.IBackup>( { client: 'DatabaseAdminClient', method: 'updateBackup', reqOpts, gaxOpts, headers: this.resourceHeader_, }, (err, response) => { callback!(err, response); } ); } /** * Deletes a backup. * * @method Backup#delete * @param {object} [gaxOptions] Request configuration options, * See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} * for more details. * @param {DeleteBackupCallback} [callback] Callback function. * @returns {Promise<void>} When resolved, the backup will have been deleted. * * @example * ``` * const {Spanner} = require('@google-cloud/spanner'); * const spanner = new Spanner(); * const instance = spanner.instance('my-instance'); * const backup = instance.backup('my-backup'); * await backup.delete(); * ``` */ delete(gaxOptions?: CallOptions): Promise<databaseAdmin.protobuf.IEmpty>; delete(callback: DeleteCallback): void; delete(gaxOptions: CallOptions, callback: DeleteCallback): void; delete( gaxOptionsOrCallback?: CallOptions | DeleteCallback, cb?: DeleteCallback ): void | Promise<databaseAdmin.protobuf.IEmpty> { const callback = typeof gaxOptionsOrCallback === 'function' ? (gaxOptionsOrCallback as DeleteCallback) : cb; const gaxOpts = typeof gaxOptionsOrCallback === 'object' ? (gaxOptionsOrCallback as CallOptions) : {}; const reqOpts: databaseAdmin.spanner.admin.database.v1.IDeleteBackupRequest = { name: this.formattedName_, }; this.request<databaseAdmin.spanner.admin.database.v1.IBackup>( { client: 'DatabaseAdminClient', method: 'deleteBackup', reqOpts, gaxOpts, headers: this.resourceHeader_, }, err => { callback!(err); } ); } /** * Format the backup name to include the instance name. * * @private * * @param {string} instanceName The formatted instance name. * @param {string} name The table name. * @returns {string} * * @example * ``` * Backup.formatName_( * 'projects/grape-spaceship-123/instances/my-instance', * 'my-backup' * ); * // 'projects/grape-spaceship-123/instances/my-instance/backups/my-backup' * ``` */ static formatName_(instanceName: string, name: string) { if (name.indexOf('/') > -1) { return name; } const backupName = name.split('/').pop(); return instanceName + '/backups/' + backupName; } } /*! Developer Documentation * * All async methods (except for streams) will return a Promise in the event * that a callback is omitted. */ promisifyAll(Backup, { exclude: ['getState', 'getExpireTime', 'exists'], }); /*! Developer Documentation * * All async methods (except for streams) will return a Promise in the event * that a callback is omitted. */ callbackifyAll(Backup, { exclude: ['create', 'getMetadata', 'updateExpireTime', 'delete'], }); /** * Reference to the {@link Backup} class. * @name module:@google-cloud/spanner.Backup * @see Backup */ export {Backup};
the_stack
import Page = require('../../../../../base/Page'); import Response = require('../../../../../http/response'); import V2010 = require('../../../V2010'); import { SerializableClass } from '../../../../../interfaces'; type SiprecStatus = 'in-progress'|'stopped'; type SiprecTrack = 'inbound_track'|'outbound_track'|'both_tracks'; type SiprecUpdateStatus = 'stopped'; /** * Initialize the SiprecList * * @param version - Version of the resource * @param accountSid - The SID of the Account that created this resource * @param callSid - The SID of the Call the resource is associated with */ declare function SiprecList(version: V2010, accountSid: string, callSid: string): SiprecListInstance; /** * Options to pass to update * * @property status - The status. Must have the value `stopped` */ interface SiprecInstanceUpdateOptions { status: SiprecUpdateStatus; } interface SiprecListInstance { /** * @param sid - sid of instance */ (sid: string): SiprecContext; /** * create a SiprecInstance * * @param callback - Callback to handle processed record */ create(callback?: (error: Error | null, item: SiprecInstance) => any): Promise<SiprecInstance>; /** * create a SiprecInstance * * @param opts - Options for request * @param callback - Callback to handle processed record */ create(opts?: SiprecListInstanceCreateOptions, callback?: (error: Error | null, item: SiprecInstance) => any): Promise<SiprecInstance>; /** * Constructs a siprec * * @param sid - The SID of the Siprec resource, or the `name` */ get(sid: string): SiprecContext; /** * Provide a user-friendly representation */ toJSON(): any; } /** * Options to pass to create * * @property connectorName - Unique name used when configuring the connector via Marketplace Add-on. * @property name - The name of this resource * @property parameter1.name - Parameter name * @property parameter1.value - Parameter value * @property parameter10.name - Parameter name * @property parameter10.value - Parameter value * @property parameter11.name - Parameter name * @property parameter11.value - Parameter value * @property parameter12.name - Parameter name * @property parameter12.value - Parameter value * @property parameter13.name - Parameter name * @property parameter13.value - Parameter value * @property parameter14.name - Parameter name * @property parameter14.value - Parameter value * @property parameter15.name - Parameter name * @property parameter15.value - Parameter value * @property parameter16.name - Parameter name * @property parameter16.value - Parameter value * @property parameter17.name - Parameter name * @property parameter17.value - Parameter value * @property parameter18.name - Parameter name * @property parameter18.value - Parameter value * @property parameter19.name - Parameter name * @property parameter19.value - Parameter value * @property parameter2.name - Parameter name * @property parameter2.value - Parameter value * @property parameter20.name - Parameter name * @property parameter20.value - Parameter value * @property parameter21.name - Parameter name * @property parameter21.value - Parameter value * @property parameter22.name - Parameter name * @property parameter22.value - Parameter value * @property parameter23.name - Parameter name * @property parameter23.value - Parameter value * @property parameter24.name - Parameter name * @property parameter24.value - Parameter value * @property parameter25.name - Parameter name * @property parameter25.value - Parameter value * @property parameter26.name - Parameter name * @property parameter26.value - Parameter value * @property parameter27.name - Parameter name * @property parameter27.value - Parameter value * @property parameter28.name - Parameter name * @property parameter28.value - Parameter value * @property parameter29.name - Parameter name * @property parameter29.value - Parameter value * @property parameter3.name - Parameter name * @property parameter3.value - Parameter value * @property parameter30.name - Parameter name * @property parameter30.value - Parameter value * @property parameter31.name - Parameter name * @property parameter31.value - Parameter value * @property parameter32.name - Parameter name * @property parameter32.value - Parameter value * @property parameter33.name - Parameter name * @property parameter33.value - Parameter value * @property parameter34.name - Parameter name * @property parameter34.value - Parameter value * @property parameter35.name - Parameter name * @property parameter35.value - Parameter value * @property parameter36.name - Parameter name * @property parameter36.value - Parameter value * @property parameter37.name - Parameter name * @property parameter37.value - Parameter value * @property parameter38.name - Parameter name * @property parameter38.value - Parameter value * @property parameter39.name - Parameter name * @property parameter39.value - Parameter value * @property parameter4.name - Parameter name * @property parameter4.value - Parameter value * @property parameter40.name - Parameter name * @property parameter40.value - Parameter value * @property parameter41.name - Parameter name * @property parameter41.value - Parameter value * @property parameter42.name - Parameter name * @property parameter42.value - Parameter value * @property parameter43.name - Parameter name * @property parameter43.value - Parameter value * @property parameter44.name - Parameter name * @property parameter44.value - Parameter value * @property parameter45.name - Parameter name * @property parameter45.value - Parameter value * @property parameter46.name - Parameter name * @property parameter46.value - Parameter value * @property parameter47.name - Parameter name * @property parameter47.value - Parameter value * @property parameter48.name - Parameter name * @property parameter48.value - Parameter value * @property parameter49.name - Parameter name * @property parameter49.value - Parameter value * @property parameter5.name - Parameter name * @property parameter5.value - Parameter value * @property parameter50.name - Parameter name * @property parameter50.value - Parameter value * @property parameter51.name - Parameter name * @property parameter51.value - Parameter value * @property parameter52.name - Parameter name * @property parameter52.value - Parameter value * @property parameter53.name - Parameter name * @property parameter53.value - Parameter value * @property parameter54.name - Parameter name * @property parameter54.value - Parameter value * @property parameter55.name - Parameter name * @property parameter55.value - Parameter value * @property parameter56.name - Parameter name * @property parameter56.value - Parameter value * @property parameter57.name - Parameter name * @property parameter57.value - Parameter value * @property parameter58.name - Parameter name * @property parameter58.value - Parameter value * @property parameter59.name - Parameter name * @property parameter59.value - Parameter value * @property parameter6.name - Parameter name * @property parameter6.value - Parameter value * @property parameter60.name - Parameter name * @property parameter60.value - Parameter value * @property parameter61.name - Parameter name * @property parameter61.value - Parameter value * @property parameter62.name - Parameter name * @property parameter62.value - Parameter value * @property parameter63.name - Parameter name * @property parameter63.value - Parameter value * @property parameter64.name - Parameter name * @property parameter64.value - Parameter value * @property parameter65.name - Parameter name * @property parameter65.value - Parameter value * @property parameter66.name - Parameter name * @property parameter66.value - Parameter value * @property parameter67.name - Parameter name * @property parameter67.value - Parameter value * @property parameter68.name - Parameter name * @property parameter68.value - Parameter value * @property parameter69.name - Parameter name * @property parameter69.value - Parameter value * @property parameter7.name - Parameter name * @property parameter7.value - Parameter value * @property parameter70.name - Parameter name * @property parameter70.value - Parameter value * @property parameter71.name - Parameter name * @property parameter71.value - Parameter value * @property parameter72.name - Parameter name * @property parameter72.value - Parameter value * @property parameter73.name - Parameter name * @property parameter73.value - Parameter value * @property parameter74.name - Parameter name * @property parameter74.value - Parameter value * @property parameter75.name - Parameter name * @property parameter75.value - Parameter value * @property parameter76.name - Parameter name * @property parameter76.value - Parameter value * @property parameter77.name - Parameter name * @property parameter77.value - Parameter value * @property parameter78.name - Parameter name * @property parameter78.value - Parameter value * @property parameter79.name - Parameter name * @property parameter79.value - Parameter value * @property parameter8.name - Parameter name * @property parameter8.value - Parameter value * @property parameter80.name - Parameter name * @property parameter80.value - Parameter value * @property parameter81.name - Parameter name * @property parameter81.value - Parameter value * @property parameter82.name - Parameter name * @property parameter82.value - Parameter value * @property parameter83.name - Parameter name * @property parameter83.value - Parameter value * @property parameter84.name - Parameter name * @property parameter84.value - Parameter value * @property parameter85.name - Parameter name * @property parameter85.value - Parameter value * @property parameter86.name - Parameter name * @property parameter86.value - Parameter value * @property parameter87.name - Parameter name * @property parameter87.value - Parameter value * @property parameter88.name - Parameter name * @property parameter88.value - Parameter value * @property parameter89.name - Parameter name * @property parameter89.value - Parameter value * @property parameter9.name - Parameter name * @property parameter9.value - Parameter value * @property parameter90.name - Parameter name * @property parameter90.value - Parameter value * @property parameter91.name - Parameter name * @property parameter91.value - Parameter value * @property parameter92.name - Parameter name * @property parameter92.value - Parameter value * @property parameter93.name - Parameter name * @property parameter93.value - Parameter value * @property parameter94.name - Parameter name * @property parameter94.value - Parameter value * @property parameter95.name - Parameter name * @property parameter95.value - Parameter value * @property parameter96.name - Parameter name * @property parameter96.value - Parameter value * @property parameter97.name - Parameter name * @property parameter97.value - Parameter value * @property parameter98.name - Parameter name * @property parameter98.value - Parameter value * @property parameter99.name - Parameter name * @property parameter99.value - Parameter value * @property statusCallback - Absolute URL of the status callback. * @property statusCallbackMethod - The http method for the status_callback. * @property track - One of `inbound_track`, `outbound_track`, `both_tracks`. */ interface SiprecListInstanceCreateOptions { connectorName?: string; name?: string; parameter1?: { name?: string; value?: string; }; parameter10?: { name?: string; value?: string; }; parameter11?: { name?: string; value?: string; }; parameter12?: { name?: string; value?: string; }; parameter13?: { name?: string; value?: string; }; parameter14?: { name?: string; value?: string; }; parameter15?: { name?: string; value?: string; }; parameter16?: { name?: string; value?: string; }; parameter17?: { name?: string; value?: string; }; parameter18?: { name?: string; value?: string; }; parameter19?: { name?: string; value?: string; }; parameter2?: { name?: string; value?: string; }; parameter20?: { name?: string; value?: string; }; parameter21?: { name?: string; value?: string; }; parameter22?: { name?: string; value?: string; }; parameter23?: { name?: string; value?: string; }; parameter24?: { name?: string; value?: string; }; parameter25?: { name?: string; value?: string; }; parameter26?: { name?: string; value?: string; }; parameter27?: { name?: string; value?: string; }; parameter28?: { name?: string; value?: string; }; parameter29?: { name?: string; value?: string; }; parameter3?: { name?: string; value?: string; }; parameter30?: { name?: string; value?: string; }; parameter31?: { name?: string; value?: string; }; parameter32?: { name?: string; value?: string; }; parameter33?: { name?: string; value?: string; }; parameter34?: { name?: string; value?: string; }; parameter35?: { name?: string; value?: string; }; parameter36?: { name?: string; value?: string; }; parameter37?: { name?: string; value?: string; }; parameter38?: { name?: string; value?: string; }; parameter39?: { name?: string; value?: string; }; parameter4?: { name?: string; value?: string; }; parameter40?: { name?: string; value?: string; }; parameter41?: { name?: string; value?: string; }; parameter42?: { name?: string; value?: string; }; parameter43?: { name?: string; value?: string; }; parameter44?: { name?: string; value?: string; }; parameter45?: { name?: string; value?: string; }; parameter46?: { name?: string; value?: string; }; parameter47?: { name?: string; value?: string; }; parameter48?: { name?: string; value?: string; }; parameter49?: { name?: string; value?: string; }; parameter5?: { name?: string; value?: string; }; parameter50?: { name?: string; value?: string; }; parameter51?: { name?: string; value?: string; }; parameter52?: { name?: string; value?: string; }; parameter53?: { name?: string; value?: string; }; parameter54?: { name?: string; value?: string; }; parameter55?: { name?: string; value?: string; }; parameter56?: { name?: string; value?: string; }; parameter57?: { name?: string; value?: string; }; parameter58?: { name?: string; value?: string; }; parameter59?: { name?: string; value?: string; }; parameter6?: { name?: string; value?: string; }; parameter60?: { name?: string; value?: string; }; parameter61?: { name?: string; value?: string; }; parameter62?: { name?: string; value?: string; }; parameter63?: { name?: string; value?: string; }; parameter64?: { name?: string; value?: string; }; parameter65?: { name?: string; value?: string; }; parameter66?: { name?: string; value?: string; }; parameter67?: { name?: string; value?: string; }; parameter68?: { name?: string; value?: string; }; parameter69?: { name?: string; value?: string; }; parameter7?: { name?: string; value?: string; }; parameter70?: { name?: string; value?: string; }; parameter71?: { name?: string; value?: string; }; parameter72?: { name?: string; value?: string; }; parameter73?: { name?: string; value?: string; }; parameter74?: { name?: string; value?: string; }; parameter75?: { name?: string; value?: string; }; parameter76?: { name?: string; value?: string; }; parameter77?: { name?: string; value?: string; }; parameter78?: { name?: string; value?: string; }; parameter79?: { name?: string; value?: string; }; parameter8?: { name?: string; value?: string; }; parameter80?: { name?: string; value?: string; }; parameter81?: { name?: string; value?: string; }; parameter82?: { name?: string; value?: string; }; parameter83?: { name?: string; value?: string; }; parameter84?: { name?: string; value?: string; }; parameter85?: { name?: string; value?: string; }; parameter86?: { name?: string; value?: string; }; parameter87?: { name?: string; value?: string; }; parameter88?: { name?: string; value?: string; }; parameter89?: { name?: string; value?: string; }; parameter9?: { name?: string; value?: string; }; parameter90?: { name?: string; value?: string; }; parameter91?: { name?: string; value?: string; }; parameter92?: { name?: string; value?: string; }; parameter93?: { name?: string; value?: string; }; parameter94?: { name?: string; value?: string; }; parameter95?: { name?: string; value?: string; }; parameter96?: { name?: string; value?: string; }; parameter97?: { name?: string; value?: string; }; parameter98?: { name?: string; value?: string; }; parameter99?: { name?: string; value?: string; }; statusCallback?: string; statusCallbackMethod?: string; track?: SiprecTrack; } interface SiprecPayload extends SiprecResource, Page.TwilioResponsePayload { } interface SiprecResource { account_sid: string; call_sid: string; date_updated: Date; name: string; sid: string; status: SiprecStatus; } interface SiprecSolution { accountSid?: string; callSid?: string; } declare class SiprecContext { /** * Initialize the SiprecContext * * @param version - Version of the resource * @param accountSid - The SID of the Account that created this resource * @param callSid - The SID of the Call the resource is associated with * @param sid - The SID of the Siprec resource, or the `name` */ constructor(version: V2010, accountSid: string, callSid: string, sid: string); /** * Provide a user-friendly representation */ toJSON(): any; /** * update a SiprecInstance * * @param opts - Options for request * @param callback - Callback to handle processed record */ update(opts: SiprecInstanceUpdateOptions, callback?: (error: Error | null, items: SiprecInstance) => any): Promise<SiprecInstance>; } declare class SiprecInstance extends SerializableClass { /** * Initialize the SiprecContext * * @param version - Version of the resource * @param payload - The instance payload * @param accountSid - The SID of the Account that created this resource * @param callSid - The SID of the Call the resource is associated with * @param sid - The SID of the Siprec resource, or the `name` */ constructor(version: V2010, payload: SiprecPayload, accountSid: string, callSid: string, sid: string); private _proxy: SiprecContext; accountSid: string; callSid: string; dateUpdated: Date; name: string; sid: string; status: SiprecStatus; /** * Provide a user-friendly representation */ toJSON(): any; /** * update a SiprecInstance * * @param opts - Options for request * @param callback - Callback to handle processed record */ update(opts: SiprecInstanceUpdateOptions, callback?: (error: Error | null, items: SiprecInstance) => any): Promise<SiprecInstance>; } declare class SiprecPage extends Page<V2010, SiprecPayload, SiprecResource, SiprecInstance> { /** * Initialize the SiprecPage * * @param version - Version of the resource * @param response - Response from the API * @param solution - Path solution */ constructor(version: V2010, response: Response<string>, solution: SiprecSolution); /** * Build an instance of SiprecInstance * * @param payload - Payload response from the API */ getInstance(payload: SiprecPayload): SiprecInstance; /** * Provide a user-friendly representation */ toJSON(): any; } export { SiprecContext, SiprecInstance, SiprecInstanceUpdateOptions, SiprecList, SiprecListInstance, SiprecListInstanceCreateOptions, SiprecPage, SiprecPayload, SiprecResource, SiprecSolution, SiprecStatus, SiprecTrack, SiprecUpdateStatus }
the_stack
import { BorderModel, FontModel, ColorMappingModel, LeafItemSettingsModel } from '../model/base-model'; import { createElement, compile, merge, isNullOrUndefined, remove } from '@syncfusion/ej2-base'; import { SvgRenderer } from '@syncfusion/ej2-svg-base'; import { Alignment, LabelPosition } from '../utils/enum'; import { TreeMap } from '../treemap'; import { IShapes } from '../model/interface'; import { ExportType } from '../utils/enum'; /** * Create the class for size */ export class Size { /** * height of the size */ public height: number; /** * width of the size */ public width: number; constructor(width: number, height: number) { this.width = width; this.height = height; } } export function stringToNumber(value: string, containerSize: number): number { if (value !== null && value !== undefined) { return value.indexOf('%') !== -1 ? (containerSize / 100) * parseInt(value, 10) : parseInt(value, 10); } return null; } /** * Internal use of type rect * * @private */ export class Rect { public x: number; public y: number; public height: number; public width: number; constructor(x: number, y: number, width: number, height: number) { this.x = x; this.y = y; this.width = width; this.height = height; } } /** * Internal use of rectangle options * * @private */ export class RectOption { public id: string; public fill: string; public x: number; public y: number; public height: number; public width: number; public opacity: number; public stroke: string; public ['stroke-width']: number; public ['stroke-dasharray']: string; constructor( id: string, fill: string, border: BorderModel, opacity: number, rect: Rect, dashArray?: string ) { this.y = rect.y; this.x = rect.x; this.height = rect.height; this.width = rect.width; this.id = id; this.fill = fill; this.opacity = opacity; this.stroke = border.color; this['stroke-width'] = border.width; this['stroke-dasharray'] = dashArray; } } export class PathOption { public id: string; public opacity: number; public fill: string; public stroke: string; public ['stroke-width']: number; public ['stroke-dasharray']: string; public d: string; constructor( id: string, fill: string, width: number, color: string, opacity?: number, dashArray?: string, d?: string ) { this.id = id; this.opacity = opacity; this.fill = fill; this.stroke = color; this['stroke-width'] = width; this['stroke-dasharray'] = dashArray; this.d = d; } } /** * Function to measure the height and width of the text. * * @param {string} text - Specifies the text. * @param {FontModel} font - Specifies the font. * @param {string} id - Specifies the id. * @returns {Size} - Returns the size. * @private */ export function measureText(text: string, font: FontModel): Size { let measureObject: HTMLElement = document.getElementById('treeMapMeasureText'); if (measureObject === null) { measureObject = createElement('text', { id: 'treeMapMeasureText' }); document.body.appendChild(measureObject); } measureObject.innerHTML = text; measureObject.style.position = 'absolute'; measureObject.style.fontSize = font.size; measureObject.style.fontWeight = font.fontWeight; measureObject.style.fontStyle = font.fontStyle; measureObject.style.fontFamily = font.fontFamily; measureObject.style.visibility = 'hidden'; measureObject.style.top = '-100'; measureObject.style.left = '0'; measureObject.style.whiteSpace = 'nowrap'; // For bootstrap line height issue measureObject.style.lineHeight = 'normal'; return new Size(measureObject.clientWidth, measureObject.clientHeight); } /** * Internal use of text options * * @private */ export class TextOption { public anchor: string; public id: string; public transform: string = ''; public x: number; public y: number; public text: string | string[]; public baseLine: string = 'auto'; public connectorText: string; constructor( id?: string, x?: number, y?: number, anchor?: string, text?: string | string[], transform: string = '', baseLine?: string, connectorText?: string ) { this.id = id; this.text = text; this.transform = transform; this.anchor = anchor; this.x = x; this.y = y; this.baseLine = baseLine; this.connectorText = connectorText; } } /** * Trim the title text * * @param {number} maxWidth - Specifies the maximum width * @param {string} text - Specifies the text * @param {FontModel} font - Specifies the font * @returns {string} - Returns the string * @private */ export function textTrim(maxWidth: number, text: string, font: FontModel): string { let label: string = text; let size: number = measureText(text, font).width; if (size > maxWidth) { const textLength: number = text.length; for (let i: number = textLength - 1; i >= 0; --i) { label = text.substring(0, i) + '...'; size = measureText(label, font).width; if (size <= maxWidth || label.length < 4) { if (label.length < 4) { label = ' '; } return label; } } } return label; } /** * Map internal class for Point */ export class Location { /** * To calculate x value for location */ public x: number; /** * To calculate y value for location */ public y: number; constructor(x: number, y: number) { this.x = x; this.y = y; } } /** * Method to calculate x position of title */ export function findPosition(location: Rect, alignment: Alignment, textSize: Size, type: string): Location { let x: number; switch (alignment) { case 'Near': x = location.x; break; case 'Center': x = (type === 'title') ? (location.width / 2 - textSize.width / 2) : ((location.x + (location.width / 2)) - textSize.width / 2); break; case 'Far': x = (type === 'title') ? (location.width - location.y - textSize.width) : ((location.x + location.width) - textSize.width); break; } const y: number = (type === 'title') ? location.y + (textSize.height / 2) : ((location.y + location.height / 2) + textSize.height / 2); return new Location(x, y); } export function createTextStyle( // eslint-disable-next-line @typescript-eslint/no-explicit-any renderer: SvgRenderer, renderOptions: any, text: string ): HTMLElement { const htmlObject: HTMLElement = <HTMLElement>renderer.createText(renderOptions, text); htmlObject.setAttributeNS('http://www.w3.org/XML/1998/namespace', 'xml:space', 'preserve'); htmlObject.style['user-select'] = 'none'; htmlObject.style['-moz-user-select'] = 'none'; htmlObject.style['-webkit-touch-callout'] = 'none'; htmlObject.style['-webkit-user-select'] = 'none'; htmlObject.style['-khtml-user-select'] = 'none'; htmlObject.style['-ms-user-select'] = 'none'; htmlObject.style['-o-user-select'] = 'none'; return htmlObject; } /** * Internal rendering of text * * @param {TextOption} options - Specifies the text option * @param {FontModel} font - Specifies the font model * @param {string} color - Specifies the color * @param {HTMLElement | Element} parent - Specifes the html element * @param {boolean} isMinus - Specifies the boolean value * @returns {Element} - Returns the element * @private */ export function renderTextElement( options: TextOption, font: FontModel, color: string, parent: HTMLElement | Element, isMinus: boolean = false ): Element { // eslint-disable-next-line @typescript-eslint/no-explicit-any const renderOptions: any = { 'font-size': font.size, 'font-style': font.fontStyle, 'font-family': font.fontFamily, 'font-weight': font.fontWeight, 'text-anchor': options.anchor, 'transform': options.transform, 'opacity': font.opacity, 'dominant-baseline': options.baseLine, 'id': options.id, 'x': options.x, 'y': options.y, 'fill': color }; const text: string = typeof options.text === 'string' ? options.text : isMinus ? options.text[options.text.length - 1] : options.text[0]; let tspanElement: Element; const renderer: SvgRenderer = new SvgRenderer(''); let height: number; let htmlObject: HTMLElement; const breadCrumbText: boolean = !isNullOrUndefined(text) && !isNullOrUndefined(options.connectorText) ? (text.search(options.connectorText[1]) >= 0) : false; if (breadCrumbText) { const drilledLabel: string = text; const spacing: number = 5; const drillLevelText: string[] = drilledLabel.split('#'); for (let z: number = 0; z < drillLevelText.length; z++) { let drillText: string = (drillLevelText[z].search(options.connectorText) !== -1 && !isNullOrUndefined(options.connectorText)) ? options.connectorText : drillLevelText[z]; renderOptions['id'] = options.id + '_' + z; htmlObject = createTextStyle(renderer, renderOptions, drillText); if (z % 2 === 0 && z !== 0) { const re: RegExp = /\s+/g; drillText = drillText.replace(re, '&nbsp'); } const size: Size = measureText(drillText, font); renderOptions['x'] = z !== 0 ? renderOptions['x'] + size.width : renderOptions['x'] + size.width + spacing; parent.appendChild(htmlObject); } } else { htmlObject = createTextStyle(renderer, renderOptions, text); parent.appendChild(htmlObject); } if (typeof options.text !== 'string' && options.text.length > 1) { for (let i: number = 1, len: number = options.text.length; i < len; i++) { height = (measureText(options.text[i], font).height); tspanElement = renderer.createTSpan( { 'x': options.x, 'id': options.id, 'y': (options.y) + (i * height) }, options.text[i]); htmlObject.appendChild(tspanElement); } parent.appendChild(htmlObject); } return htmlObject; } export function setItemTemplateContent(targetId: string, targetElement: Element, contentItemTemplate: string): void { const itemSelect: string = targetId.split('_RectPath')[0]; let itemTemplate: Element; if (targetId.indexOf('_LabelTemplate') > -1) { itemTemplate = targetElement; } else { itemTemplate = document.querySelector('#' + itemSelect + '_LabelTemplate'); } if (!isNullOrUndefined(itemTemplate)) { itemTemplate.innerHTML = contentItemTemplate; } } export function getElement(id: string): Element { return document.getElementById(id); } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function itemsToOrder(a: any, b: any): number { return a['weight'] === b['weight'] ? 0 : a['weight'] < b['weight'] ? 1 : -1; } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function isContainsData(source: string[], pathName: string, processData: any, treemap: TreeMap): boolean { let isExist: boolean = false; let name: string = ''; let path: string; const leaf: LeafItemSettingsModel = treemap.leafItemSettings; for (let i: number = 0; i < source.length; i++) { path = treemap.levels[i] ? treemap.levels[i].groupPath : leaf.labelPath ? leaf.labelPath : treemap.weightValuePath; const data: string = processData[path] || 'undefined'; if (source[i] === data) { name += data + (i === source.length - 1 ? '' : '#'); if (name === pathName) { isExist = true; break; } } } return isExist; } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function findChildren(data: any): any { // eslint-disable-next-line @typescript-eslint/no-explicit-any let children: any; if (data) { const keys: string[] = Object.keys(data); children = {}; for (let i: number = 0; i < keys.length; i++) { if (data[keys[i]] instanceof Array) { children['values'] = data[keys[i]]; children['key'] = keys[i]; break; } } } return children; } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function findHightLightItems(data: any, items: string[], mode: string, treeMap: TreeMap): string[] { if (mode === 'Child') { items.push(data['levelOrderName']); // eslint-disable-next-line @typescript-eslint/no-explicit-any const children: any[] = findChildren(data)['values']; if (children && children.length > 0) { for (let i: number = 0; i < children.length; i++) { if (items.indexOf(children[i]['levelOrderName']) === -1) { items.push(children[i]['levelOrderName']); } } for (let j: number = 0; j < children.length; j++) { findHightLightItems(children[j], items, mode, treeMap); } } } else if (mode === 'Parent') { if (typeof data['levelOrderName'] === 'string' && items.indexOf(data['levelOrderName']) === -1) { items.push(data['levelOrderName']); findHightLightItems(data['parent'], items, mode, treeMap); } } else if (mode === 'All') { const parentName: string = (data['levelOrderName'] as string).split('#')[0]; // eslint-disable-next-line @typescript-eslint/no-explicit-any let currentItem: any; for (let i: number = 0; i < treeMap.layout.renderItems.length; i++) { currentItem = treeMap.layout.renderItems[i]; if ((currentItem['levelOrderName']).indexOf(parentName) > -1 && items.indexOf(currentItem['levelOrderName']) === -1) { items.push(currentItem['levelOrderName']); } } } else { items.push(data['levelOrderName']); } return items; } /** * Function to compile the template function for maps. * * @param {string} template - Specifies the template * @returns {Function} - Returns the template function * @private */ // eslint-disable-next-line @typescript-eslint/no-explicit-any export function getTemplateFunction(template: string): any { // eslint-disable-next-line @typescript-eslint/no-explicit-any let templateFn: any = null; // eslint-disable-next-line @typescript-eslint/no-explicit-any let e: any; try { if (document.querySelectorAll(template).length) { templateFn = compile(document.querySelector(template).innerHTML.trim()); } } catch (e) { templateFn = compile(template); } return templateFn; } /** * @private * @param {HTMLCollection} element - Specifies the element * @param {string} labelId - Specifies the label id * @param {Object} data - Specifies the data * @returns {HTMLElement} - Returns the element */ // eslint-disable-next-line @typescript-eslint/no-explicit-any export function convertElement(element: HTMLCollection, labelId: string, data: any): HTMLElement { const childElement: HTMLElement = createElement('div', { id: labelId, styles: 'position: absolute;pointer-events: auto;' }); let elementLength: number = element.length; while (elementLength > 0) { childElement.appendChild(element[0]); elementLength--; } let templateHtml: string = childElement.innerHTML; // eslint-disable-next-line @typescript-eslint/no-explicit-any const keys: any[] = Object.keys(data); for (let i: number = 0; i < keys.length; i++) { templateHtml = templateHtml.replace(new RegExp('{{:' + <string>keys[i] + '}}', 'g'), data[keys[i].toString()]); } childElement.innerHTML = templateHtml; return childElement; } export function findLabelLocation(rect: Rect, position: LabelPosition, labelSize: Size, type: string, treemap: TreeMap): Location { const location: Location = new Location(0, 0); const padding: number = 5; const paddings: number = 2; const elementRect: ClientRect = treemap.element.getBoundingClientRect(); const x: number = (type === 'Template') ? treemap.areaRect.x : 0; const y: number = (type === 'Template') ? treemap.areaRect.y : 0; location.x = (Math.abs(x - ((position.indexOf('Left') > -1) ? rect.x + padding : !(position.indexOf('Right') > -1) ? rect.x + ((rect.width / 2) - (labelSize.width / 2)) : (rect.x + rect.width) - labelSize.width))) - paddings; if (treemap.enableDrillDown && (treemap.renderDirection === 'BottomLeftTopRight' || treemap.renderDirection === 'BottomRightTopLeft')) { location.y = Math.abs((rect.y + rect.height) - labelSize.height + padding); } else { location.y = Math.abs(y - ((position.indexOf('Top') > -1) ? (type === 'Template' ? rect.y : rect.y + labelSize.height) : !(position.indexOf('Bottom') > -1) ? type === 'Template' ? (rect.y + ((rect.height / 2) - (labelSize.height / 2))) : (rect.y + (rect.height / 2) + labelSize.height / 4) : (rect.y + rect.height) - labelSize.height)); } return location; } export function measureElement(element: HTMLElement, parentElement: HTMLElement): Size { const size: Size = new Size(0, 0); parentElement.appendChild(element); size.height = element.offsetHeight; size.width = element.offsetWidth; const measureElementId: HTMLElement = document.getElementById(element.id); measureElementId.parentNode.removeChild(measureElementId); return size; } export function getArea(rect: Rect): number { return (rect.width - rect.x) * (rect.height - rect.y); } export function getShortestEdge(input: Rect): number { const container: Rect = convertToContainer(input); const width: number = container.width; const height: number = container.height; const result: number = Math.min(width, height); return result; } export function convertToContainer(rect: Rect): Rect { const x: number = rect.x; const y: number = rect.y; const width: number = rect.width; const height: number = rect.height; return { x: x, y: y, width: width - x, height: height - y }; } export function convertToRect(container: Rect): Rect { const xOffset: number = container.x; const yOffset: number = container.y; const width: number = container.width; const height: number = container.height; return { x: xOffset, y: yOffset, width: xOffset + width, height: yOffset + height }; } export function getMousePosition(pageX: number, pageY: number, element: Element): Location { const elementRect: ClientRect = element.getBoundingClientRect(); const pageXOffset: number = element.ownerDocument.defaultView.pageXOffset; const pageYOffset: number = element.ownerDocument.defaultView.pageYOffset; const clientTop: number = element.ownerDocument.documentElement.clientTop; const clientLeft: number = element.ownerDocument.documentElement.clientLeft; const positionX: number = elementRect.left + pageXOffset - clientLeft; const positionY: number = elementRect.top + pageYOffset - clientTop; return new Location((pageX - positionX), (pageY - positionY)); } export function colorMap( colorMapping: ColorMappingModel[], equalValue: string, // eslint-disable-next-line @typescript-eslint/no-explicit-any value: number | string, weightValuePath: number): any { let fill: string; const paths: string[] = []; let opacity: string; if (isNullOrUndefined(equalValue) && (isNullOrUndefined(value) && isNaN(<number>value))) { return null; } for (let i: number = 0; i < colorMapping.length; i++) { let isEqualColor: boolean = false; const dataValue: number = <number>value; if (!isNullOrUndefined(colorMapping[i].from) && !isNullOrUndefined(colorMapping[i].to) && !isNullOrUndefined(colorMapping[i].value)) { if ((value >= colorMapping[i].from && colorMapping[i].to >= value) && (colorMapping[i].value === equalValue)) { isEqualColor = true; if (Object.prototype.toString.call(colorMapping[i].color) === '[object Array]') { fill = !isEqualColor ? colorCollections(colorMapping[i], dataValue) : colorMapping[i].color[0]; } else { fill = <string>colorMapping[i].color; } } } else if ((!isNullOrUndefined(colorMapping[i].from) && !isNullOrUndefined(colorMapping[i].to)) || !isNullOrUndefined((colorMapping[i].value))) { if ((value >= colorMapping[i].from && colorMapping[i].to >= value) || (colorMapping[i].value === equalValue)) { if (colorMapping[i].value === equalValue) { isEqualColor = true; } if (Object.prototype.toString.call(colorMapping[i].color) === '[object Array]') { fill = !isEqualColor ? colorCollections(colorMapping[i], dataValue) : colorMapping[i].color[0]; } else { fill = <string>colorMapping[i].color; } } } if (((value >= colorMapping[i].from && value <= colorMapping[i].to) || (colorMapping[i].value === equalValue)) && !isNullOrUndefined(colorMapping[i].minOpacity) && !isNullOrUndefined(colorMapping[i].maxOpacity) && fill) { opacity = deSaturationColor(weightValuePath, colorMapping[i], fill, value as number); } if ((fill === '' || isNullOrUndefined(fill)) && isNullOrUndefined(colorMapping[i].from) && isNullOrUndefined(colorMapping[i].to) && isNullOrUndefined(colorMapping[i].minOpacity) && isNullOrUndefined(colorMapping[i].maxOpacity) && isNullOrUndefined(colorMapping[i].value)) { fill = (Object.prototype.toString.call(colorMapping[i].color) === '[object Array]') ? <string>colorMapping[i].color[0] : <string>colorMapping[i].color; } opacity = !isNullOrUndefined(opacity) ? opacity : '1'; paths.push(fill); } for (let j: number = paths.length - 1; j >= 0; j--) { fill = paths[j]; j = (fill) ? -1 : j; } return { fill: fill, opacity: opacity }; } export function deSaturationColor( weightValuePath: number, colorMapping: ColorMappingModel, color: string, rangeValue: number): string { let opacity: number = 1; if ((rangeValue >= colorMapping.from && rangeValue <= colorMapping.to)) { const ratio: number = (rangeValue - colorMapping.from) / (colorMapping.to - colorMapping.from); opacity = (ratio * (colorMapping.maxOpacity - colorMapping.minOpacity)) + colorMapping.minOpacity; } return opacity.toString(); } export function colorCollections(colorMap: ColorMappingModel, value: number): string { const gradientFill: string = getColorByValue(colorMap, value); return gradientFill; } export function rgbToHex(r: number, g: number, b: number): string { return '#' + componentToHex(r) + componentToHex(g) + componentToHex(b); } export function getColorByValue(colorMap: ColorMappingModel, value: number): string { let color: string = ''; let rbg: ColorValue; if (Number(value) === colorMap.from) { color = colorMap.color[0]; } else if (Number(value) === colorMap.to) { color = colorMap.color[colorMap.color.length - 1]; } else { rbg = getGradientColor(Number(value), colorMap); color = rgbToHex(rbg.r, rbg.g, rbg.b); } return color; } export function getGradientColor(value: number, colorMap: ColorMappingModel): ColorValue { const previousOffset: number = colorMap.from; const nextOffset: number = colorMap.to; let percent: number = 0; let prev1: string; const full: number = nextOffset - previousOffset; let midColor: string; let midreturn: ColorValue; percent = (value - previousOffset) / full; let previousColor: string; let nextColor: string; if (colorMap.color.length <= 2) { previousColor = colorMap.color[0].charAt(0) === '#' ? colorMap.color[0] : colorNameToHex(colorMap.color[0]); nextColor = colorMap.color[colorMap.color.length - 1].charAt(0) === '#' ? colorMap.color[colorMap.color.length - 1] : colorNameToHex(colorMap.color[colorMap.color.length - 1]); } else { previousColor = colorMap.color[0].charAt(0) === '#' ? colorMap.color[0] : colorNameToHex(colorMap.color[0]); nextColor = colorMap.color[colorMap.color.length - 1].charAt(0) === '#' ? colorMap.color[colorMap.color.length - 1] : colorNameToHex(colorMap.color[colorMap.color.length - 1]); const a: number = full / (colorMap.color.length - 1); let b: number; let c: number; const length: number = colorMap.color.length - 1; // eslint-disable-next-line @typescript-eslint/no-explicit-any const splitColorValueOffset: any[] = []; let splitColor: any = {}; for (let j: number = 1; j < length; j++) { c = j * a; b = previousOffset + c; splitColor = { b: b, color: colorMap.color[j] }; splitColorValueOffset.push(splitColor); } for (let i: number = 0; i < splitColorValueOffset.length; i++) { if (previousOffset <= value && value <= splitColorValueOffset[i]['b'] && i === 0) { midColor = splitColorValueOffset[i]['color'].charAt(0) === '#' ? splitColorValueOffset[i]['color'] : colorNameToHex(splitColorValueOffset[i]['color']); nextColor = midColor; percent = value < splitColorValueOffset[i]['b'] ? 1 - Math.abs((value - splitColorValueOffset[i]['b']) / a) : (value - splitColorValueOffset[i]['b']) / a; } else if (splitColorValueOffset[i]['b'] <= value && value <= nextOffset && i === (splitColorValueOffset.length - 1)) { midColor = splitColorValueOffset[i]['color'].charAt(0) === '#' ? splitColorValueOffset[i]['color'] : colorNameToHex(splitColorValueOffset[i]['color']); previousColor = midColor; percent = value < splitColorValueOffset[i]['b'] ? 1 - Math.abs((value - splitColorValueOffset[i]['b']) / a) : (value - splitColorValueOffset[i]['b']) / a; } if (i !== splitColorValueOffset.length - 1 && i < splitColorValueOffset.length) { if (splitColorValueOffset[i]['b'] <= value && value <= splitColorValueOffset[i + 1]['b']) { midColor = splitColorValueOffset[i]['color'].charAt(0) === '#' ? splitColorValueOffset[i]['color'] : colorNameToHex(splitColorValueOffset[i]['color']); previousColor = midColor; nextColor = splitColorValueOffset[i + 1]['color'].charAt(0) === '#' ? splitColorValueOffset[i + 1]['color'] : colorNameToHex(splitColorValueOffset[i + 1]['color']); percent = Math.abs((value - splitColorValueOffset[i + 1]['b'])) / a; } } } } return getPercentageColor(percent, previousColor, nextColor); } export function getPercentageColor(percent: number, previous: string, next: string): ColorValue { const nextColor: string = next.split('#')[1]; const prevColor: string = previous.split('#')[1]; const r: number = getPercentage(percent, parseInt(prevColor.substr(0, 2), 16), parseInt(nextColor.substr(0, 2), 16)); const g: number = getPercentage(percent, parseInt(prevColor.substr(2, 2), 16), parseInt(nextColor.substr(2, 2), 16)); const b: number = getPercentage(percent, parseInt(prevColor.substr(4, 2), 16), parseInt(nextColor.substr(4, 2), 16)); return new ColorValue(r, g, b); } export function getPercentage(percent: number, previous: number, next: number): number { const full: number = next - previous; return Math.round((previous + (full * percent))); } export function wordWrap(maximumWidth: number, dataLabel: string, font: FontModel): string[] { const textCollection: string[] = dataLabel.split(' '); let label: string = ''; const labelCollection: string[] = []; let text: string; for (let i: number = 0, len: number = textCollection.length; i < len; i++) { text = textCollection[i]; if (measureText(label.concat(text), font).width < maximumWidth) { label = label.concat((label === '' ? '' : ' ') + text); } else { if (label !== '') { labelCollection.push(textTrim(maximumWidth, label, font)); label = text; } else { labelCollection.push(textTrim(maximumWidth, text, font)); text = ''; } } if (label && i === len - 1) { labelCollection.push(textTrim(maximumWidth, label, font)); } } return labelCollection; } export function textWrap(maxWidth: number, label: string, font: FontModel): string[] { const text: string = label; const resultText: string[] = []; let currentLength: number = 0; let totalWidth: number = measureText(label, font).width; const totalLength: number = label.length; if (maxWidth >= totalWidth) { resultText.push(label); return resultText; } else { for (let i: number = label.length; i > currentLength; i--) { const sliceString: string = label.slice(currentLength, i); totalWidth = measureText(sliceString, font).width; if (totalWidth <= maxWidth) { resultText.push(sliceString); currentLength += sliceString.length; if (totalLength === currentLength) { return resultText; } i = totalLength + 1; } } } return resultText; } /** * hide function * * @param {number} maxWidth - Specifies the maximum width * @param {number} maxHeight - Specifies the maximum height * @param {string} text - Specifies the text * @param {FontModel} font - Specifies the font * @returns {string} - Returns the hideText */ export function hide(maxWidth: number, maxHeight: number, text: string, font: FontModel): string { let hideText: string = text; const textSize: Size = measureText(text, font); hideText = (textSize.width > maxWidth || textSize.height > maxHeight) ? ' ' : text; return hideText; } export function orderByArea(a: number, b: number): number { if (a['itemArea'] === b['itemArea']) { return 0; } else if (a['itemArea'] < b['itemArea']) { return 1; } return -1; } export function maintainSelection(treemap: TreeMap, element: Element, className: string): void { const elementId: string[] = treemap.levelSelection; if (elementId) { for (let index: number = 0; index < elementId.length; index++) { if (element.getAttribute('id') === elementId[index]) { if (element.childElementCount > 0) { element.children[0].setAttribute('class', className); applyOptions( element.childNodes[0] as SVGPathElement, { border: treemap.selectionSettings.border, fill: treemap.selectionSettings.fill, opacity: treemap.selectionSettings.opacity } ); } } else { element.setAttribute('class', ''); } } } } export function legendMaintain(treemap: TreeMap, legendGroup: Element): void { const elementId: string[] = treemap.legendId; if (elementId) { for (let i: number = 0; i < elementId.length; i++) { for (let j: number = 0; j < legendGroup.childElementCount; j++) { if (legendGroup.childNodes[j]['id'] === elementId[i]) { (legendGroup.childNodes[j] as SVGRectElement).setAttribute('fill', treemap.selectionSettings.fill); (legendGroup.childNodes[j] as SVGRectElement).setAttribute('stroke', treemap.selectionSettings.border.color); (legendGroup.childNodes[j] as SVGRectElement).setAttribute('stroke-width', (treemap.selectionSettings.border.width).toString()); (legendGroup.childNodes[j] as SVGRectElement).setAttribute('opacity', treemap.selectionSettings.opacity); } } } } } export function removeClassNames(elements: HTMLCollection, type: string, treemap: TreeMap): void { let opacity: string; const process: boolean = true; let element: SVGPathElement; let stroke: string; let strokeWidth: string; let fill: string; // eslint-disable-next-line @typescript-eslint/no-explicit-any let options: any = {}; for (let j: number = 0; j < elements.length; j++) { element = isNullOrUndefined(elements[j].childNodes[0] as SVGPathElement) ? elements[j] as SVGPathElement : elements[j].childNodes[0] as SVGPathElement; options = treemap.layout.renderItems[element.id.split('_')[6]]['options']; applyOptions(element, options); elements[j].classList.remove(type); j -= 1; } } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function applyOptions(element: SVGPathElement, options: any): void { element.setAttribute('opacity', options['opacity']); if (!isNullOrUndefined(options['fill'])) { element.setAttribute('fill', options['fill']); } element.setAttribute('stroke', options['border']['color']); element.setAttribute('stroke-width', options['border']['width']); } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function textFormatter(format: string, data: any, treemap: TreeMap): string { if (isNullOrUndefined(format)) { return null; } const keys: string[] = Object.keys(data); for (const key of keys) { format = format.split('${' + key + '}').join(formatValue(data[key], treemap).toString()); } return format; } export function formatValue(value: number, treemap: TreeMap): string | number { // eslint-disable-next-line @typescript-eslint/no-explicit-any let formatValue: string | number; let formatFunction: any; if (treemap.format && !isNaN(Number(value))) { formatFunction = treemap.intl.getNumberFormat( { format: treemap.format, useGrouping: treemap.useGroupingSeparator }); formatValue = formatFunction(Number(value)); } else { formatValue = value; } return formatValue ? formatValue : ''; } /** * @private */ export class ColorValue { public r: number; public g: number; public b: number; constructor(r?: number, g?: number, b?: number) { this.r = r; this.g = g; this.b = b; } } /** * @param {ColorValue} value - Specfies the color value * @returns {string} - Returns the string * @private */ export function convertToHexCode(value: ColorValue): string { return '#' + componentToHex(value.r) + componentToHex(value.g) + componentToHex(value.b); } /** * @param {number} value - Specifes the value * @returns {string} - Returns the string * @private */ export function componentToHex(value: number): string { const hex: string = value.toString(16); return hex.length === 1 ? '0' + hex : hex; } /** * @param {string} hex - Specifies the hex value * @returns {ColorValue} - Returns the color value * @private */ export function convertHexToColor(hex: string): ColorValue { const result: RegExpExecArray = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? new ColorValue(parseInt(result[1], 16), parseInt(result[2], 16), parseInt(result[3], 16)) : new ColorValue(255, 255, 255); } /** * @param {string} color - Specifies the color * @returns {string} - Returns the string * @private */ export function colorNameToHex(color: string): string { color = color === 'transparent' ? 'white' : color; const element: HTMLElement = document.getElementById('treeMapMeasureText'); element.style.color = color; color = window.getComputedStyle(element).color; const exp: RegExp = /^(rgb|hsl)(a?)[(]\s*([\d.]+\s*%?)\s*,\s*([\d.]+\s*%?)\s*,\s*([\d.]+\s*%?)\s*(?:,\s*([\d.]+)\s*)?[)]$/; const isRGBValue: RegExpExecArray = exp.exec(color); return convertToHexCode( new ColorValue(parseInt(isRGBValue[3], 10), parseInt(isRGBValue[4], 10), parseInt(isRGBValue[5], 10)) ); } /** * @param {Location} location - Specifies the location * @param {string} shape - Specifies the shape * @param {Size} size - Specifies the size * @param {string} url - Specifies the url * @param {PathOption} options - Specifies the options * @param {string} label - Specifies the label * @returns {Element} - Returns the element * @private */ export function drawSymbol(location: Location, shape: string, size: Size, url: string, options: PathOption, label: string): Element { const functionName: string = 'Path'; const svgRenderer: SvgRenderer = new SvgRenderer(''); const temp: IShapes = renderLegendShape(location, size, shape, options, url); const htmlElement: Element = svgRenderer['draw' + temp.functionName](temp.renderOption); htmlElement.setAttribute('aria-label', label); return htmlElement; } /** * @param {Location} location - Specifies the location * @param {Size} size - Specifies the size * @param {string} shape - Specifies the shape * @param {PathOption} options - Specifies the path option * @param {string} url - Specifies the string * @returns {IShapes} - Returns the shapes * @private */ export function renderLegendShape(location: Location, size: Size, shape: string, options: PathOption, url: string): IShapes { let renderPath: string; let functionName: string = 'Path'; const shapeWidth: number = size.width; const shapeHeight: number = size.height; const shapeX: number = location.x; const shapeY: number = location.y; const x: number = location.x + (-shapeWidth / 2); const y: number = location.y + (-shapeHeight / 2); switch (shape) { case 'Circle': case 'Bubble': functionName = 'Ellipse'; merge(options, { 'rx': shapeWidth / 2, 'ry': shapeHeight / 2, 'cx': shapeX, 'cy': shapeY }); break; case 'VerticalLine': renderPath = 'M' + ' ' + shapeX + ' ' + (shapeY + (shapeHeight / 2)) + ' ' + 'L' + ' ' + shapeX + ' ' + (shapeY + (-shapeHeight / 2)); merge(options, { 'd': renderPath }); break; case 'Diamond': renderPath = 'M' + ' ' + x + ' ' + shapeY + ' ' + 'L' + ' ' + shapeX + ' ' + (shapeY + (-shapeHeight / 2)) + ' ' + 'L' + ' ' + (shapeX + (shapeWidth / 2)) + ' ' + shapeY + ' ' + 'L' + ' ' + shapeX + ' ' + (shapeY + (shapeHeight / 2)) + ' ' + 'L' + ' ' + x + ' ' + shapeY + ' z'; merge(options, { 'd': renderPath }); break; case 'Rectangle': renderPath = 'M' + ' ' + x + ' ' + (shapeY + (-shapeHeight / 2)) + ' ' + 'L' + ' ' + (shapeX + (shapeWidth / 2)) + ' ' + (shapeY + (-shapeHeight / 2)) + ' ' + 'L' + ' ' + (shapeX + (shapeWidth / 2)) + ' ' + (shapeY + (shapeHeight / 2)) + ' ' + 'L' + ' ' + x + ' ' + (shapeY + (shapeHeight / 2)) + ' ' + 'L' + ' ' + x + ' ' + (shapeY + (-shapeHeight / 2)) + ' z'; merge(options, { 'd': renderPath }); break; case 'Triangle': renderPath = 'M' + ' ' + x + ' ' + (shapeY + (shapeHeight / 2)) + ' ' + 'L' + ' ' + shapeX + ' ' + (shapeY + (-shapeHeight / 2)) + ' ' + 'L' + ' ' + (shapeX + (shapeWidth / 2)) + ' ' + (shapeY + (shapeHeight / 2)) + ' ' + 'L' + ' ' + x + ' ' + (shapeY + (shapeHeight / 2)) + ' z'; merge(options, { 'd': renderPath }); break; case 'InvertedTriangle': renderPath = 'M' + ' ' + (shapeX + (shapeWidth / 2)) + ' ' + (shapeY - (shapeHeight / 2)) + ' ' + 'L' + ' ' + shapeX + ' ' + (shapeY + (shapeHeight / 2)) + ' ' + 'L' + ' ' + (shapeX - (shapeWidth / 2)) + ' ' + (shapeY - (shapeHeight / 2)) + ' ' + 'L' + ' ' + (shapeX + (shapeWidth / 2)) + ' ' + (shapeY - (shapeHeight / 2)) + ' z'; merge(options, { 'd': renderPath }); break; case 'Pentagon': // eslint-disable-next-line no-case-declarations const eq: number = 72; // eslint-disable-next-line no-case-declarations let xValue: number; // eslint-disable-next-line no-case-declarations let yValue: number; for (let i: number = 0; i <= 5; i++) { xValue = (shapeWidth / 2) * Math.cos((Math.PI / 180) * (i * eq)); yValue = (shapeWidth / 2) * Math.sin((Math.PI / 180) * (i * eq)); if (i === 0) { renderPath = 'M' + ' ' + (shapeX + xValue) + ' ' + (shapeY + yValue) + ' '; } else { renderPath = renderPath.concat('L' + ' ' + (shapeX + xValue) + ' ' + (shapeY + yValue) + ' '); } } renderPath = renderPath.concat('Z'); merge(options, { 'd': renderPath }); break; case 'Star': renderPath = 'M ' + (location.x + size.width / 3) + ' ' + (location.y - size.height / 2) + ' L ' + (location.x - size.width / 2) + ' ' + (location.y + size.height / 6) + ' L ' + (location.x + size.width / 2) + ' ' + (location.y + size.height / 6) + ' L ' + (location.x - size.width / 3) + ' ' + (location.y - size.height / 2) + ' L ' + location.x + ' ' + (location.y + size.height / 2) + ' L ' + (location.x + size.width / 3) + ' ' + (location.y - size.height / 2) + ' Z'; merge(options, { 'd': renderPath }); break; case 'Cross': renderPath = 'M' + ' ' + x + ' ' + shapeY + ' ' + 'L' + ' ' + (shapeX + (shapeWidth / 2)) + ' ' + shapeY + ' ' + 'M' + ' ' + shapeX + ' ' + (shapeY + (shapeHeight / 2)) + ' ' + 'L' + ' ' + shapeX + ' ' + (shapeY + (-shapeHeight / 2)); merge(options, { 'd': renderPath }); break; case 'Image': functionName = 'Image'; merge(options, { 'href': url, 'height': shapeHeight, 'width': shapeWidth, x: x, y: y }); break; } return { renderOption: options, functionName: functionName }; } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function isParentItem(data: any[], item: any): boolean { let isParentItem: boolean = false; for (let j: number = 0; j < data.length; j++) { if (item['levelOrderName'] === data[j]['levelOrderName']) { isParentItem = true; break; } } return isParentItem; } /** * Ajax support for treemap */ export class TreeMapAjax { /** options for data */ // eslint-disable-next-line @typescript-eslint/no-explicit-any public dataOptions: string | any; /** type of data */ public type: string; /** async value */ public async: boolean; /** type of the content */ public contentType: string; /** sending data */ // eslint-disable-next-line @typescript-eslint/no-explicit-any public sendData: string | any; // eslint-disable-next-line @typescript-eslint/no-explicit-any constructor(options: string | any, type?: string, async?: boolean, contentType?: string, sendData?: string | any) { this.dataOptions = options; this.type = type || 'GET'; this.async = async || true; this.contentType = contentType; this.sendData = sendData; } } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function removeShape(collection: any[], value: string): void { if (collection.length > 0) { for (let i: number = 0; i < collection.length; i++) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const item: any = collection[i]; setColor(item['legendEle'], item['oldFill'], item['oldOpacity'], item['oldBorderColor'], item['oldBorderWidth']); } } } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function removeLegend(collection: any[], value: string): void { if (collection.length > 0) { for (let j: number = 0; j < collection.length; j++) { // eslint-disable-next-line @typescript-eslint/no-explicit-any const item: any = collection[j]; setColor(item['legendEle'], item['oldFill'], item['oldOpacity'], item['oldBorderColor'], item['oldBorderWidth']); const dataCount: number = item['ShapeCollection']['Elements'].length; for (let k: number = 0; k < dataCount; k++) { setColor( item['ShapeCollection']['Elements'][k], item['shapeOldFill'], item['shapeOldOpacity'], item['shapeOldBorderColor'], item['shapeOldBorderWidth']); } } } } export function setColor(element: Element, fill: string, opacity: string, borderColor: string, borderWidth: string): void { element.setAttribute('fill', fill); element.setAttribute('opacity', opacity); element.setAttribute('stroke', borderColor); element.setAttribute('stroke-width', borderWidth); } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function removeSelectionWithHighlight(collection: any[], element: any[], treemap: TreeMap): void { removeShape(collection, 'highlight'); element = []; removeClassNames(document.getElementsByClassName('treeMapHighLight'), 'treeMapHighLight', treemap); } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function getLegendIndex(length: number, item: any, treemap: TreeMap): number { let index: number; for (let i: number = 0; i < length; i++) { const dataLength: number = treemap.treeMapLegendModule.legendCollections[i]['legendData'].length; for (let j: number = 0; j < dataLength; j++) { if (treemap.treeMapLegendModule.legendCollections[i]['legendData'][j]['levelOrderName'] === item['levelOrderName']) { index = i; break; } } } return index; } export function pushCollection( // eslint-disable-next-line @typescript-eslint/no-explicit-any collection: any[], index: number, number: number, legendElement: Element, shapeElement: Element, // eslint-disable-next-line @typescript-eslint/no-explicit-any renderItems: any[], legendCollection: any[]): void { collection.push({ legendEle: legendElement, oldFill: legendCollection[index]['legendFill'], oldOpacity: legendCollection[index]['opacity'], oldBorderColor: legendCollection[index]['borderColor'], oldBorderWidth: legendCollection[index]['borderWidth'], shapeElement: shapeElement, shapeOldFill: renderItems[number]['options']['fill'], shapeOldOpacity: renderItems[number]['options']['opacity'], shapeOldBorderColor: renderItems[number]['options']['border']['color'], shapeOldBorderWidth: renderItems[number]['options']['border']['width'] }); } /** * To trigger the download element * * @param {string} fileName - Specifies the file name * @param {ExportType} type - Specifies the type * @param {string} url - Specifies the url * @param {boolean} isDownload - Specifies the boolean value * @returns {void} */ export function triggerDownload(fileName: string, type: ExportType, url: string, isDownload: boolean): void { createElement('a', { attrs: { 'download': fileName + '.' + (type as string).toLocaleLowerCase(), 'href': url } }).dispatchEvent(new MouseEvent(isDownload ? 'click' : 'move', { view: window, bubbles: false, cancelable: true })); } export function removeElement(id: string): void { const element: Element = document.getElementById(id); return element ? remove(element) : null; }
the_stack
import * as pulumi from "@pulumi/pulumi"; import * as utilities from "../utilities"; /** * A Dialogflow agent is a virtual agent that handles conversations with your end-users. It is a natural language * understanding module that understands the nuances of human language. Dialogflow translates end-user text or audio * during a conversation to structured data that your apps and services can understand. You design and build a Dialogflow * agent to handle the types of conversations required for your system. * * To get more information about Agent, see: * * * [API documentation](https://cloud.google.com/dialogflow/docs/reference/rest/v2/projects/agent) * * How-to Guides * * [Official Documentation](https://cloud.google.com/dialogflow/docs/) * * ## Example Usage * ### Dialogflow Agent Full * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const fullAgent = new gcp.diagflow.Agent("full_agent", { * apiVersion: "API_VERSION_V2_BETA_1", * avatarUri: "https://cloud.google.com/_static/images/cloud/icons/favicons/onecloud/super_cloud.png", * classificationThreshold: 0.3, * defaultLanguageCode: "en", * description: "Example description.", * displayName: "dialogflow-agent", * enableLogging: true, * matchMode: "MATCH_MODE_ML_ONLY", * supportedLanguageCodes: [ * "fr", * "de", * "es", * ], * tier: "TIER_STANDARD", * timeZone: "America/New_York", * }); * ``` * * ## Import * * Agent can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:diagflow/agent:Agent default {{project}} * ``` */ export class Agent extends pulumi.CustomResource { /** * Get an existing Agent 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?: AgentState, opts?: pulumi.CustomResourceOptions): Agent { return new Agent(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:diagflow/agent:Agent'; /** * Returns true if the given object is an instance of Agent. 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 Agent { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Agent.__pulumiType; } /** * API version displayed in Dialogflow console. If not specified, V2 API is assumed. Clients are free to query * different service endpoints for different API versions. However, bots connectors and webhook calls will follow * the specified API version. * * API_VERSION_V1: Legacy V1 API. * * API_VERSION_V2: V2 API. * * API_VERSION_V2_BETA_1: V2beta1 API. * Possible values are `API_VERSION_V1`, `API_VERSION_V2`, and `API_VERSION_V2_BETA_1`. */ public readonly apiVersion!: pulumi.Output<string>; /** * The URI of the agent's avatar, which are used throughout the Dialogflow console. When an image URL is entered * into this field, the Dialogflow will save the image in the backend. The address of the backend image returned * from the API will be shown in the [avatarUriBackend] field. */ public readonly avatarUri!: pulumi.Output<string | undefined>; /** * The URI of the agent's avatar as returned from the API. Output only. To provide an image URL for the agent avatar, the * [avatarUri] field can be used. */ public /*out*/ readonly avatarUriBackend!: pulumi.Output<string>; /** * To filter out false positive results and still get variety in matched natural language inputs for your agent, * you can tune the machine learning classification threshold. If the returned score value is less than the threshold * value, then a fallback intent will be triggered or, if there are no fallback intents defined, no intent will be * triggered. The score values range from 0.0 (completely uncertain) to 1.0 (completely certain). If set to 0.0, the * default of 0.3 is used. */ public readonly classificationThreshold!: pulumi.Output<number | undefined>; /** * The default language of the agent as a language tag. [See Language Support](https://cloud.google.com/dialogflow/docs/reference/language) * for a list of the currently supported language codes. This field cannot be updated after creation. */ public readonly defaultLanguageCode!: pulumi.Output<string>; /** * The description of this agent. The maximum length is 500 characters. If exceeded, the request is rejected. */ public readonly description!: pulumi.Output<string | undefined>; /** * The name of this agent. */ public readonly displayName!: pulumi.Output<string>; /** * Determines whether this agent should log conversation queries. */ public readonly enableLogging!: pulumi.Output<boolean | undefined>; /** * Determines how intents are detected from user queries. * * MATCH_MODE_HYBRID: Best for agents with a small number of examples in intents and/or wide use of templates * syntax and composite entities. * * MATCH_MODE_ML_ONLY: Can be used for agents with a large number of examples in intents, especially the ones * using @sys.any or very large developer entities. * Possible values are `MATCH_MODE_HYBRID` and `MATCH_MODE_ML_ONLY`. */ public readonly matchMode!: pulumi.Output<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ public readonly project!: pulumi.Output<string>; /** * The list of all languages supported by this agent (except for the defaultLanguageCode). */ public readonly supportedLanguageCodes!: pulumi.Output<string[] | undefined>; /** * The agent tier. If not specified, TIER_STANDARD is assumed. * * TIER_STANDARD: Standard tier. * * TIER_ENTERPRISE: Enterprise tier (Essentials). * * TIER_ENTERPRISE_PLUS: Enterprise tier (Plus). * NOTE: Due to consistency issues, the provider will not read this field from the API. Drift is possible between * the the provider state and Dialogflow if the agent tier is changed outside of the provider. */ public readonly tier!: pulumi.Output<string | undefined>; /** * The time zone of this agent from the [time zone database](https://www.iana.org/time-zones), e.g., America/New_York, * Europe/Paris. */ public readonly timeZone!: pulumi.Output<string>; /** * Create a Agent 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: AgentArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: AgentArgs | AgentState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as AgentState | undefined; inputs["apiVersion"] = state ? state.apiVersion : undefined; inputs["avatarUri"] = state ? state.avatarUri : undefined; inputs["avatarUriBackend"] = state ? state.avatarUriBackend : undefined; inputs["classificationThreshold"] = state ? state.classificationThreshold : undefined; inputs["defaultLanguageCode"] = state ? state.defaultLanguageCode : undefined; inputs["description"] = state ? state.description : undefined; inputs["displayName"] = state ? state.displayName : undefined; inputs["enableLogging"] = state ? state.enableLogging : undefined; inputs["matchMode"] = state ? state.matchMode : undefined; inputs["project"] = state ? state.project : undefined; inputs["supportedLanguageCodes"] = state ? state.supportedLanguageCodes : undefined; inputs["tier"] = state ? state.tier : undefined; inputs["timeZone"] = state ? state.timeZone : undefined; } else { const args = argsOrState as AgentArgs | undefined; if ((!args || args.defaultLanguageCode === undefined) && !opts.urn) { throw new Error("Missing required property 'defaultLanguageCode'"); } if ((!args || args.displayName === undefined) && !opts.urn) { throw new Error("Missing required property 'displayName'"); } if ((!args || args.timeZone === undefined) && !opts.urn) { throw new Error("Missing required property 'timeZone'"); } inputs["apiVersion"] = args ? args.apiVersion : undefined; inputs["avatarUri"] = args ? args.avatarUri : undefined; inputs["classificationThreshold"] = args ? args.classificationThreshold : undefined; inputs["defaultLanguageCode"] = args ? args.defaultLanguageCode : undefined; inputs["description"] = args ? args.description : undefined; inputs["displayName"] = args ? args.displayName : undefined; inputs["enableLogging"] = args ? args.enableLogging : undefined; inputs["matchMode"] = args ? args.matchMode : undefined; inputs["project"] = args ? args.project : undefined; inputs["supportedLanguageCodes"] = args ? args.supportedLanguageCodes : undefined; inputs["tier"] = args ? args.tier : undefined; inputs["timeZone"] = args ? args.timeZone : undefined; inputs["avatarUriBackend"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Agent.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Agent resources. */ export interface AgentState { /** * API version displayed in Dialogflow console. If not specified, V2 API is assumed. Clients are free to query * different service endpoints for different API versions. However, bots connectors and webhook calls will follow * the specified API version. * * API_VERSION_V1: Legacy V1 API. * * API_VERSION_V2: V2 API. * * API_VERSION_V2_BETA_1: V2beta1 API. * Possible values are `API_VERSION_V1`, `API_VERSION_V2`, and `API_VERSION_V2_BETA_1`. */ apiVersion?: pulumi.Input<string>; /** * The URI of the agent's avatar, which are used throughout the Dialogflow console. When an image URL is entered * into this field, the Dialogflow will save the image in the backend. The address of the backend image returned * from the API will be shown in the [avatarUriBackend] field. */ avatarUri?: pulumi.Input<string>; /** * The URI of the agent's avatar as returned from the API. Output only. To provide an image URL for the agent avatar, the * [avatarUri] field can be used. */ avatarUriBackend?: pulumi.Input<string>; /** * To filter out false positive results and still get variety in matched natural language inputs for your agent, * you can tune the machine learning classification threshold. If the returned score value is less than the threshold * value, then a fallback intent will be triggered or, if there are no fallback intents defined, no intent will be * triggered. The score values range from 0.0 (completely uncertain) to 1.0 (completely certain). If set to 0.0, the * default of 0.3 is used. */ classificationThreshold?: pulumi.Input<number>; /** * The default language of the agent as a language tag. [See Language Support](https://cloud.google.com/dialogflow/docs/reference/language) * for a list of the currently supported language codes. This field cannot be updated after creation. */ defaultLanguageCode?: pulumi.Input<string>; /** * The description of this agent. The maximum length is 500 characters. If exceeded, the request is rejected. */ description?: pulumi.Input<string>; /** * The name of this agent. */ displayName?: pulumi.Input<string>; /** * Determines whether this agent should log conversation queries. */ enableLogging?: pulumi.Input<boolean>; /** * Determines how intents are detected from user queries. * * MATCH_MODE_HYBRID: Best for agents with a small number of examples in intents and/or wide use of templates * syntax and composite entities. * * MATCH_MODE_ML_ONLY: Can be used for agents with a large number of examples in intents, especially the ones * using @sys.any or very large developer entities. * Possible values are `MATCH_MODE_HYBRID` and `MATCH_MODE_ML_ONLY`. */ matchMode?: pulumi.Input<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * The list of all languages supported by this agent (except for the defaultLanguageCode). */ supportedLanguageCodes?: pulumi.Input<pulumi.Input<string>[]>; /** * The agent tier. If not specified, TIER_STANDARD is assumed. * * TIER_STANDARD: Standard tier. * * TIER_ENTERPRISE: Enterprise tier (Essentials). * * TIER_ENTERPRISE_PLUS: Enterprise tier (Plus). * NOTE: Due to consistency issues, the provider will not read this field from the API. Drift is possible between * the the provider state and Dialogflow if the agent tier is changed outside of the provider. */ tier?: pulumi.Input<string>; /** * The time zone of this agent from the [time zone database](https://www.iana.org/time-zones), e.g., America/New_York, * Europe/Paris. */ timeZone?: pulumi.Input<string>; } /** * The set of arguments for constructing a Agent resource. */ export interface AgentArgs { /** * API version displayed in Dialogflow console. If not specified, V2 API is assumed. Clients are free to query * different service endpoints for different API versions. However, bots connectors and webhook calls will follow * the specified API version. * * API_VERSION_V1: Legacy V1 API. * * API_VERSION_V2: V2 API. * * API_VERSION_V2_BETA_1: V2beta1 API. * Possible values are `API_VERSION_V1`, `API_VERSION_V2`, and `API_VERSION_V2_BETA_1`. */ apiVersion?: pulumi.Input<string>; /** * The URI of the agent's avatar, which are used throughout the Dialogflow console. When an image URL is entered * into this field, the Dialogflow will save the image in the backend. The address of the backend image returned * from the API will be shown in the [avatarUriBackend] field. */ avatarUri?: pulumi.Input<string>; /** * To filter out false positive results and still get variety in matched natural language inputs for your agent, * you can tune the machine learning classification threshold. If the returned score value is less than the threshold * value, then a fallback intent will be triggered or, if there are no fallback intents defined, no intent will be * triggered. The score values range from 0.0 (completely uncertain) to 1.0 (completely certain). If set to 0.0, the * default of 0.3 is used. */ classificationThreshold?: pulumi.Input<number>; /** * The default language of the agent as a language tag. [See Language Support](https://cloud.google.com/dialogflow/docs/reference/language) * for a list of the currently supported language codes. This field cannot be updated after creation. */ defaultLanguageCode: pulumi.Input<string>; /** * The description of this agent. The maximum length is 500 characters. If exceeded, the request is rejected. */ description?: pulumi.Input<string>; /** * The name of this agent. */ displayName: pulumi.Input<string>; /** * Determines whether this agent should log conversation queries. */ enableLogging?: pulumi.Input<boolean>; /** * Determines how intents are detected from user queries. * * MATCH_MODE_HYBRID: Best for agents with a small number of examples in intents and/or wide use of templates * syntax and composite entities. * * MATCH_MODE_ML_ONLY: Can be used for agents with a large number of examples in intents, especially the ones * using @sys.any or very large developer entities. * Possible values are `MATCH_MODE_HYBRID` and `MATCH_MODE_ML_ONLY`. */ matchMode?: pulumi.Input<string>; /** * The ID of the project in which the resource belongs. * If it is not provided, the provider project is used. */ project?: pulumi.Input<string>; /** * The list of all languages supported by this agent (except for the defaultLanguageCode). */ supportedLanguageCodes?: pulumi.Input<pulumi.Input<string>[]>; /** * The agent tier. If not specified, TIER_STANDARD is assumed. * * TIER_STANDARD: Standard tier. * * TIER_ENTERPRISE: Enterprise tier (Essentials). * * TIER_ENTERPRISE_PLUS: Enterprise tier (Plus). * NOTE: Due to consistency issues, the provider will not read this field from the API. Drift is possible between * the the provider state and Dialogflow if the agent tier is changed outside of the provider. */ tier?: pulumi.Input<string>; /** * The time zone of this agent from the [time zone database](https://www.iana.org/time-zones), e.g., America/New_York, * Europe/Paris. */ timeZone: pulumi.Input<string>; }
the_stack
// The types match the ones used internally. Will make it easier to maintain. // tslint:disable:interface-over-type-literal // This gets changed manually during development in the project, rule would require changes when updating DT's definitions since resolution is different. // tslint:disable:no-single-declare-module // tslint:disable:no-declare-current-package declare module 'flashpoint-launcher' { /** Version of the Flashpoint Launcher */ const version: string; /** Path to own extension */ const extensionPath: string; /** Config Data */ const config: AppConfigData; /** Returns most up to date Preferences Data */ function getPreferences(): AppPreferencesData; /** * Updates the Preferences data with a partial change. * @param data Partial data to apply * @param onError Callback for error handling * @returns Updated Preferences data */ function overwritePreferenceData( data: DeepPartial<AppPreferencesData>, onError?: (error: string) => void, ): Promise<AppPreferencesData>; /** Unload own extension */ function unload(): Promise<void>; /** * Get a URL for an extensions file * @param filePath Relative path to file from extension path */ function getExtensionFileURL(filePath: string): string; /** * Unzips a file into a given directory (7zip) * @param filePath Path to archive * @param outDir Directory to output into * @param onProgress Function called whenever a new file is extracted */ function unzipFile(filePath: string, outDir: string, opts: ZipExtractOptions): Promise<void>; /** * Gets an extension configuration value given its key */ function getExtConfigValue(key: string): any; /** * Gets an extension configuration value given its key and a new value */ function setExtConfigValue(key: string, value: any): Promise<void>; /** * Log functions to properly pass messages to the Logs Page. */ namespace log { const trace: (message: string) => void; const debug: (message: string) => void; const info: (message: string) => void; const warn: (message: string) => void; const error: (message: string) => void; } /** Collection of Command related API functions */ namespace commands { /** * Register a command to be called by name later * @param command Name of the command * @param callback Function to run when called * @returns Disposable to register to context.subscriptions */ function registerCommand(command: string, callback: (...args: any[]) => any): Disposable; } /** Collection of Game related API functions */ namespace games { // Playlist /** * Finds a playlist given its ID * @param playlistId ID of the Playlist * @param join Whether to include Playlist Games in the result */ function findPlaylist(playlistId: string, join?: boolean): Promise<Playlist | undefined>; /** * Finds a playlist given its name * @param playlistName Name of the Playlist * @param join Whether to include Playlist Games in the result */ function findPlaylistByName(playlistName: string, join?: boolean): Promise<Playlist | undefined>; /** Find all Playlists in the database (Playlist Games not returned) */ function findPlaylists(showExtreme: boolean): Promise<Playlist[]>; /** * Updates / Creates a Playlist * @param playlist Playlist data to save */ function updatePlaylist(playlist: Playlist): Promise<Playlist>; /** * Removes a playlist * @param playlist Playlist ID to remove * @returns Playlist that was removed */ function removePlaylist(playlistId: string): Promise<Playlist | undefined>; // Playlist Game /** * Finds a Playlist Game entry in a Playlist * @param playlistId Playlist to search * @param gameId Game to find */ function findPlaylistGame(playlistId: string, gameId: string): Promise<PlaylistGame | undefined>; /** * Removes a Playlist Game entry from a Playlist * @param playlistId Playlist to search * @param gameId Game to remove */ function removePlaylistGame(playlistId: string, gameId: string): Promise<PlaylistGame | undefined>; /** * Update / Create a Playlist Game entry * @param playlistGame Playlist Game entry to save */ function updatePlaylistGame(playlistGame: PlaylistGame): Promise<PlaylistGame>; /** * Update / Create many Playlist Game entries in a transaction * @param playlistGames Playlist Game entries to save */ function updatePlaylistGames(playlistGames: PlaylistGame[]): Promise<void>; // Games /** Returns the total number of games in the database */ function countGames(): Promise<number>; /** * Finds a Game given its ID * @param id ID of the Game */ function findGame(id: string): Promise<Game | undefined>; /** * Finds a selection of Games given filter options * @param opts Filter options * @param shallow Whether to return ViewGame or Game objects */ function findGames<T extends boolean>(opts: FindGamesOpts, shallow: T): Promise<Array<ResponseGameRange<T>>>; /** * Finds all Games using a Tag * @param tag Tag to filter for */ function findGamesWithTag(tag: Tag): Promise<Game[]>; /** * Updates / Creates a Game * @param game Game data to save */ function updateGame(game: Game): Promise<Game>; /** * Updates / Creates many Games in a transaction * @param games Game data to save */ function updateGames(games: Game[]): Promise<void>; /** * Removes a Game and all its AddApps * @param gameId ID of Game to remove */ function removeGameAndAddApps(gameId: string): Promise<Game | undefined>; // Misc /** * Returns all unique Platform strings in a library * @param library Library to search */ function findPlatforms(library: string): Promise<string[]>; /** * Parses a Playlist JSON file and returns an object you can save later. * @param jsonData Raw JSON data of the Playlist file * @param library Library to use instead of Playlist defined library */ function createPlaylistFromJson(jsonData: any, library?: string): Playlist; // Events const onWillLaunchGame: Event<GameLaunchInfo>; const onWillLaunchAddApp: Event<AdditionalApp>; const onWillLaunchCurationGame: Event<GameLaunchInfo>; const onWillLaunchCurationAddApp: Event<AdditionalApp>; const onDidLaunchGame: Event<Game>; const onDidLaunchAddApp: Event<AdditionalApp>; const onDidLaunchCurationGame: Event<Game>; const onDidLaunchCurationAddApp: Event<AdditionalApp>; const onDidUpdateGame: Event<{ oldGame: Game; newGame: Game }>; const onDidRemoveGame: Event<Game>; const onDidUpdatePlaylist: Event<{ oldPlaylist: Playlist; newPlaylist: Playlist }>; const onDidUpdatePlaylistGame: Event<{ oldGame: PlaylistGame; newGame: PlaylistGame }>; const onDidRemovePlaylistGame: Event<PlaylistGame>; const onWillImportGame: Event<CurationImportState>; } /** Collection of Tag related API functions */ namespace tags { // Tags /** * Finds a tag given it's ID * @param tagId ID of the Tag */ function getTagById(tagId: number): Promise<Tag | undefined>; /** * Finds a tag given an alias name * @param name Name of the Tag (any matching alias) */ function findTag(name: string): Promise<Tag | undefined>; /** * Finds a list of tags that begins with a name (if given) * @param name Partial name that a tag starts with */ function findTags(name?: string): Promise<Tag[]>; /** * Creates a new Tag * @param name Name of the primary alias * @param categoryName Name of the category to use, Default if none given * @param aliases List of extra aliases to register */ function createTag(name: string, categoryName?: string, aliases?: string[]): Promise<Tag | undefined>; /** * Updates a Tag * @param tag Tag data to save */ function saveTag(tag: Tag): Promise<Tag>; /** * Removes a Tag (from all Games) * @param tagId ID of Tag to remove * @param skipWarn If true, warn user before deleting tag from games. */ function deleteTag(tagId: number, skipWarn?: boolean): Promise<boolean>; /** * Finds all the Tags a Game is tagged with * @param gameId ID of the Game to find */ function findGameTags(gameId: string): Promise<Tag[] | undefined>; // Tag Categories /** * Find a Tag Category by it's ID. (Useful when a Tag doesn't populate it) * @param categoryId ID of the Tag Category */ function getTagCategoryById(categoryId: number): Promise<TagCategory | undefined>; /** * Find all Tag Categories */ function findTagCategories(): Promise<TagCategory[]>; /** * Create a new Tag Category * @param name Name of the Tag Category * @param color Color to give the Tag Category */ function createTagCategory(name: string, color: string): Promise<TagCategory | undefined>; /** * Update a Tag Category * @param tagCategory Tag Category data to save */ function saveTagCategory(tagCategory: TagCategory): Promise<TagCategory>; /** * Removes a Tag Category. All owned Tags are moved to the first available Tag Category. * @param tagCategoryId ID of the Tag Category to remove */ function deleteTagCategory(tagCategoryId: number): Promise<boolean>; // Tag Suggestions /** * Finds a list of Tag Suggestions given a string they start with * @param name Partial name that a tag starts with */ function findTagSuggestions(name: string): Promise<TagSuggestion[]>; // Misc /** * Merges 2 tags into a single tag. * @param mergeData Required data to merge. */ function mergeTags(mergeData: MergeTagData): Promise<Tag | undefined>; } /** Collection of Status related API functions */ namespace status { /** * Update any status in the Status State * @param key Element to update * @param val Value to update element with */ function setStatus<T extends keyof StatusState>(key: T, val: StatusState[T]): void; /** * Gets the status in any Status State * @param key Element to view */ function getStatus<T extends keyof StatusState>(key: T): StatusState[T]; } /** Collection of Service related API function */ namespace services { /** * Runs a managed service given info, will die when the launcher exits. * @param name Name of the service * @param info Service info to run. * @param basePath Override for directory to start in (info is relative to this), Extension path if none given * @returns A managed process. Can be passed to removeService. */ function runService(name: string, info: ProcessInfo, opts: ProcessOpts, basePath?: string): ManagedChildProcess; /** * Creates a managed process given info, will die when disposed. (Does not start it) * @param name Name of the process * @param info Process info to run. * @param basePath Override for directory to start in (info is relative to this), Extension path if none given * @returns A managed process. */ function createProcess( name: string, info: ProcessInfo, opts: ProcessOpts, basePath?: string, ): DisposableChildProcess; /** * Kills and removes a service process started by runService * @param process Service process to remove */ function removeService(process: ManagedChildProcess): Promise<void>; /** * Returns the service info of all running services */ function getServices(): ManagedChildProcess[]; // Events const onServiceNew: Event<ManagedChildProcess>; const onServiceRemove: Event<ManagedChildProcess>; const onServiceChange: Event<ServiceChange>; } /** Front facing dialogs */ namespace dialogs { /** * Opens a message box on the client. Buttons can be provided in options. * @param options Message box options * @returns Button index pressed (0 or cancelId if exited) */ function showMessageBox(options: ShowMessageBoxOptions): Promise<number>; /** * Opens a save dialog on the client. They can select a file to save to. * @param options Save dialog options * @returns Path to file chosen, if any */ function showSaveDialog(options: ShowSaveDialogOptions): Promise<string | undefined>; /** * Opens an open dialog on the client. They can select a file for you to open. * @param options Open dialog options * @returns Path to file(s) chosen, if any */ function showOpenDialog(options: ShowOpenDialogOptions): Promise<string[] | undefined>; } // Events /** Called when the backend has fully initialized. Extension activation is earlier. */ const onDidInit: Event<void>; /** Called when a client connects to the backend */ const onDidConnect: Event<void>; /** See Electron docs for explanations. https://www.electronjs.org/docs/api/dialog */ type ShowMessageBoxOptions = { title?: string | undefined; message: string; buttons?: string[] | undefined; cancelId?: number | undefined; }; /** See Electron docs for explanations. http://electronjs.org/docs/api/structures/file-filter */ interface FileFilter { extensions: string[]; name: string; } /** See Electron docs for explanations. https://www.electronjs.org/docs/api/dialog */ type ShowSaveDialogOptions = { title?: string | undefined; defaultPath?: string | undefined; buttonLabel?: string | undefined; filters?: FileFilter[] | undefined; message?: string | undefined; nameFieldLabel?: string | undefined; }; /** See Electron docs for explanations. https://www.electronjs.org/docs/api/dialog */ type ShowOpenDialogOptions = { title?: string | undefined; defaultPath?: string | undefined; buttonLabel?: string | undefined; filters: FileFilter[]; properties?: Array< | 'openFile' | 'openDirectory' | 'multiSelections' | 'showHiddenFiles' | 'createDirectory' | 'promptToCreate' | 'noResolveAliases' | 'treatPackageAsDirectory' | 'dontAddToRecent' > | undefined; message?: string | undefined; }; type Game = { /** ID of the game (unique identifier) */ id: string; /** ID of the game which owns this game */ parentGameId?: string | undefined; /** Full title of the game */ title: string; /** Any alternate titles to match against search */ alternateTitles: string; /** Game series the game belongs to (empty string if none) */ series: string; /** Name of the developer(s) of the game (developer names are separated by ',') */ developer: string; /** Name of the publisher of the game */ publisher: string; /** Date-time of when the game was added to collection */ dateAdded: string; /** Date-time of when the game was added to collection */ dateModified: string; /** Platform the game runs on (Flash, HTML5, Shockwave etc.) */ platform: string; /** If the game is "broken" or not */ broken: boolean; /** Game is not suitable for children */ extreme: boolean; /** If the game is single player or multiplayer, and if the multiplayer is cooperative or not */ playMode: string; /** How playable the game is */ status: string; /** Information that could be useful for the player (of varying importance) */ notes: string; /** List of tags attached to the game */ tags: Tag[]; /** Source if the game files, either full URL or the name of the website */ source: string; /** Path to the application that runs the game */ applicationPath: string; /** Command line argument(s) passed to the application to launch the game */ launchCommand: string; /** Date of when the game was released */ releaseDate: string; /** Version of the game */ version: string; /** Original description of the game (probably given by the game's creator or publisher) */ originalDescription: string; /** The language(s) the game is in */ language: string; /** Library this game belongs to */ library: string; /** All attached Additional Apps of a game */ addApps: AdditionalApp[]; /** Unused */ orderTitle: string; /** If the game is a placeholder (and can therefore not be saved) */ placeholder: boolean; }; type AdditionalApp = { /** ID of the additional application (unique identifier) */ id: string; /** Path to the application that runs the additional application */ applicationPath: string; /** * If the additional application should run before the game. * (If true, this will always run when the game is launched) * (If false, this will only run when specifically launched) */ autoRunBefore: boolean; /** Command line argument(s) passed to the application to launch the game */ launchCommand: string; /** Name of the additional application */ name: string; /** Wait for this to exit before the Game will launch (if starting before launch) */ waitForExit: boolean; /** Parent of this add app */ parentGame: Game; }; type Tag = { /** ID of the tag (unique identifier) */ id?: number | undefined; /** Date when this tag was last modified */ dateModified: string; /** ID of Primary Alias */ primaryAliasId: number; /** Primary Alias */ primaryAlias: TagAlias; /** Aliases / Names of the tag */ aliases: TagAlias[]; /** Category this tag is a part of (either ID or TagCategory will exist) */ categoryId?: number | undefined; /** Category this tag is a part of (either ID or TagCategory will exist) */ category?: TagCategory | undefined; /** Description of the tag */ description?: string | undefined; /** Games which are marked with this Tag */ gamesUsing?: Game[] | undefined; /** Number of games this tag belongs to */ count?: number | undefined; }; type TagAlias = { /** ID of the tag alias (unique identifier) */ id: number; /** Tag this alias belongs to (either ID or Tag will exist) */ tagId?: number | undefined; /** Tag this alias belongs to (either ID or Tag will exist) */ tag?: Tag | undefined; /** The name this alias represents */ name: string; }; type TagSuggestion = { /** Alias found, only present if not the same as the primary alias */ alias?: string | undefined; /** Primary alias of the tag suggestion */ primaryAlias: string; /** Tag suggested */ tag: Tag; }; type TagCategory = { /** ID of the tag category (unique identifier) */ id: number; /** Category Name */ name: string; /** Category Color */ color: string; /** Description of the Tag Category */ description?: string | undefined; /** Tags using this Tag Category */ tags: Tag[]; }; type Playlist = { /** ID of the playlist (unique identifier) */ id: string; /** Games in this playlist */ games: PlaylistGame[]; /** Title of the playlist. */ title: string; /** Description of the playlist. */ description: string; /** Author of the playlist. */ author: string; /** Icon of the playlist (Base64 encoded image). */ icon: string; /** Route of the library this playlist is for. */ library: string; /** Attribute for if playlist contains games not suitable for children */ extreme: boolean; }; type PlaylistGame = { /** Internal ID of the playlist game entry */ id?: string | undefined; /** Playlist which owns this game (either ID or Playlist will exist) */ playlistId?: string | undefined; /** Playlist which owns this game (either ID or Playlist will exist) */ playlist?: Playlist | undefined; /** Order priority of the game in the playlist */ order: number; /** Notes for the game inside the playlist specifically */ notes: string; /** Game this represents (either ID or Game will exist) */ gameId?: string | undefined; /** Game this represents (either ID or Game will exist) */ game?: Game | undefined; }; /** * Data passed to merge tags together * @param toMerge Tag to merge from * @param mergeInto Tag to merge into * @param makeAlias Whether to move all aliases from toMerge into mergeInto as well */ type MergeTagData = { toMerge: string; mergeInto: string; makeAlias: boolean; }; type FindGamesOpts = { /** Ranges of games to fetch (all games are fetched if undefined). */ ranges?: RequestGameRange[] | undefined; filter?: FilterGameOpts | undefined; orderBy?: GameOrderBy | undefined; direction?: GameOrderDirection | undefined; getTotal?: boolean | undefined; }; /** Game field to order the results by */ type GameOrderBy = keyof Game; /** Direction to return the results in (ascending or descending) */ type GameOrderDirection = 'ASC' | 'DESC'; type RequestGameRange = { /** Index of the first game. */ start: number; /** Number of games to request (if undefined, all games until the end of the query will be included). */ length: number | undefined; /** * Tuple of the last game of the previous page. * If this is set then "start" must be the index of the game after this (since this will be used instead of * "start" when selecting the games). */ index?: PageTuple | undefined; }; /** Tuple of values from the last game of a previous page (look up "keyset pagination"). */ type PageTuple = { /** Primary order value. */ orderVal: any; /** Title of the game (secondary order value). */ title: string; /** ID of the game (unique value). */ id: string; }; /** Options for ordering games. */ type FilterGameOpts = { /** Search query to filter by */ searchQuery?: ParsedSearch | undefined; /** Playlist to limit the results to (no playlist limit will be applied if undefined). */ playlistId?: string | undefined; }; /** Object representation of a parsed search query. */ type ParsedSearch = { /** Generic filter to blacklist some predetermined field(s). */ genericBlacklist: string[]; /** Generic filter to whitelist some predetermined field(s). */ genericWhitelist: string[]; /** Whitelists to apply */ blacklist: FieldFilter[]; /** Blacklists to apply */ whitelist: FieldFilter[]; }; /** A search filter that applies to a specific field. */ type FieldFilter = { /** The field the filter applies to. */ field: string; /** Value to search for in the field. */ value: any; }; type ResponseGameRange<T extends boolean> = { /** Index of the first game. */ start: number; /** Number of games requested. */ length?: number | undefined; /** Games found within the range. */ games: T extends true ? ViewGame[] : Game[]; }; /** Shortend version of {@link Game} returned in searches, makes for better performance. */ type ViewGame = { id: string; title: string; platform: string; tags: Tag[]; developer: string; publisher: string; }; /** Data contained in the Config file */ type AppConfigData = { /** Path to the Flashpoint root folder (relative or absolute) */ flashpointPath: string; /** Path to the image folder (relative to the flashpoint path) */ imageFolderPath: string; /** Path to the logo folder (relative to the flashpoint path) */ logoFolderPath: string; /** Path to the playlist folder (relative to the flashpoint path) */ playlistFolderPath: string; /** Path to the json folder (relative to the flashpoint path) */ jsonFolderPath: string; /** Path to the platform folder (relative to the flashpoint path) */ platformFolderPath: string; /** Path to the theme folder (relative to the flashpoint path) */ themeFolderPath: string; /** Path to the logo sets folder (relative to the flashpoint path) */ logoSetsFolderPath: string; /** Path of the meta edits folder (relative to the flashpoint path) */ metaEditsFolderPath: string; /** Path to load User extensions from (relative to the flashpoint path) */ extensionsPath: string; /** If the custom title bar should be used in MainWindow */ useCustomTitlebar: boolean; /** * If the Server should be started, and closed, together with this application. * The "server" is defined in "services.json". */ startServer: boolean; // Name of the Server process to run server: string; /** If games flagged as "extreme" should be hidden (mainly for parental control) */ disableExtremeGames: boolean; /** If games flagged as "broken" should be hidden */ showBrokenGames: boolean; /** Array of native locked platforms */ nativePlatforms: string[]; /** Lower limit of the range of ports that the back should listen on. */ backPortMin: number; /** Upper limit of the range of ports that the back should listen on. */ backPortMax: number; /** Lower limit of the range of ports that the back image server should listen on. */ imagesPortMin: number; /** Upper limit of the range of ports that the back image server should listen on. */ imagesPortMax: number; /** Metadata Server Host (For Online Sync) */ metadataServerHost: string; /** Last time the Metadata Server Host was synced with */ lastSync: number; /** Base URL of the server to download missing thumbnails/screenshots from. */ onDemandBaseUrl: string; /** Base URL of the server to do pastes of the Logs to. */ logsBaseUrl: string; /** Whether to notify that launcher updates are available */ updatesEnabled: boolean; }; /** * Contains state of all non-config settings the user can change in the application. * This is the data contained in the Preferences file. */ type AppPreferencesData = { [key: string]: any; /** Scale of the games at the BrowsePage. */ browsePageGameScale: number; /** If "Extreme" games should be shown at the BrowsePage. */ browsePageShowExtreme: boolean; /** If editing games, additional applications and playlists should be allowed. */ enableEditing: boolean; /** Default language used for fallback */ fallbackLanguage: string; /** Current language */ currentLanguage: string; /** Layout of game collection at BrowsePage. */ browsePageLayout: BrowsePageLayout; /** If the left sidebar at the BrowsePage should be visible. */ browsePageShowLeftSidebar: boolean; /** If the right sidebar at the BrowsePage should be visible. */ browsePageShowRightSidebar: boolean; /** Width of the left sidebar. (Browse Page) */ browsePageLeftSidebarWidth: number; /** Width of the right sidebar. (Browse Page) */ browsePageRightSidebarWidth: number; /** Width of the left sidebar. (Curate Page) */ curatePageLeftSidebarWidth: number; /** If the "Developer" tab should be visible in the header. */ showDeveloperTab: boolean; /** Filename of the current theme. */ currentTheme: string | undefined; /** Filename of the current logo set */ currentLogoSet: string | undefined; /** The "route" of the last selected library (empty string selects the default). */ lastSelectedLibrary: string; /** What property to order the games by. */ gamesOrderBy: GameOrderBy; /** What order the games should appear in. */ gamesOrder: GameOrderDirection; /** Position and size of the main window. */ mainWindow: AppPreferencesDataMainWindow; /** Default Library for new games etc. */ defaultLibrary: string; /** Save curations after importing */ saveImportedCurations: boolean; /** Whether to symlink or copy curation content when running (Symlink required for MAD4FP) */ symlinkCurationContent: boolean; /** Download missing thumbnails/screenshots from a remote server. */ onDemandImages: boolean; /** Sources to show/hide in the log page. */ showLogSource: { [key: string]: boolean; }; /** Levels to show/hide in the log page. */ showLogLevel: { [key in LogLevel]: boolean; }; /** Libraries that should be excluded from random picks. */ excludedRandomLibraries: string[]; /** Application path overrides to check during app launches */ appPathOverrides: AppPathOverride[]; }; type AppPathOverride = { path: string; override: string; enabled: boolean; }; type AppPreferencesDataMainWindow = { x?: number | undefined; y?: number | undefined; width?: number | undefined; height?: number | undefined; maximized: boolean; }; type ProcessInfo = { /** Path of the file (relative to the Flashpoint root) */ path: string; /** Name of the file to execute */ filename: string; /** Arguments to pass to the process */ arguments: string[]; }; type CurationImportState = { /** Game being imported */ game: Game; /** Files / Folders being copied, and to where */ contentToMove: string[][]; /** Path of the curation */ curationPath: string; }; type StatusState = { devConsole: string; }; class DisposableChildProcess extends ManagedChildProcess implements Disposable { toDispose: Disposable[]; isDisposed: boolean; onDispose?: (() => void) | undefined; } type ProcessOpts = { detached?: boolean | undefined; autoRestart?: boolean | undefined; shell?: boolean | undefined; }; type ServiceChange = { process: ManagedChildProcess; oldState: ProcessState; newState: ProcessState; }; interface ManagedChildProcess { /** Fires whenever the status of a process changes. */ on(event: 'change', listener: (newState: ProcessState) => void): this; /** Fires whenever the process exits */ on(event: 'exit', listener: (code: number | null, signal: string | null) => void): this; emit(event: 'exit', code: number | null, signal: string | null): boolean; emit(event: 'change', newState: ProcessState): boolean; } class ManagedChildProcess { /** ID of the process */ id: string; /** Info this process was created with */ info: ProcessInfo; /** Display name of the service. */ readonly name: string; constructor(id: string, name: string, cwd: string, opts: ProcessOpts, info: ProcessInfo); /** Get the process ID (or -1 if the process is not running). */ getPid(): number; /** Get the state of the process. */ getState(): ProcessState; /** Get the time timestamp of when the process was started. */ getStartTime(): number; /** Spawn process and keep track on it. */ spawn(auto?: boolean): void; /** Politely ask the child process to exit (if it is running). */ kill(): void; /** Restart the managed child process (by killing the current, and spawning a new). */ restart(): void; } /** State of a managed process. */ enum ProcessState { /** The process is not running. */ STOPPED = 0, /** The process is running. */ RUNNING = 1, /** The process is being killed (it has been requested to terminate, but it hasn't been terminated yet). */ KILLING = 2, } /** Info type passed to onWillLaunch events */ type GameLaunchInfo = { game: Game; launchInfo: LaunchInfo; }; type LaunchInfo = { gamePath: string; gameArgs: string | string[]; useWine: boolean; env: ProcessEnv; }; /** Options expected for 'browser' mode application return */ type BrowserApplicationOpts = { url: string; proxy?: string | undefined; }; type ZipExtractOptions = { onData?: ((data: ZipData) => void) | undefined; onProgress?: ((progress: ZipProgress) => void) | undefined; }; interface ZipData { file: string; status: string; attributes?: string | undefined; size?: number | undefined; sizeCompressed?: number | undefined; hash?: string | undefined; } interface ZipProgress { percent: number; fileCount: number; file: string; } interface ProcessEnv { [key: string]: string | undefined; } /** Modes for displaying the game collection at the BrowsePage */ enum BrowsePageLayout { /** Games are in a vertical list, one game per row */ list = 0, /** Games are in a table-like grid, each cell is a game */ grid = 1, } /** Severity level of a Log */ enum LogLevel { TRACE = 0, DEBUG = 1, INFO = 2, WARN = 3, ERROR = 4, SILENT = 5, } /** A self-nesting type that allows one time disposable with an optional callback */ type Disposable = { /** Children to dispose of in the future. Add with {@link registerDisposable} to maintain safety. */ toDispose: Disposable[]; /** Whether this is already disposed */ isDisposed: boolean; /** Callback to use when disposed */ onDispose?: (() => void) | undefined; }; /** Dispose of a disposable and all its children */ function dispose(disposable: Disposable): void; /** Dispose of all a disposable;s children but not itself */ function clearDisposable(disposable: Disposable): void; /** * Register a disposable to its parent. They must not be the same. * @param parent Parent to register to * @param child Child to register */ function registerDisposable(parent: Disposable, child: Disposable): void; /** * Creates Disposable data to fill a newly created Disposable type object * @param callback Callback to run when disposed */ function newDisposable(callback?: () => void): Disposable; type ExtensionContext = { /** Put all extension disposables on here with registerDisposable */ subscriptions: Disposable; }; interface Event<T> { /** * A function that represents an event to which you subscribe by calling it with * a listener function as argument. * * @param listener The listener function will be called when the event happens. * @param thisArgs The `this` argument which will be used when calling the event listener. (rarely used) * @param disposables An array to which a disposable will be added. * @return A disposable which unsubscribes the event listener. */ (listener: (e: T) => any, thisArgs?: any, disposables?: Disposable): Disposable; } /** Replacement of "object" type. Note: I'm not sure how effective it is though //obelisk */ type ObjectLike = Record<string, unknown> | Record<number, unknown>; /** Utility type. Recursively set all properties as optional. */ type DeepPartial<T> = { [K in keyof T]?: T[K] extends ObjectLike ? DeepPartial<T[K]> : T[K]; }; }
the_stack
import CliOption from '../CliOption'; import CodegenConstants from '../CodegenConstants'; import CodegenType from '../CodegenType'; import DefaultCodegen from '../DefaultCodegen'; import { ArrayProperty, MapProperty } from '../models/properties'; import StringUtils, { capitalizeFully } from '../java/StringUtils'; import File from '../java/File'; import { HeaderParameter } from '../models/parameters'; import { parseBoolean } from '../java/BooleanHelper'; import Pattern from '../java/Pattern'; import StringBuilder from '../java/StringBuilder'; import { log } from 'ern-core'; import { newHashMap, newHashSet } from '../java/javaUtil'; const PATH_PARAM_PATTERN = Pattern.compile('\\{[a-zA-Z_\\-]+\\}'); const ArrayUtils = { contains(arr, val) { return arr && arr.indexOf(val) > -1; }, }; export default class SwiftCodegen extends DefaultCodegen { public static readonly PROJECT_NAME = 'projectName'; public static readonly RESPONSE_AS = 'responseAs'; public static readonly UNWRAP_REQUIRED = 'unwrapRequired'; public static readonly POD_SOURCE = 'podSource'; public static readonly POD_AUTHORS = 'podAuthors'; public static readonly POD_SOCIAL_MEDIA_URL = 'podSocialMediaURL'; public static readonly POD_DOCSET_URL = 'podDocsetURL'; public static readonly POD_LICENSE = 'podLicense'; public static readonly POD_HOMEPAGE = 'podHomepage'; public static readonly POD_SUMMARY = 'podSummary'; public static readonly POD_DESCRIPTION = 'podDescription'; public static readonly POD_SCREENSHOTS = 'podScreenshots'; public static readonly POD_DOCUMENTATION_URL = 'podDocumentationURL'; public static readonly SWIFT_USE_API_NAMESPACE = 'swiftUseApiNamespace'; public static readonly DEFAULT_POD_AUTHORS = 'Swagger Codegen'; public static readonly LIBRARY_PROMISE_KIT = 'PromiseKit'; public static readonly RESPONSE_LIBRARIES = [ SwiftCodegen.LIBRARY_PROMISE_KIT, ]; public static normalizePath(path) { const builder = StringBuilder(); let cursor = 0; // Matcher matcher = PATH_PARAM_PATTERN.matcher(path); const matcher = PATH_PARAM_PATTERN.matcher(path); let found = matcher.find(); while (found) { const stringBeforeMatch = path.substring(cursor, matcher.start()); builder.append(stringBeforeMatch); let group = matcher.group().substring(1, matcher.group().length - 1); group = DefaultCodegen.camelize(group, true); builder.append('{').append(group).append('}'); cursor = matcher.end(); found = matcher.find(); } const stringAfterMatch = path.substring(cursor); builder.append(stringAfterMatch); return builder.toString(); } public projectName = 'SwaggerClient'; public responseAs = []; public sourceFolder = 'Classes' + File.separator + 'Swaggers'; public unwrapRequired = false; public swiftUseApiNamespace = false; public __outputFolder = 'generated-code' + File.separator + 'swift'; public __embeddedTemplateDir = 'swift'; public __templateDir = 'swift'; public __apiPackage = File.separator + 'APIs'; public __modelPackage = File.separator + 'Models'; public __typeMapping = newHashMap( ['array', 'Array'], ['List', 'Array'], ['map', 'Dictionary'], ['date', 'NSDate'], ['Date', 'NSDate'], ['DateTime', 'NSDate'], ['boolean', 'Bool'], ['string', 'String'], ['char', 'Character'], ['short', 'Int'], ['int', 'Int32'], ['long', 'Int64'], ['integer', 'Int32'], ['Integer', 'Int32'], ['float', 'Float'], ['number', 'Double'], ['double', 'Double'], ['object', 'AnyObject'], ['file', 'NSURL'], ['binary', 'NSData'], ['ByteArray', 'NSData'], ['UUID', 'NSUUID'], ); public __defaultIncludes = newHashSet( 'NSData', 'NSDate', 'NSURL', 'NSUUID', 'Array', 'Dictionary', 'Set', 'Any', 'Empty', 'AnyObject', ); public __reservedWords = newHashSet( 'Int', 'Int32', 'Int64', 'Int64', 'Float', 'Double', 'Bool', 'Void', 'String', 'Character', 'AnyObject', 'class', 'Class', 'break', 'as', 'associativity', 'deinit', 'case', 'dynamicType', 'convenience', 'enum', 'continue', 'false', 'dynamic', 'extension', 'default', 'is', 'didSet', 'func', 'do', 'nil', 'final', 'import', 'else', 'self', 'get', 'init', 'fallthrough', 'Self', 'infix', 'internal', 'for', 'super', 'inout', 'let', 'if', 'true', 'lazy', 'operator', 'in', 'COLUMN', 'left', 'private', 'return', 'FILE', 'mutating', 'protocol', 'switch', 'FUNCTION', 'none', 'public', 'where', 'LINE', 'nonmutating', 'static', 'while', 'optional', 'struct', 'override', 'subscript', 'postfix', 'typealias', 'precedence', 'var', 'prefix', 'Protocol', 'required', 'right', 'set', 'Type', 'unowned', 'weak', ); public __importMapping = newHashMap(); public __languageSpecificPrimitives = newHashSet( 'Int', 'Int32', 'Int64', 'Float', 'Double', 'Bool', 'Void', 'String', 'Character', 'AnyObject', ); constructor() { super(); this.__modelTemplateFiles.put('model.mustache', '.swift'); this.__apiTemplateFiles.put('api.mustache', '.swift'); } public initalizeCliOptions() { super.initalizeCliOptions(); this.__cliOptions.push( new CliOption(SwiftCodegen.PROJECT_NAME, 'Project name in Xcode'), ); this.__cliOptions.push( new CliOption( SwiftCodegen.RESPONSE_AS, 'Optionally use libraries to manage response. Currently ' + StringUtils.join(SwiftCodegen.RESPONSE_LIBRARIES, ', ') + ' are available.', ), ); this.__cliOptions.push( new CliOption( SwiftCodegen.UNWRAP_REQUIRED, "Treat 'required' properties in response as non-optional (which would crash the app if api returns null as opposed to required option specified in json schema", ), ); this.__cliOptions.push( new CliOption( SwiftCodegen.POD_SOURCE, 'Source information used for Podspec', ), ); this.__cliOptions.push( new CliOption(CodegenConstants.POD_VERSION, 'Version used for Podspec'), ); this.__cliOptions.push( new CliOption(SwiftCodegen.POD_AUTHORS, 'Authors used for Podspec'), ); this.__cliOptions.push( new CliOption( SwiftCodegen.POD_SOCIAL_MEDIA_URL, 'Social Media URL used for Podspec', ), ); this.__cliOptions.push( new CliOption(SwiftCodegen.POD_DOCSET_URL, 'Docset URL used for Podspec'), ); this.__cliOptions.push( new CliOption(SwiftCodegen.POD_LICENSE, 'License used for Podspec'), ); this.__cliOptions.push( new CliOption(SwiftCodegen.POD_HOMEPAGE, 'Homepage used for Podspec'), ); this.__cliOptions.push( new CliOption(SwiftCodegen.POD_SUMMARY, 'Summary used for Podspec'), ); this.__cliOptions.push( new CliOption( SwiftCodegen.POD_DESCRIPTION, 'Description used for Podspec', ), ); this.__cliOptions.push( new CliOption( SwiftCodegen.POD_SCREENSHOTS, 'Screenshots used for Podspec', ), ); this.__cliOptions.push( new CliOption( SwiftCodegen.POD_DOCUMENTATION_URL, 'Documentation URL used for Podspec', ), ); this.__cliOptions.push( new CliOption( SwiftCodegen.SWIFT_USE_API_NAMESPACE, 'Flag to make all the API classes inner-class of {{projectName}}API', ), ); } public getTag() { return CodegenType.CLIENT; } public getName() { return 'Swift'; } public getHelp() { return 'Generates a swift client library.'; } public processOpts() { super.processOpts(); if (this.__additionalProperties.containsKey(SwiftCodegen.PROJECT_NAME)) { this.setProjectName( this.__additionalProperties.get(SwiftCodegen.PROJECT_NAME), ); } else { this.__additionalProperties.put( SwiftCodegen.PROJECT_NAME, this.projectName, ); } this.sourceFolder = this.projectName + File.separator + this.sourceFolder; if (this.__additionalProperties.containsKey(SwiftCodegen.UNWRAP_REQUIRED)) { this.setUnwrapRequired( parseBoolean( this.__additionalProperties.get(SwiftCodegen.UNWRAP_REQUIRED), ), ); } this.__additionalProperties.put( SwiftCodegen.UNWRAP_REQUIRED, this.unwrapRequired, ); if (this.__additionalProperties.containsKey(SwiftCodegen.RESPONSE_AS)) { const responseAsObject = this.__additionalProperties.get( SwiftCodegen.RESPONSE_AS, ); if (typeof responseAsObject === 'string') { this.setResponseAs(responseAsObject.split(',')); } else { this.setResponseAs(responseAsObject); } } this.__additionalProperties.put(SwiftCodegen.RESPONSE_AS, this.responseAs); if ( ArrayUtils.contains(this.responseAs, SwiftCodegen.LIBRARY_PROMISE_KIT) ) { this.__additionalProperties.put('usePromiseKit', true); } if ( this.__additionalProperties.containsKey( SwiftCodegen.SWIFT_USE_API_NAMESPACE, ) ) { this.swiftUseApiNamespace = parseBoolean( this.__additionalProperties.get(SwiftCodegen.SWIFT_USE_API_NAMESPACE), ); } this.__additionalProperties.put( SwiftCodegen.SWIFT_USE_API_NAMESPACE, this.swiftUseApiNamespace, ); if (!this.__additionalProperties.containsKey(SwiftCodegen.POD_AUTHORS)) { this.__additionalProperties.put( SwiftCodegen.POD_AUTHORS, SwiftCodegen.DEFAULT_POD_AUTHORS, ); } } public isReservedWord(word) { return word != null && this.__reservedWords.contains(word); } public escapeReservedWord(name) { return '_' + name; } public modelFileFolder() { return ( this.__outputFolder + File.separator + this.sourceFolder + this.modelPackage().split('.').join(File.separatorChar) ); } public apiFileFolder() { return ( this.__outputFolder + File.separator + this.sourceFolder + this.apiPackage().split('.').join(File.separatorChar) ); } public getTypeDeclaration(p) { if (p != null) { if (p instanceof ArrayProperty) { const inner = p.getItems(); return '[' + this.getTypeDeclaration(inner) + ']'; } else if (p instanceof MapProperty) { const inner = p.getAdditionalProperties(); return '[String:' + this.getTypeDeclaration(inner) + ']'; } } return super.getTypeDeclaration(p); } public getSwaggerType(p) { const swaggerType = super.getSwaggerType(p); let type = null; if (this.__typeMapping.containsKey(swaggerType)) { type = this.__typeMapping.get(swaggerType); if ( this.__languageSpecificPrimitives.contains(type) || this.__defaultIncludes.contains(type) ) { return type; } } else { type = swaggerType; } return this.toModelName(type); } public isDataTypeBinary(dataType) { return dataType != null && dataType === 'NSData'; } /** * Output the proper model name (capitalized) * * @param name the name of the model * @return capitalized model name */ public toModelName(name) { name = this.sanitizeName(name); if (!StringUtils.isEmpty(this.modelNameSuffix)) { name = name + '_' + this.modelNameSuffix; } if (!StringUtils.isEmpty(this.modelNamePrefix)) { name = this.modelNamePrefix + '_' + name; } name = DefaultCodegen.camelize(name); if (this.isReservedWord(name)) { const modelName = 'Model' + name; log.warn( `${name} (reserved word) cannot be used as model name. Renamed to ${modelName}`, ); return modelName; } if (name.match('^\\d.*')) { const modelName = 'Model' + name; log.warn( `${name} (model name starts with number) cannot be used as model name. Renamed to ${modelName}`, ); return modelName; } return name; } /** * Return the capitalized file name of the model * * @param name the model name * @return the file name of the model */ public toModelFilename(name) { return this.toModelName(name); } public toDefaultValue(p) { return null; } public toInstantiationType(p) { if (p instanceof MapProperty) { const inner = this.getSwaggerType(p.getAdditionalProperties()); return '[String:' + inner + ']'; } else if (p instanceof ArrayProperty) { const inner = this.getSwaggerType(p.getItems()); return '[' + inner + ']'; } return null; } public fromProperty(name, p) { const codegenProperty = super.fromProperty(name, p); if (codegenProperty.isContainer) { return codegenProperty; } if (codegenProperty.isEnum) { const swiftEnums: any[] = []; const values = codegenProperty.allowableValues.get('values'); for (const value of values) { swiftEnums.push( newHashMap( ['enum', this.toSwiftyEnumName('' + value)], ['raw', '' + value], ), ); } codegenProperty.allowableValues.put('values', swiftEnums); codegenProperty.datatypeWithEnum = this.toEnumName(codegenProperty); if ( this.isReservedWord(codegenProperty.datatypeWithEnum) || this.toVarName(name) === codegenProperty.datatypeWithEnum ) { codegenProperty.datatypeWithEnum = codegenProperty.datatypeWithEnum + 'Enum'; } } return codegenProperty; } public toSwiftyEnumName(value) { if (value.match('[A-Z][a-z0-9]+[a-zA-Z0-9]*')) { return value; } return capitalizeFully(value.toLowerCase()).replace( new RegExp('[-_ :]', 'g'), '', ); } public toApiName(name) { if (name.length === 0) { return 'DefaultAPI'; } return this.initialCaps(name) + 'API'; } public toOperationId(operationId) { operationId = DefaultCodegen.camelize(this.sanitizeName(operationId), true); if (StringUtils.isEmpty(operationId)) { throw new Error('Empty method name (operationId) not allowed'); } if (this.isReservedWord(operationId)) { const newOperationId = DefaultCodegen.camelize( 'call_' + operationId, true, ); log.warn( `${operationId} (reserved word) cannot be used as method name. Renamed to ${newOperationId}`, ); return newOperationId; } return operationId; } public toVarName(name) { name = this.sanitizeName(name); if (name.match('^[A-Z_]*$')) { return name; } name = DefaultCodegen.camelize(name, true); if (this.isReservedWord(name) || name.match('^\\d.*')) { name = this.escapeReservedWord(name); } return name; } public toParamName(name) { name = this.sanitizeName(name); name = name.replace(new RegExp('-', 'g'), '_'); if (name.match('^[A-Z_]*$')) { return name; } name = DefaultCodegen.camelize(name, true); if (this.isReservedWord(name) || name.match('^\\d.*')) { name = this.escapeReservedWord(name); } return name; } public fromOperation(path, httpMethod, operation, definitions, swagger) { if (arguments.length > 4) { path = SwiftCodegen.normalizePath(path); let parameters = operation.getParameters(); parameters = parameters.filter(isHeader); operation.setParameters(parameters); return super.fromOperation( path, httpMethod, operation, definitions, swagger, ); } return super.fromOperation(path, httpMethod, operation, definitions); } public setProjectName(projectName) { this.projectName = projectName; } public setUnwrapRequired(unwrapRequired) { this.unwrapRequired = unwrapRequired; } public setResponseAs(responseAs) { this.responseAs = responseAs; } public toEnumValue(value, datatype) { if ('int' === datatype || 'double' === datatype || 'float' === datatype) { return value; } else { return "'" + this.escapeText(value) + "'"; } } public toEnumDefaultValue(value, datatype) { return datatype + '_' + value; } public toEnumVarName(name, datatype) { if ('int' === datatype || 'double' === datatype || 'float' === datatype) { let varName = String(name); varName = varName.replace(new RegExp('-', 'g'), 'MINUS_'); varName = varName.replace(new RegExp('\\+', 'g'), 'PLUS_'); varName = varName.replace(new RegExp('\\.', 'g'), '_DOT_'); return varName; } let enumName = this.sanitizeName( DefaultCodegen.underscore(name).toUpperCase(), ); enumName = enumName.replace(/^_/, ''); enumName = enumName.replace(/_$/, ''); if (enumName.match('\\d.*')) { return '_' + enumName; } else { return enumName; } } public toEnumName(property) { const enumName = this.toModelName(property.name); if (enumName.match('\\d.*')) { return '_' + enumName; } else { return enumName; } } public postProcessModels(objs) { return this.postProcessModelsEnum(objs); } public escapeQuotationMark(input) { return input.split('"').join(''); } public escapeUnsafeCharacters(input) { return input.split('*/').join('*_/').split('/*').join('/_*'); } } const isHeader = (parameter) => !(parameter instanceof HeaderParameter);
the_stack
import Vector = Utils.Maths.Vector; import DisplayObject = etch.drawing.DisplayObject; import {IApp} from './IApp'; import {ISource} from './Blocks/ISource'; import {Laser} from './Blocks/Power/Laser'; import {Logic} from './Blocks/Power/Logic/Logic'; import {MainScene} from './MainScene'; import {Source} from './Blocks/Source'; import {Void} from './Blocks/Power/Void'; import IDisplayContext = etch.drawing.IDisplayContext; import Point = etch.primitives.Point; declare var App: IApp; export class LaserBeams extends DisplayObject { public UpdateAllLasers: boolean; //private _TestPoints: Point[]; Init(drawTo: IDisplayContext): void { super.Init(drawTo); this.UpdateAllLasers = false; //this._TestPoints = []; } Update() { //console.log("BEAMS"); this.UpdateCollisions(); } QuadPartition(p1,p2,angle) { var margin = App.ScaledGridSize*1.7; var laser = p1; var target = p2; if (angle<0 && angle > -180 && target.y > (laser.y + margin)) { // NOT TOP return false; } if ((angle>0 || angle < -180) && target.y < (laser.y - margin)) { // NOT BOTTOM return false; } if (angle<=-90 && target.x > (laser.x + margin)) { // NOT LEFT return false; } if (angle>-90 && target.x < (laser.x - margin)) { // NOT LEFT return false; } return true; } PointFromLine(x, y, x0, y0, x1, y1, o) { function lineLength(x, y, x0, y0){ return Math.sqrt((x -= x0) * x + (y -= y0) * y); } if(o && !(o = function(x, y, x0, y0, x1, y1){ if(!(x1 - x0)) return {x: x0, y: y}; else if(!(y1 - y0)) return {x: x, y: y0}; var left, tg = -1 / ((y1 - y0) / (x1 - x0)); return {x: left = (x1 * (x * tg - y + y0) + x0 * (x * - tg + y - y1)) / (tg * (x1 - x0) + y0 - y1), y: tg * left - tg * x + y}; }(x, y, x0, y0, x1, y1), o.x >= Math.min(x0, x1) && o.x <= Math.max(x0, x1) && o.y >= Math.min(y0, y1) && o.y <= Math.max(y0, y1))){ var l1 = lineLength(x, y, x0, y0), l2 = lineLength(x, y, x1, y1); return l1 > l2 ? l2 : l1; } else { var a = y0 - y1, b = x1 - x0, c = x0 * y1 - y0 * x1; return Math.abs(a * x + b * y + c) / Math.sqrt(a * a + b * b); } } PointFromPoint(x, y, x0, y0){ return Math.sqrt((x -= x0) * x + (y -= y0) * y); } UpdateCollisions() { if (App.Audio.ConnectionManager.IsConnected) { var p1, p2, vector, line, outline; var rectSize = 1.7; // size of rectangle for rough check (in grid cells) var grd = App.ScaledGridSize * rectSize; // SETUP LISTS // // TODO: do this once when Blocks[] changes var voidlist = []; // we'll make a list of all void blocks so we can check those first var sourcelist = []; // get all other checks; var laserlist = []; var checklist = []; // void & source combined; for (var i = 0; i < App.Blocks.length; i++) { var block:any = App.Blocks[i]; if (block instanceof Void) { voidlist.push(block); } if ((block instanceof Source || block instanceof Logic)) { sourcelist.push(block); } if (block instanceof Laser) { laserlist.push(block); } checklist = voidlist.concat(sourcelist); // combine } // LOOK FOR LASERS // for (var i = 0; i < laserlist.length; i++) { var laser:ISource = laserlist[i]; // gets set to true when blocks are moved if (this.UpdateAllLasers) { laser.UpdateCollision = true; } // if this blocks collisions should be updated if (laser.UpdateCollision) { laser.UpdateCollision = false; laser.CheckRange = laser.Params.range; var collisions = []; // If we're in self powered mode, or if this is powered if (laser.Params.selfPoweredMode || laser.IsPowered()) { vector = Vector.multN(Vector.fromAngle(Math.degreesToRadians(laser.Params.angle)), App.ScaledUnit); line = Vector.multN(vector, laser.CheckRange); // FOR EACH LASER LOOK FOR SOURCE COLLISIONS // for (var j = 0; j < checklist.length; j++) { var block:any = checklist[j]; if (block !== laser) { // stop hitting yourself... stop hitting yourself... etc outline = []; p1 = App.Metrics.UndraggedPointOnGrid(laser.Position); p2 = App.Metrics.UndraggedPointOnGrid(block.Position); // IF IN RANGE // if (this.PointFromPoint(p1.x, p1.y, p2.x, p2.y) < ((laser.CheckRange * App.ScaledUnit) + grd)) { // IF IN QUADRANT // if (this.QuadPartition(p1, p2, laser.Params.angle)) { //IF CLOSE TO LINE // if (this.PointFromLine(p2.x, p2.y, p1.x, p1.y, p1.x + line.X, p1.y + line.Y, false) < grd) { // INTERSECT CHECK // for (var k = 0; k < block.Outline.length; k++) { outline.push(App.Metrics.UndraggedPointOnGrid(App.Metrics.GetRelativePoint(block.Outline[k], block.Position))); } p2 = new Point(p1.x + line.X, p1.y + line.Y); var intersection = Intersection.intersectLinePolygon(p1, p2, outline); if (intersection.status == "Intersection") { // THERE IS A COLLISION // // VOID BLOCKS // if (block instanceof Void) { var intersect = intersection.points; for (var h = 0; h < intersect.length; h++) { var dist = this.PointFromPoint(p1.x, p1.y, intersect[h].x, intersect[h].y) / App.ScaledUnit; if (dist < laser.CheckRange) { laser.CheckRange = dist; } } } // SOURCE BLOCKS // else { collisions.push(block); if (laser.Collisions.length == 0 || $.inArray(block, laser.Collisions) == -1) { if (block instanceof Logic) { block.ScheduleLogic(); } else { /*if (!block.IsPowered()) { block.TriggerAttack(); //block.ScheduleAttack(); }*/ //console.log(block.PowerConnections); //block.PowerConnections += 1; block.AddPower(); (<MainScene>this.DrawTo).ConnectionLines.UpdateList(); } } } } } // end line } // end quad } // end range } // end if right block }// end block loop } // end if powered // FOR EACH COLLISION CHECK RELEASE // if (laser.Collisions && laser.Collisions.length) { for (var j = 0; j < laser.Collisions.length; j++) { var block = laser.Collisions[j]; if (collisions.length == 0 || $.inArray(block, collisions) == -1) { if (!(block instanceof Logic)) { block.RemovePower(); (<MainScene>this.DrawTo).ConnectionLines.UpdateList(); } } } } // UPDATE COLLISIONS ARRAY laser.Collisions = collisions; } // end if collisions don't need updating for this block } // end laser loop this.UpdateAllLasers = false; } // end audiomanager is connected } Draw() { var unit = App.ScaledUnit; var myPos,vector; //App.FillColor(this.Ctx,App.Palette[8]); App.StrokeColor(this.Ctx,App.Palette[App.ThemeManager.Power]); this.Ctx.globalAlpha = 1; this.Ctx.lineWidth = (unit*2) * (0.8 + (Math.random()*0.5)); //this.Ctx.lineWidth = unit*2; this.Ctx.beginPath(); for (var j=0; j<App.Sources.length; j++) { var laser: ISource = App.Sources[j]; if (laser instanceof Laser) { // If we're in self powered mode, or if this is powered if (laser.Params.selfPoweredMode || laser.IsPowered()) { myPos = App.Metrics.PointOnGrid(laser.Position); vector = Vector.fromAngle(Math.degreesToRadians(laser.Params.angle)); vector.mult(laser.CheckRange * unit); this.Ctx.moveTo(myPos.x, myPos.y); this.Ctx.lineTo(myPos.x + vector.X, myPos.y + vector.Y); } } } this.Ctx.stroke(); this.Ctx.lineWidth = 1; // TEST // /*this.Ctx.beginPath(); this.Ctx.moveTo(0,0); for (var i=0; i<this._TestPoints.length; i++) { //this.Ctx.fillRect(this._TestPoints[i].x - (30*unit),this._TestPoints[i].y - (30*unit),60*unit,60*unit); this.Ctx.lineTo(this._TestPoints[i].x,this._TestPoints[i].y); } this.Ctx.stroke();*/ } }
the_stack
const home = 'Home'; const playground = 'Playground'; const test = 'Test'; const debug = 'Debug'; const account = 'Account'; const user = 'User'; const role = 'Role'; const permission = 'Permission'; const category = 'Category'; const article = 'Article'; const ax = 'Ad'; const tag = 'Tag'; const attachment = 'Attachment'; const setting = 'Setting'; const coupon = 'Coupon'; const promo = 'Promo'; const marketing = 'Marketing'; const content = 'Content'; const product = 'Product'; const address = 'Address'; const division = 'Division'; const zan = 'Collect Zan'; const auth = 'Auth'; const oauth = 'OAuth'; const action = 'Action Log'; // eslint-disable-next-line no-underscore-dangle const _lang = { test: '0x00 EN', langen: 'English', langcn: 'Chinese', 'lang-en-US': 'English', 'lang-zh-CN': '中文', 'lang-code-en-US': 'EN', 'lang-code-zh-CN': 'CN', // id: 'ID', uuid: 'UUID', category: 'Category', parentCategory: 'Parent Category', user: 'User', role: 'Role', email: 'Email', phone: 'Phone', name: 'Name', fullname: 'Fullname', title: 'Title', parent: 'Parent', slug: 'Unique Label', password: 'Password', login: 'Login', register: 'Register', status: 'Status', createdAt: 'Created At', updatedAt: 'Updated At', releasedAt: 'Released At', action: 'Action', size: 'Size', description: 'Description', link: 'Link', sort: 'Sort', upload: 'Upload', attachment: 'Attachment', empty: 'Empty', list: 'List', card: 'Card', mobile: 'Mobile', desktop: 'Desktop', banner: 'Banner', cover: 'Cover', quantity: 'Quantity', ax: 'Ad', ad: 'Ad', tag: 'Tag', icon: 'Icon', type: 'Type', value: 'Value', noData: 'No Data', options: 'Options', tips: 'Tips', unavailable: 'Unavailable', admin: 'Admin', price: 'Price', serial: 'Serial', stock: 'Stock', account: 'Account', module: 'Module', // create: 'Create', edit: 'Edit', update: 'Update', delete: 'Delete', submit: 'Submit', redeem: 'Redeem', search: 'Search', private: 'Private', public: 'Public', export: 'Export', views: 'Views', avatar: 'Avatar', creator: 'Creator', ip: 'IP', token: 'Token', info: 'Info', comingSoon: 'Coming Soon...', // select: 'Select', selected: 'Selected', selectAll: 'Select All', checkAll: 'Check all', // type_input: 'Text', type_textarea: 'Multiple Text', type_radio: 'Select', type_checkbox: 'Multiple Select', // uploadSuccessfully: 'Upload Successfully', uploadError: 'Upload Error', readSuccessfully: 'Read Successfully', createdSuccessfully: 'Created Successfully', updatedSuccessfully: 'Updated Successfully', deletedSuccessfully: 'Deleted Successfully #{{ id }}', // bannerMb: 'Banner Mb', bannerPc: 'Banner PC', galleryMb: 'Gallery Mb', galleryPc: 'Gallery PC', }; export default { _lang, _route: { home, login: _lang.login, regist: _lang.register, // playground, test, debug, testAny: 'Test Any', testAttachment: 'Test Attachment', testI18n: 'Test I18n', testStore: 'Test Store', // accountGroup: `${account}`, userGroup: `${user}`, user, createUser: `${_lang.create} ${user}`, editUser: `${_lang.edit} ${user}`, // role, createRole: `${_lang.create} ${role}`, editRole: `${_lang.edit} ${role}`, // permission, createPermission: `${_lang.create} ${permission}`, editPermission: `${_lang.edit} ${permission}`, // category, createCategory: `${_lang.create} ${category}`, editCategory: `${_lang.edit} ${category}`, // contentGroup: `${content}`, article, createArticle: `${_lang.create}${article}`, editArticle: `${_lang.edit}${article}`, // ax, createAx: `${_lang.create} ${ax}`, editAx: `${_lang.edit} ${ax}`, // tag, createTag: `${_lang.create} ${tag}`, editTag: `${_lang.edit} ${tag}`, // attachment, createAttachment: `${_lang.create} ${attachment}`, editAttachment: `${_lang.edit} ${attachment}`, // setting, // marketingGroup: `${marketing}`, coupon, createCoupon: `${_lang.create} ${coupon}`, editCoupon: `${_lang.edit} ${coupon}`, redeemCoupon: `${_lang.redeem} ${coupon}`, // promo, createPromo: `${_lang.create}${promo}`, editPromo: `${_lang.edit}${promo}`, redeemPromo: `${_lang.redeem}${promo}`, // productGroup: `${product}`, product, createProduct: `${_lang.create} ${product}`, editProduct: `${_lang.edit} ${product}`, // dataGroup: 'Data', // address, createAddress: `${_lang.create} ${address}`, editAddress: `${_lang.edit} ${address}`, // division, createDivision: `${_lang.create} ${division}`, editDivision: `${_lang.edit} ${division}`, // zan, createZan: `${_lang.create} ${zan}`, editZan: `${_lang.edit} ${zan}`, // action, createAction: `${_lang.create} ${action}`, editAction: `${_lang.edit} ${action}`, // auth, oauth, }, _comp: { SwitchLanguage: { title: 'CUR ENG', }, UserMenu: { safelyLogout: 'Safely Logout', logoutFaild: 'Logout Faild', }, TableColumnDeleteButton: { confirmDeleteItem: 'Confirm Delete', }, SelectTagId: { searchTags: 'Search Tags', notFoundTags: 'Not Found Tags', addTag: 'Add Tag', canAlsoAddTagsQuantity: 'You could add Tag {{ length }}', createAndAdd: 'Create and Add', }, SearchInput: { placeholder: 'Search...', }, CouponItem: { unavailable: 'Unavailable', moreThanAmount: 'More than', isAvailable: 'available', }, TableColumnStatusSwitch: { updatedSuccessfully: '#{{ id }} Status Updated To ', }, UserSearchBox: { searchUsers: 'Search User', }, TableCard: { totalLength: 'Total {{ length }} Items', selectedItems: '{{ length }} Items Selected', }, ConfirmDeleteButton: { confirmDeleteMessage: 'Confirm Deletion, PRESS AGAIN', }, }, _page: { Auth: { Login: { title: 'DASHBOARD', subTitle: 'Welcome Back, Please login to your account', email: 'Email', account: 'Account', accountTips: 'Phone or Email', password: _lang.password, login: _lang.login, rememberPassword: 'Remember Password', back: 'Back', notPermissions: 'Not Premissions', backTips: 'here is not back now ; >', captcha: 'Captcha', }, // openId: 'Open Id', userId: 'User Id', unionId: 'Union Id', platform: 'Platform', nickname: 'Nickname', lastAuthAt: 'Last Auth At', }, User: { userInfo: 'User Info', userRoles: 'User Roles', userAvatar: 'User Avatar', deleteAuthAvatar: 'Delete Avatar', }, Role: { roleInfo: 'Role Info', rolePermissions: 'Role Permissions', }, Permission: { permissionInfo: 'Permission Info', }, Category: { categoryInfo: 'Category Info', }, Article: { articleInfo: 'Article Info', articleContent: 'Article Content', extendedInfo: 'Extended Info', }, Ax: { axInfo: 'Ad Info', axImage: 'Ad Image', }, Setting: { pleaseSelectTheTypeFirst: 'Please select the type first', options: 'Options', optionsTips: 'One per line', confirmDelete: 'Confirm Delete Setting', }, Tag: { count: 'Count', tagInfo: 'Tag Info', }, Coupon: { couponInfo: 'Coupon Info', couponCodeStatusTitle: 'Coupon Code', startTime: 'Start Time', expireTime: 'Expire Time', amount: 'Amount', code: 'Code', overAmount: 'Over Amount', availableDate: 'Available Date', availableProductIds: 'Available Product', unavailableProductIds: 'Unvailable Product', redeem: 'Redeem', redeemConpon: 'Redeem Coupon', redeemToUser: 'Redeem Coupon To User', redeemUser: 'Redeem User', accessOrder: 'Access Order', }, Promo: { promoInfo: 'Promo Info', promoCodeStatusTitle: 'Promo Code', startTime: 'Start Time', expireTime: 'Expire Time', amount: 'Amount', overAmount: 'Over Amount', availableDate: 'Available Date', availableProductIds: 'Available Product', unavailableProductIds: 'Unvailable Product', redeemedQuantity: 'redeemed Quantity', }, Product: { productInfo: 'Product Info', productContent: 'Product Content', putOnSale: 'Put On Sale', price: 'Price', productName: 'Product Name', productFullname: 'Product Fullname', costPrice: 'Cost Price', marketPrice: 'Market Price', brand: 'Brand', style: 'Style', banner: 'Banner', // productImage: 'Product Images', bannerMb: 'Banner MB', galleryMb: 'Gallery MB', bannerPc: 'Banner PC', galleryPc: 'Gallery PC', }, Address: { province: 'Province', city: 'City', area: 'Area', areaLabel: 'Area', address: 'Address', consignee: 'Consignee', zip: 'Zip', phone: 'Phone', status: 'Status', // addressInfo: 'Address Info', }, Division: { name: 'Name', provinceCode: 'Province Code', cityCode: 'City Code', areaCode: 'Area Code', code: 'Code', // divisionData: 'Division Data', expandedAll: 'Expanded All', collapseAll: 'Collapse All', }, Zan: { views: 'Views', zanInfo: 'Zan Info', zanUserList: 'Zan Users', targetZanQuantity: 'Quantity of Target Zan', currentZanQuantity: 'Quantity of Current Zan', currentTargetZanQuantity: 'Current / Target', like: 'Like', liked: 'Liked', deletedLikeUser: 'Deleted Like User', }, Test: { getApiError: 'Get Api Error', getApiMessage: 'Get Api Message', }, Action: { actionInfo: 'Action Log Info', }, }, };
the_stack
import { LoggerService } from 'src/chat21-core/providers/abstract/logger.service'; import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; // firebase // import * as firebase from 'firebase/app'; import firebase from "firebase/app"; import 'firebase/messaging'; import 'firebase/database'; import 'firebase/auth'; import 'firebase/storage'; // models import { ConversationModel } from '../../models/conversation'; // services import { ConversationsHandlerService } from '../abstract/conversations-handler.service'; // utils import { avatarPlaceholder, getColorBck } from '../../utils/utils-user'; import { compareValues, getFromNow, searchIndexInArrayForUid, archivedConversationsPathForUserId, isGroup } from '../../utils/utils'; import { ImageRepoService } from '../abstract/image-repo.service'; import { FirebaseImageRepoService } from './firebase-image-repo'; import { ArchivedConversationsHandlerService } from '../abstract/archivedconversations-handler.service'; import { CustomLogger } from '../logger/customLogger'; import { LoggerInstance } from '../logger/loggerInstance'; // @Injectable({ providedIn: 'root' }) @Injectable() export class FirebaseArchivedConversationsHandler extends ArchivedConversationsHandlerService { // BehaviorSubject BSConversationDetail: BehaviorSubject<ConversationModel>; // readAllMessages: BehaviorSubject<string>; archivedConversationAdded: BehaviorSubject<ConversationModel>; archivedConversationChanged: BehaviorSubject<ConversationModel>; archivedConversationRemoved: BehaviorSubject<ConversationModel>; loadedConversationsStorage: BehaviorSubject<ConversationModel[]>; // public params archivedConversations: Array<ConversationModel> = []; uidConvSelected: string; tenant: string; // imageRepo: ImageRepoService = new FirebaseImageRepoService(); // private params private loggedUserId: string; private translationMap: Map<string, string>; private isConversationClosingMap: Map<string, boolean>; private logger: LoggerService = LoggerInstance.getInstance() private ref: firebase.database.Query; constructor( //public databaseProvider: DatabaseProvider ) { super(); } /** * inizializzo conversations handler */ initialize(tenant: string, userId: string, translationMap: Map<string, string>) { this.logger.info('[initialize FROM [APP-COMP] - FIREBASEArchivedConversationsHandlerSERVICE] tenant ', tenant, ' - userId: ', userId, ' - translationMap: ', translationMap) this.tenant = tenant; this.loggedUserId = userId; this.translationMap = translationMap; this.archivedConversations = []; this.isConversationClosingMap = new Map(); //this.databaseProvider.initialize(userId, this.tenant); //this.getConversationsFromStorage(); } /** * mi connetto al nodo conversations * creo la reference * mi sottoscrivo a change, removed, added */ // connect() { // const that = this; // const urlNodeFirebase = archivedConversationsPathForUserId(this.tenant, this.loggedUserId); // this.logger.printDebug('connect -------> conversations::ARCHIVED', urlNodeFirebase) // this.ref = firebase.database().ref(urlNodeFirebase).orderByChild('timestamp').limitToLast(200); // this.ref.on('child_changed', (childSnapshot) => { // that.changed(childSnapshot); // }); // this.ref.on('child_removed', (childSnapshot) => { // that.removed(childSnapshot); // }); // this.ref.on('child_added', (childSnapshot) => { // that.added(childSnapshot); // }); // } // --------------------------------------------------------------------------------- // New connect - renamed subscribeToConversation //---------------------------------------------------------------------------------- subscribeToConversations(callback: any) { const that = this; const urlNodeFirebase = archivedConversationsPathForUserId(this.tenant, this.loggedUserId); this.logger.debug('[FIREBASEArchivedConversationsHandlerSERVICE] SubscribeToConversations conversations::ARCHIVED urlNodeFirebase', urlNodeFirebase) this.ref = firebase.database().ref(urlNodeFirebase).orderByChild('timestamp').limitToLast(200); this.ref.on('child_changed', (childSnapshot) => { that.changed(childSnapshot); }); this.ref.on('child_removed', (childSnapshot) => { that.removed(childSnapshot); }); this.ref.on('child_added', (childSnapshot) => { that.added(childSnapshot); }); setTimeout(() => { callback() }, 2000); // SET AUDIO // this.audio = new Audio(); // this.audio.src = URL_SOUND; // this.audio.load(); } /** * restituisce il numero di conversazioni nuove */ countIsNew(): number { let num = 0; this.archivedConversations.forEach((element) => { if (element.is_new === true) { num++; } }); return num; } //imposto la conversazione come: letta setConversationRead(conversationrecipient): void { this.logger.log('[CONVS-DETAIL][FB-ARCHIVED] updateConversationBadge: '); const urlUpdate = archivedConversationsPathForUserId(this.tenant, this.loggedUserId) + '/' + conversationrecipient; const update = {}; update['/is_new'] = false; firebase.database().ref(urlUpdate).update(update); } /** * Returns the status of the conversations with conversationId from isConversationClosingMap * @param conversationId the conversation id * @returns true if the conversation is waiting to be closed, false otherwise */ getClosingConversation(conversationId: string) { return this.isConversationClosingMap[conversationId]; } /** * Add the conversation with conversationId to the isConversationClosingMap * @param conversationId the id of the conversation of which it wants to save the state * @param status true if the conversation is waiting to be closed, false otherwise */ setClosingConversation(conversationId: string, status: boolean) { this.isConversationClosingMap[conversationId] = status; } /** * Delete the conversation with conversationId from the isConversationClosingMap * @param conversationId the id of the conversation of which is wants to delete */ deleteClosingConversation(conversationId: string) { this.isConversationClosingMap.delete(conversationId); } getConversationDetail(conversationId: string, callback: (conv: ConversationModel) => void) { const conversation = this.archivedConversations.find(item => item.uid === conversationId); this.logger.log('[FIREBASEArchivedConversationsHandlerSERVICE] SubscribeToConversations getConversationDetail::ARCHIVED *****: ', conversation) if (conversation) { callback(conversation) // this.BSConversationDetail.next(conversationSelected); } else { // const urlNodeFirebase = '/apps/' + this.tenant + '/users/' + this.loggedUserId + '/archived_conversations/' + conversationId; const urlNodeFirebase = archivedConversationsPathForUserId(this.tenant, this.loggedUserId) + '/' + conversationId; this.logger.log('[FIREBASEArchivedConversationsHandlerSERVICE] urlNodeFirebase conversationDetail *****', urlNodeFirebase) const firebaseMessages = firebase.database().ref(urlNodeFirebase); firebaseMessages.on('value', (childSnapshot) => { const childData: ConversationModel = childSnapshot.val(); this.logger.log('[FIREBASEArchivedConversationsHandlerSERVICE] childData *****', childData) // if (childSnapshot && childSnapshot.key && childData.uid) { if (childSnapshot && childSnapshot.key && childData) { childData.uid = childSnapshot.key; const conversation = this.completeConversation(childData); if (conversation) { callback(conversation) } else { callback(null) } } // this.BSConversationDetail.next(conversation); }); } } /** * dispose reference di conversations */ dispose() { this.archivedConversations = []; this.uidConvSelected = ''; //this.ref.off(); // this.ref.off("child_changed"); // this.ref.off("child_removed"); // this.ref.off("child_added"); this.logger.debug('[FIREBASEArchivedConversationsHandlerSERVICE] DISPOSE::: ', this.ref) } // ---------------------------------------------------------- // // BEGIN PRIVATE FUNCTIONS // ---------------------------------------------------------- // /** * */ // private getConversationsFromStorage() { // const that = this; // this.databaseProvider.getConversations() // .then((conversations: [ConversationModel]) => { // that.loadedConversationsStorage.next(conversations); // }) // .catch((e) => { // console.log('error: ', e); // }); // } // /** DEPRECATED // * // * @param childSnapshot // */ private conversationGenerate(childSnapshot: any): boolean { const childData: ConversationModel = childSnapshot.val(); childData.uid = childSnapshot.key; const conversation = this.completeConversation(childData); if (this.isValidConversation(conversation)) { this.setClosingConversation(childSnapshot.key, false); const index = searchIndexInArrayForUid(this.archivedConversations, conversation.uid); if (index > -1) { this.archivedConversations.splice(index, 1, conversation); } else { this.archivedConversations.splice(0, 0, conversation); } //this.databaseProvider.setConversation(conversation); this.archivedConversations.sort(compareValues('timestamp', 'desc')); return true; } else { return false; } } /** * * @param childSnapshot */ // private conversationGenerate(childSnapshot: any): ConversationModel { // console.log('conversationGenerate: ', childSnapshot.val()); // const childData: ConversationModel = childSnapshot.val(); // childData.uid = childSnapshot.key; // const conversation = this.completeConversation(childData); // if (this.isValidConversation(conversation)) { // this.setClosingConversation(childSnapshot.key, false); // const index = searchIndexInArrayForUid(this.conversations, conversation.uid); // if (index > -1) { // this.conversations.splice(index, 1, conversation); // } else { // this.conversations.splice(0, 0, conversation); // } // //this.databaseProvider.setConversation(conversation); // this.conversations.sort(compareValues('timestamp', 'desc')); // if (conversation.is_new) { // this.soundMessage(); // } // return conversation; // } else { // return null; // } // } // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice /** * 1 - completo la conversazione con i parametri mancanti * 2 - verifico che sia una conversazione valida * 3 - salvo stato conversazione (false) nell'array delle conversazioni chiuse * 4 - aggiungo alla pos 0 la nuova conversazione all'array di conversazioni * o sostituisco la conversazione con quella preesistente * 5 - salvo la conversazione nello storage * 6 - ordino l'array per timestamp * 7 - pubblico conversations:update */ private added(childSnapshot: any) { if (this.conversationGenerate(childSnapshot)) { const index = searchIndexInArrayForUid(this.archivedConversations, childSnapshot.key); if (index > -1) { const conversationAdded = this.archivedConversations[index] this.archivedConversationAdded.next(conversationAdded); } } else { this.logger.error('[FIREBASEArchivedConversationsHandlerSERVICE] ADDED::conversations with conversationId: ', childSnapshot.key, 'is not valid') } } /** * 1 - completo la conversazione con i parametri mancanti * 2 - verifico che sia una conversazione valida * 3 - aggiungo alla pos 0 la nuova conversazione all'array di conversazioni * 4 - salvo la conversazione nello storage * 5 - ordino l'array per timestamp * 6 - pubblico conversations:update * 7 - attivo sound se è un msg nuovo */ //TODO-GAB: fare emit singola conversation e non dell'intero array di conversations private changed(childSnapshot: any) { if (this.conversationGenerate(childSnapshot)) { const index = searchIndexInArrayForUid(this.archivedConversations, childSnapshot.key); if (index > -1) { const conversationChanged = this.archivedConversations[index] this.archivedConversationChanged.next(conversationChanged); } } else { this.logger.error('[FIREBASEArchivedConversationsHandlerSERVICE] CHANGED::conversations with conversationId: ', childSnapshot.key, 'is not valid') } } /** * 1 - cerco indice conversazione da eliminare * 2 - elimino conversazione da array conversations * 3 - elimino la conversazione dallo storage * 4 - pubblico conversations:update * 5 - elimino conversazione dall'array delle conversazioni chiuse */ private removed(childSnapshot: any) { const index = searchIndexInArrayForUid(this.archivedConversations, childSnapshot.key); if (index > -1) { const conversationRemoved = this.archivedConversations[index] this.archivedConversations.splice(index, 1); // this.conversations.sort(compareValues('timestamp', 'desc')); //this.databaseProvider.removeConversation(childSnapshot.key); this.archivedConversationRemoved.next(conversationRemoved); } // remove the conversation from the isConversationClosingMap this.deleteClosingConversation(childSnapshot.key); } /** * Completo conversazione aggiungendo: * 1 - nel caso in cui sender_fullname e recipient_fullname sono vuoti, imposto i rispettivi id come fullname, * in modo da avere sempre il campo fullname popolato * 2 - imposto conversation_with e conversation_with_fullname con i valori del sender o al recipient, * a seconda che il sender corrisponda o meno all'utente loggato. Aggiungo 'tu:' se il sender coincide con il loggedUser * Se il sender NON è l'utente loggato, ma è una conversazione di tipo GROUP, il conversation_with_fullname * sarà uguale al recipient_fullname * 3 - imposto stato conversazione, che indica se ci sono messaggi non letti nella conversazione * 4 - imposto il tempo trascorso tra l'ora attuale e l'invio dell'ultimo messaggio * 5 - imposto avatar, colore e immagine * @param conv */ private completeConversation(conv): ConversationModel { conv.selected = false; if (!conv.sender_fullname || conv.sender_fullname === 'undefined' || conv.sender_fullname.trim() === '') { conv.sender_fullname = conv.sender; } if (!conv.recipient_fullname || conv.recipient_fullname === 'undefined' || conv.recipient_fullname.trim() === '') { conv.recipient_fullname = conv.recipient; } let conversation_with_fullname = conv.sender_fullname; let conversation_with = conv.sender; if (conv.sender === this.loggedUserId) { conversation_with = conv.recipient; conversation_with_fullname = conv.recipient_fullname; conv.sender_fullname = this.translationMap.get('YOU') // conv.last_message_text = YOU + conv.last_message_text; // } else if (conv.channel_type === TYPE_GROUP) { } else if (isGroup(conv)) { // conversation_with_fullname = conv.sender_fullname; // conv.last_message_text = conv.last_message_text; conversation_with = conv.recipient; conversation_with_fullname = conv.recipient_fullname; } // Fixes the bug: if a snippet of code is pasted and sent it is not displayed correctly in the archived convesations list // conv.last_message_text = htmlEntities(conv.last_message_text) conv.conversation_with = conversation_with; conv.conversation_with_fullname = conversation_with_fullname; conv.status = this.setStatusConversation(conv.sender, conv.uid); // conv.time_last_message = this.getTimeLastMessage(conv.timestamp); // evaluate if is used conv.avatar = avatarPlaceholder(conversation_with_fullname); conv.color = getColorBck(conversation_with_fullname); conv.archived = true; //conv.image = this.imageRepo.getImagePhotoUrl(conversation_with); return conv; } /** */ private setStatusConversation(sender: string, uid: string): string { let status = '0'; // letto if (sender === this.loggedUserId || uid === this.uidConvSelected) { status = '0'; } else { status = '1'; // non letto } return status; } /** * calcolo il tempo trascorso da ora al timestamp passato * @param timestamp */ private getTimeLastMessage(timestamp: string) { const timestampNumber = parseInt(timestamp, 10) / 1000; const time = getFromNow(timestampNumber); return time; } /** * check if the conversations is valid or not */ private isValidConversation(convToCheck: ConversationModel): boolean { if (!this.isValidField(convToCheck.uid)) { return false; } if (!this.isValidField(convToCheck.is_new)) { return false; } if (!this.isValidField(convToCheck.last_message_text)) { return false; } if (!this.isValidField(convToCheck.recipient)) { return false; } if (!this.isValidField(convToCheck.recipient_fullname)) { return false; } if (!this.isValidField(convToCheck.sender)) { return false; } if (!this.isValidField(convToCheck.sender_fullname)) { return false; } if (!this.isValidField(convToCheck.status)) { return false; } if (!this.isValidField(convToCheck.timestamp)) { return false; } if (!this.isValidField(convToCheck.channel_type)) { return false; } return true; } /** * * @param field */ private isValidField(field: any): boolean { return (field === null || field === undefined) ? false : true; } // ---------------------------------------------------------- // // END PRIVATE FUNCTIONS // ---------------------------------------------------------- // }
the_stack
import { ITextFeaturizer } from "./ITextFeaturizer"; import { ISparseTextFeaturizer } from "./ISparseTextFeaturizer"; import { DictionaryMapUtility } from "../../../data_structure/DictionaryMapUtility"; import { Utility } from "../../../utility/Utility"; export class NgramSubwordFeaturizer implements ISparseTextFeaturizer { protected numberHashingFeaturesSetting: number = 0; protected subwordNgramBegin: number = 3; protected subwordNgramEnd: number = 4; protected toLowercase: boolean = true; protected toRemovePunctuations: boolean = false; protected toRemoveEmptyElements: boolean = true; protected splitDelimiter: string = " "; protected intentsUtterancesWeights: { "intents": string[], "utterances": string[], "weights": number[] } = { intents: [], utterances: [], weights: [] }; protected labels: string[] = []; protected labelMap: Map<string, number> = new Map<string, number>(); protected features: string[] = []; protected featureMap: Map<string, number> = new Map<string, number>(); protected hashingFeatureArrays: Array<Set<string>> = []; constructor( subwordNgramBegin: number = 3, subwordNgramEnd: number = 4, toLowercase: boolean = true, toRemovePunctuations: boolean = false, toRemoveEmptyElements: boolean = true, splitDelimiter: string = " ", numberHashingFeaturesSetting: number = 0) { this.subwordNgramBegin = subwordNgramBegin; this.subwordNgramEnd = subwordNgramEnd; this.toLowercase = toLowercase; this.toRemovePunctuations = toRemovePunctuations; this.toRemoveEmptyElements = toRemoveEmptyElements; this.splitDelimiter = splitDelimiter; this.numberHashingFeaturesSetting = numberHashingFeaturesSetting; } public getIntentsUtterancesWeights(): { "intents": string[], "utterances": string[], "weights": number[] } { return this.intentsUtterancesWeights; } public getLabels(): string[] { return this.labels; } public getLabelMap(): Map<string, number> { return this.labelMap; } public getFeatures(): string[] { return this.features; } public getFeatureMap(): Map<string, number> { return this.featureMap; } public getHashingFeatureArrays(): Array<Set<string>> { return this.hashingFeatureArrays; } public getNumberHashingFeaturesSetting(): number { return this.numberHashingFeaturesSetting; } public getNumberLabels(): number { return this.getLabels().length; } public getNumberFeatures(): number { return this.getFeatures().length; } public getNumberHashingFeatures(): number { return this.getHashingFeatureArrays().length; } public getHashingFeatureIndex(feature: string): number { const numberHashingFeatures: number = this.getNumberHashingFeatures(); if (numberHashingFeatures <= 0) { Utility.debuggingThrow( "numberHashingFeaturesSetting <= 0"); } const featureHashCode: number = Utility.getPositiveStringHashCode(feature); return (featureHashCode % numberHashingFeatures); } public getLabelIndex(label: string, throwIfNonExistentLabel: boolean = true): number { if (Utility.isEmptyString(label)) { Utility.debuggingThrow("label == null"); } let labelId: number = -1; if (!this.labelMap) { Utility.debuggingThrow("this.labelMap == null"); } if (this.labelMap.has(label)) { labelId = this.labelMap.get(label) as number; } if (labelId < 0) { if (throwIfNonExistentLabel) { Utility.debuggingThrow(`label=${label} does not exist in this.labelMap=${DictionaryMapUtility.jsonStringifyStringKeyGenericValueNativeMap(this.labelMap)}`); } } return labelId; } public getFeatureIndex(feature: string, throwIfNonExistentLabel: boolean = true): number { if (!feature) { Utility.debuggingThrow("feature == null"); } let featureId: number = -1; if (!this.featureMap) { Utility.debuggingThrow("this.featureMap == null"); } if (this.featureMap.has(feature)) { featureId = this.featureMap.get(feature) as number; } if (featureId < 0) { if (throwIfNonExistentLabel) { Utility.debuggingThrow(`feature=${feature} does not exist in this.featureMap=${this.featureMap}`); } } return featureId; } public createFeatureSparseIndexArray(input: string): number[] { const featureSparseIndexArray: number[] = new Array<number>(); const features: string[] = this.featurize(input); if (!this.featureMap) { Utility.debuggingThrow("this.featureMap==null"); } features.forEach(function(this: NgramSubwordFeaturizer, feature: string) { if (!feature) { Utility.debuggingThrow(`EXCEPTION: feature==null, input=$${input}$, feature=$${feature}$`); } let featureId: number = -1; if (this.featureMap.has(feature)) { featureId = this.featureMap.get(feature) as number; } if (featureId >= 0) { featureSparseIndexArray.push(featureId); } }, this); return featureSparseIndexArray; } public createFeatureSparseIndexArrays(inputs: string[]): number[][] { const inputArrays: number[][] = inputs.map((input) => this.createFeatureSparseIndexArray(input), this); return inputArrays; } public createIntentUtteranceSparseIndexArrays( intentsUtterancesWeights: { "intents": string[], "utterances": string[], "weights": number[] }): { "intentLabelIndexArray": number[], "utteranceFeatureIndexArrays": number[][] } { const intents: string[] = intentsUtterancesWeights.intents; const utterances: string[] = intentsUtterancesWeights.utterances; const weights: number[] = intentsUtterancesWeights.weights; const intentLabelIndexArray: number[] = intents.map((intent) => this.getLabelIndex(intent), this); const utteranceFeatureIndexArrays: number[][] = utterances.map((utterance) => this.createFeatureSparseIndexArray(utterance), this); return { intentLabelIndexArray, utteranceFeatureIndexArrays }; } public createFeatureMiniBatchingSparseIndexArrays( inputs: string[], miniBatchIndexBegin: number = 0, miniBatchIndexEnd: number = 0): number[][] { if (miniBatchIndexBegin < 0) { miniBatchIndexBegin = 0; } if (miniBatchIndexEnd <= 0) { miniBatchIndexEnd = inputs.length; } const miniBatchNumber: number = miniBatchIndexEnd - miniBatchIndexBegin; if (miniBatchNumber <= 0) { Utility.debuggingThrow( `miniBatchNumber <= 0`); } const inputArrays: number[][] = new Array<number[]>(miniBatchNumber); let miniBatchIndex = 0; for (let i: number = miniBatchIndexBegin; i < miniBatchIndexEnd; i++) { inputArrays[miniBatchIndex++] = this.createFeatureSparseIndexArray(inputs[i]); } return inputArrays; } public createIntentUtteranceMiniBatchingSparseIndexArrays( intentsUtterancesWeights: { "intents": string[], "utterances": string[], "weights": number[] }, miniBatchIndexBegin: number = 0, miniBatchIndexEnd: number = 0): { "intentLabelIndexArray": number[], "utteranceFeatureIndexArrays": number[][] } { const intents: string[] = intentsUtterancesWeights.intents; const utterances: string[] = intentsUtterancesWeights.utterances; const weights: number[] = intentsUtterancesWeights.weights; const intentLabelIndexArray: number[] = intents .slice(miniBatchIndexBegin, miniBatchIndexEnd) .map((intent) => this.getLabelIndex(intent), this); const utteranceFeatureIndexArrays: number[][] = utterances .slice(miniBatchIndexBegin, miniBatchIndexEnd) .map((utterance) => this.createFeatureSparseIndexArray(utterance), this); return { intentLabelIndexArray, utteranceFeatureIndexArrays }; } public createFeatureHashingSparseIndexArray( input: string): number[] { const featureArray: number[] = new Array(); const features: string[] = this.featurize(input); features.forEach(function(this: NgramSubwordFeaturizer, feature: string) { if (!feature) { Utility.debuggingThrow("feature==null"); } const featureId: number = this.getHashingFeatureIndex(feature); if (featureId >= 0) { featureArray.push(featureId); } }, this); return featureArray; } public createFeatureHashingSparseIndexArrays( inputs: string[]): number[][] { const inputArrays: number[][] = inputs.map((input) => this.createFeatureHashingSparseIndexArray(input), this); return inputArrays; } public createIntentUtteranceHashingSparseIndexArrays( intentsUtterancesWeights: { "intents": string[], "utterances": string[], "weights": number[] }): { "intentLabelIndexArray": number[], "utteranceFeatureIndexArrays": number[][] } { const intents: string[] = intentsUtterancesWeights.intents; const utterances: string[] = intentsUtterancesWeights.utterances; const weights: number[] = intentsUtterancesWeights.weights; const intentLabelIndexArray: number[] = intents.map((intent) => this.getLabelIndex(intent), this); const utteranceFeatureIndexArrays: number[][] = utterances.map((utterance) => this.createFeatureHashingSparseIndexArray(utterance), this); return { intentLabelIndexArray, utteranceFeatureIndexArrays }; } public createLabelOneHotEncoderBooleanArray( label: string, throwIfNonExistentLabel: boolean = true): boolean[] { if (Utility.isEmptyString(label)) { Utility.debuggingThrow("label == null"); } let labelId: number = -1; if (!this.labelMap) { Utility.debuggingThrow("this.labelMap == null"); } if (this.labelMap.has(label)) { labelId = this.labelMap.get(label) as number; } const numberLabels: number = this.getNumberLabels(); const labelArray: boolean[] = new Array(numberLabels).fill(0); if (labelId >= 0) { labelArray[labelId] = true; } else { if (throwIfNonExistentLabel) { Utility.debuggingThrow(`label=${label} does not exist in this.labelMap=${DictionaryMapUtility.jsonStringifyStringKeyGenericValueNativeMap(this.labelMap)}`); } } return labelArray; } public createLabelOneHotEncoderNumberArray( label: string, throwIfNonExistentLabel: boolean = true): number[] { if (Utility.isEmptyString(label)) { Utility.debuggingThrow("label == null"); } let labelId: number = -1; if (!this.labelMap) { Utility.debuggingThrow("this.labelMap == null"); } if (this.labelMap.has(label)) { labelId = this.labelMap.get(label) as number; } const numberLabels: number = this.getNumberLabels(); const labelArray: number[] = new Array(numberLabels).fill(0); if (labelId >= 0) { labelArray[labelId] = 1; } else { if (throwIfNonExistentLabel) { Utility.debuggingThrow(`label=${label} does not exist in this.labelMap=${DictionaryMapUtility.jsonStringifyStringKeyGenericValueNativeMap(this.labelMap)}`); } } return labelArray; } public createFeatureOneHotEncoderBooleanArray( input: string): boolean[] { const numberFeatures: number = this.getNumberFeatures(); const featureArray: boolean[] = new Array(numberFeatures).fill(0); const features: string[] = this.featurize(input); if (!this.featureMap) { Utility.debuggingThrow("this.featureMap == null"); } features.forEach(function(this: NgramSubwordFeaturizer, feature: string) { if (!feature) { Utility.debuggingThrow("feature==null"); } let featureId: number = -1; if (this.featureMap.has(feature)) { featureId = this.featureMap.get(feature) as number; } if (featureId >= 0) { featureArray[featureId] = true; } }, this); return featureArray; } public createFeatureOneHotEncoderNumberArray( input: string): number[] { const numberFeatures: number = this.getNumberFeatures(); const featureArray: number[] = new Array(numberFeatures).fill(0); const features: string[] = this.featurize(input); if (!this.featureMap) { Utility.debuggingThrow("this.featureMap==null"); } features.forEach(function(this: NgramSubwordFeaturizer, feature: string) { if (!feature) { Utility.debuggingThrow(`EXCEPTION: feature==null, input=$${input}$, feature=$${feature}$`); } let featureId: number = -1; if (this.featureMap.has(feature)) { featureId = this.featureMap.get(feature) as number; } if (featureId >= 0) { featureArray[featureId] = 1; } }, this); return featureArray; } public createFeatureOneHotEncoderBooleanArrays( inputs: string[]): boolean[][] { const inputArrays: boolean[][] = inputs.map((input) => this.createFeatureOneHotEncoderBooleanArray(input), this); return inputArrays; } public createFeatureOneHotEncoderNumberArrays( inputs: string[]): number[][] { const inputArrays: number[][] = inputs.map((input) => this.createFeatureOneHotEncoderNumberArray(input), this); return inputArrays; } public createIntentUtteranceOneHotEncoderBooleanArrays( intentsUtterancesWeights: { "intents": string[], "utterances": string[], "weights": number[] }): { "intentLabelIndexArrays": boolean[][], "utteranceFeatureIndexArrays": boolean[][] } { const intents: string[] = intentsUtterancesWeights.intents; const utterances: string[] = intentsUtterancesWeights.utterances; const weights: number[] = intentsUtterancesWeights.weights; const intentLabelIndexArrays: boolean[][] = intents.map((intent) => this.createLabelOneHotEncoderBooleanArray(intent), this); const utteranceFeatureIndexArrays: boolean[][] = utterances.map((utterance) => this.createFeatureOneHotEncoderBooleanArray(utterance), this); return { intentLabelIndexArrays, utteranceFeatureIndexArrays }; } public createIntentUtteranceOneHotEncoderNumberArrays( intentsUtterancesWeights: { "intents": string[], "utterances": string[], "weights": number[] }): { "intentLabelIndexArrays": number[][], "utteranceFeatureIndexArrays": number[][] } { const intents: string[] = intentsUtterancesWeights.intents; const utterances: string[] = intentsUtterancesWeights.utterances; const weights: number[] = intentsUtterancesWeights.weights; const intentLabelIndexArrays: number[][] = intents.map((intent) => this.createLabelOneHotEncoderNumberArray(intent), this); const utteranceFeatureIndexArrays: number[][] = utterances.map((utterance) => this.createFeatureOneHotEncoderNumberArray(utterance), this); return { intentLabelIndexArrays, utteranceFeatureIndexArrays }; } public createFeatureMiniBatchingOneHotEncoderBooleanArrays( inputs: string[], miniBatchIndexBegin: number = 0, miniBatchIndexEnd: number = 0): boolean[][] { if (miniBatchIndexBegin < 0) { miniBatchIndexBegin = 0; } if (miniBatchIndexEnd <= 0) { miniBatchIndexEnd = inputs.length; } const miniBatchNumber: number = miniBatchIndexEnd - miniBatchIndexBegin; if (miniBatchNumber <= 0) { return new Array<boolean[]>(); } const inputArrays: boolean[][] = new Array<boolean[]>(miniBatchNumber); let miniBatchIndex = 0; for (let i: number = miniBatchIndexBegin; i < miniBatchIndexEnd; i++) { inputArrays[miniBatchIndex++] = this.createFeatureOneHotEncoderBooleanArray(inputs[i]); } return inputArrays; } public createFeatureMiniBatchingOneHotEncoderNumberArrays( inputs: string[], miniBatchIndexBegin: number = 0, miniBatchIndexEnd: number = 0): number[][] { if (miniBatchIndexBegin < 0) { miniBatchIndexBegin = 0; } if (miniBatchIndexEnd <= 0) { miniBatchIndexEnd = inputs.length; } const miniBatchNumber: number = miniBatchIndexEnd - miniBatchIndexBegin; if (miniBatchNumber <= 0) { return new Array<number[]>(); } const inputArrays: number[][] = new Array<number[]>(miniBatchNumber); let miniBatchIndex = 0; for (let i: number = miniBatchIndexBegin; i < miniBatchIndexEnd; i++) { inputArrays[miniBatchIndex++] = this.createFeatureOneHotEncoderNumberArray(inputs[i]); } return inputArrays; } public createIntentUtteranceMiniBatchingOneHotEncoderBooleanArrays( intentsUtterancesWeights: { "intents": string[], "utterances": string[], "weights": number[] }, miniBatchIndexBegin: number = 0, miniBatchIndexEnd: number = 0): { "intentLabelIndexArrays": boolean[][], "utteranceFeatureIndexArrays": boolean[][] } { const intents: string[] = intentsUtterancesWeights.intents; const utterances: string[] = intentsUtterancesWeights.utterances; const weights: number[] = intentsUtterancesWeights.weights; const intentLabelIndexArrays: boolean[][] = intents .slice(miniBatchIndexBegin, miniBatchIndexEnd) .map((intent) => this.createLabelOneHotEncoderBooleanArray(intent), this); const utteranceFeatureIndexArrays: boolean[][] = utterances .slice(miniBatchIndexBegin, miniBatchIndexEnd) .map((utterance) => this.createFeatureOneHotEncoderBooleanArray(utterance), this); return { intentLabelIndexArrays, utteranceFeatureIndexArrays }; } public createIntentUtteranceMiniBatchingOneHotEncoderNumberArrays( intentsUtterancesWeights: { "intents": string[], "utterances": string[], "weights": number[] }, miniBatchIndexBegin: number = 0, miniBatchIndexEnd: number = 0): { "intentLabelIndexArrays": number[][], "utteranceFeatureIndexArrays": number[][] } { const intents: string[] = intentsUtterancesWeights.intents; const utterances: string[] = intentsUtterancesWeights.utterances; const weights: number[] = intentsUtterancesWeights.weights; const intentLabelIndexArrays: number[][] = intents .slice(miniBatchIndexBegin, miniBatchIndexEnd) .map((intent) => this.createLabelOneHotEncoderNumberArray(intent), this); const utteranceFeatureIndexArrays: number[][] = utterances .slice(miniBatchIndexBegin, miniBatchIndexEnd) .map((utterance) => this.createFeatureOneHotEncoderNumberArray(utterance), this); return { intentLabelIndexArrays, utteranceFeatureIndexArrays }; } public createFeatureHashingOneHotEncoderBooleanArray(input: string): boolean[] { const featureArray: boolean[] = new Array(this.numberHashingFeaturesSetting).fill(0); const features: string[] = this.featurize(input); features.forEach(function(this: NgramSubwordFeaturizer, feature: string, index: number, array: string[]) { if (!feature) { Utility.debuggingThrow("feature==null"); } const featureId: number = this.getHashingFeatureIndex(feature); if (featureId >= 0) { featureArray[featureId] = true; } }, this); return featureArray; } public createFeatureHashingOneHotEncoderNumberArray(input: string): number[] { const featureArray: number[] = new Array(this.numberHashingFeaturesSetting).fill(0); const features: string[] = this.featurize(input); features.forEach(function(this: NgramSubwordFeaturizer, feature: string, index: number, array: string[]) { if (!feature) { Utility.debuggingThrow("feature==null"); } const featureId: number = this.getHashingFeatureIndex(feature); if (featureId >= 0) { featureArray[featureId] = 1; } }, this); return featureArray; } public createFeatureHashingOneHotEncoderBooleanArrays(inputs: string[]): boolean[][] { const inputArrays: boolean[][] = inputs.map((input) => this.createFeatureHashingOneHotEncoderBooleanArray(input), this); return inputArrays; } public createFeatureHashingOneHotEncoderNumberArrays(inputs: string[]): number[][] { const inputArrays: number[][] = inputs.map((input) => this.createFeatureHashingOneHotEncoderNumberArray(input), this); return inputArrays; } public createIntentUtteranceHashingOneHotEncoderBooleanArrays( intentsUtterancesWeights: { "intents": string[], "utterances": string[], "weights": number[] }): { "intentLabelIndexArrays": boolean[][], "utteranceFeatureIndexArrays": boolean[][] } { const intents: string[] = intentsUtterancesWeights.intents; const utterances: string[] = intentsUtterancesWeights.utterances; const weights: number[] = intentsUtterancesWeights.weights; const intentLabelIndexArrays: boolean[][] = intents.map((intent) => this.createLabelOneHotEncoderBooleanArray(intent), this); const utteranceFeatureIndexArrays: boolean[][] = utterances.map((utterance) => this.createFeatureHashingOneHotEncoderBooleanArray(utterance), this); return { intentLabelIndexArrays, utteranceFeatureIndexArrays }; } public createIntentUtteranceHashingOneHotEncoderNumberArrays( intentsUtterancesWeights: { "intents": string[], "utterances": string[], "weights": number[] }): { "intentLabelIndexArrays": number[][], "utteranceFeatureIndexArrays": number[][] } { const intents: string[] = intentsUtterancesWeights.intents; const utterances: string[] = intentsUtterancesWeights.utterances; const weights: number[] = intentsUtterancesWeights.weights; const intentLabelIndexArrays: number[][] = intents.map((intent) => this.createLabelOneHotEncoderNumberArray(intent), this); const utteranceFeatureIndexArrays: number[][] = utterances.map((utterance) => this.createFeatureHashingOneHotEncoderNumberArray(utterance), this); return { intentLabelIndexArrays, utteranceFeatureIndexArrays }; } public featurize(input: string): string[] { if (this.toLowercase) { input = input.toLowerCase(); } let result: string[] = this.split(input); if (this.toRemovePunctuations) { result = result.filter((element: string) => { return (!Utility.LanguageTokenPunctuationDelimitersSet.has(element)); }); } const subwordFeatures: string[] = this.generateSubwords(result.join(this.splitDelimiter)); return result.concat(subwordFeatures); } public split(input: string): string[] { return this.splitRaw( input).map((x: string) => x.trim()); } public splitRaw(input: string): string[] { return Utility.splitByPunctuation( input, this.splitDelimiter, this.toRemoveEmptyElements); } public generateSubwords(input: string): string[] { const result: string[] = []; if ((this.subwordNgramBegin > 0) && (this.subwordNgramEnd >= this.subwordNgramBegin)) { const length = input.length; for (let ngram = this.subwordNgramBegin; ngram <= this.subwordNgramEnd; ngram++) { for (let i = 0; i < length - ngram; i++) { result.push(input.substr(i, ngram)); } } } return result; } public resetLabelFeatureMaps( intentsUtterancesWeights: { "intents": string[], "utterances": string[], "weights": number[] }): void { // ------------------------------------------------------------------- this.intentsUtterancesWeights = intentsUtterancesWeights; // ------------------------------------------------------------------- const intents: string[] = intentsUtterancesWeights.intents; const intentLabels: { "stringArray": string[], "stringMap": Map<string, number> } = DictionaryMapUtility.buildStringKeyNumberValueMapFromStringArray(intents); this.labels = intentLabels.stringArray; this.labelMap = intentLabels.stringMap; // ------------------------------------------------------------------- const utterances: string[] = intentsUtterancesWeights.utterances; const featureArray: string[][] = utterances.map((text) => this.featurize(text)); // ---- NOTE-FOR-REFERENCE ---- let featureArrayFlattened: string[] = // ---- NOTE-FOR-REFERENCE ---- []; // ---- NOTE-FOR-REFERENCE ---- for (let i: number = 0; i < featureArray.length; i++) { // ---- NOTE-FOR-REFERENCE ---- featureArrayFlattened = featureArrayFlattened.concat(featureArray[i]); // ---- NOTE-FOR-REFERENCE ---- } // ---- NOTE-FOR-REFERENCE ---- NOTE ---- for a large file, the loop above can take a long time! // ---- NOTE-FOR-REFERENCE ---- const featureArrayFlattened: string[] = // ---- NOTE-FOR-REFERENCE ---- ([] as string[]).concat(...featureArray); // ---- NOTE-FOR-REFERENCE ---- NOTE ---- for a large file, the above "Spread Operator" can lead to // ---- NOTE-FOR-REFERENCE ---- NOTE ---- RangeError: Maximum call stack size exceeded! // ---- NOTE-FOR-REFERENCE ---- const utteranceTexts: { // ---- NOTE-FOR-REFERENCE ---- "stringArray": string[], // ---- NOTE-FOR-REFERENCE ---- "stringMap": Map<string, number> } = // tslint:disable-next-line: max-line-length // ---- NOTE-FOR-REFERENCE ---- DictionaryMapUtility.buildStringIdNumberValueDictionaryFromStringArray(featureArrayFlattened); const utteranceTexts: { "stringArray": string[], "stringMap": Map<string, number> } = DictionaryMapUtility.buildStringKeyNumberValueMapFromStringArrays(featureArray); this.features = utteranceTexts.stringArray; this.featureMap = utteranceTexts.stringMap; // ------------------------------------------------------------------- if (this.numberHashingFeaturesSetting > 0) { this.hashingFeatureArrays = new Array<Set<string>>(this.numberHashingFeaturesSetting); for (let i: number = 0; i < this.numberHashingFeaturesSetting; i++) { this.hashingFeatureArrays[i] = new Set<string>(); } for (const feature of this.features) { const featureHashingIndex: number = this.getHashingFeatureIndex(feature); this.hashingFeatureArrays[featureHashingIndex].add(feature); } } // ------------------------------------------------------------------- // return { // "labels": this.labels, // "labelMap": this.labelMap, // "features": this.features, // "featureMap": this.featureMap // }; // ------------------------------------------------------------------- } public serializeToJsonString( replacer?: (this: any, key: string, value: any) => any, space?: string | number): string { return JSON.stringify(this, replacer, space); } public deserializeFromJsonString(jsonString: string): void { const deserialized: NgramSubwordFeaturizer = JSON.parse(jsonString); this.numberHashingFeaturesSetting = deserialized.numberHashingFeaturesSetting; this.subwordNgramBegin = deserialized.subwordNgramBegin; this.subwordNgramEnd = deserialized.subwordNgramEnd; this.toLowercase = deserialized.toLowercase; this.toRemovePunctuations = deserialized.toRemovePunctuations; this.toRemoveEmptyElements = deserialized.toRemoveEmptyElements; this.splitDelimiter = deserialized.splitDelimiter; this.intentsUtterancesWeights = deserialized.intentsUtterancesWeights; this.labels = deserialized.labels; this.labelMap = deserialized.labelMap; this.features = deserialized.features; this.featureMap = deserialized.featureMap; this.hashingFeatureArrays = deserialized.hashingFeatureArrays; } }
the_stack
import { Components, registerComponent, getCollection } from '../../lib/vulcan-lib'; import { withMulti } from '../../lib/crud/withMulti'; import withUser from '../common/withUser'; import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { getSchema } from '../../lib/utils/getSchema'; import { intlShape } from '../../lib/vulcan-i18n'; import { getFieldValue } from './Card'; import _sortBy from 'lodash/sortBy'; /* Datatable Component */ // see: http://stackoverflow.com/questions/1909441/jquery-keyup-delay const delay = (function(){ var timer: any = 0; return function(callback, ms){ clearTimeout (timer); timer = setTimeout(callback, ms); }; })(); const getColumnName = column => ( typeof column === 'string' ? column : column.label || column.name ); class Datatable extends PureComponent<any,any> { constructor(props) { super(props); this.updateQuery = this.updateQuery.bind(this); this.state = { value: '', query: '', currentSort: {} }; } toggleSort = column => { let currentSort; if (!this.state.currentSort[column]) { currentSort = { [column] : 1 }; } else if (this.state.currentSort[column] === 1) { currentSort = { [column] : -1 }; } else { currentSort = {}; } this.setState({ currentSort }); } updateQuery(e) { e.persist(); e.preventDefault(); this.setState({ value: e.target.value }); delay(() => { this.setState({ query: e.target.value }); }, 700 ); } render() { if (this.props.data) { // static JSON datatable return <Components.DatatableContents columns={Object.keys(this.props.data[0])} {...this.props} results={this.props.data} />; } else { // dynamic datatable with data loading const collection = this.props.collection || getCollection(this.props.collectionName); const options = { collection, ...this.props.options }; const DatatableWithMulti: any = withMulti(options)(Components.DatatableContents); // add _id to orderBy when we want to sort a column, to avoid breaking the graphql() hoc; // see https://github.com/VulcanJS/Vulcan/issues/2090#issuecomment-433860782 // this.state.currentSort !== {} is always false, even when console.log(this.state.currentSort) displays {}. So we test on the length of keys for this object. const orderBy = Object.keys(this.state.currentSort).length == 0 ? {} : { ...this.state.currentSort, _id: -1 }; return ( <Components.DatatableLayout collectionName={collection.options.collectionName}> <DatatableWithMulti {...this.props} collection={collection} terms={{ query: this.state.query, orderBy: orderBy }} currentUser={this.props.currentUser} toggleSort={this.toggleSort} currentSort={this.state.currentSort}/> </Components.DatatableLayout> ); } } } (Datatable as any).propTypes = { title: PropTypes.string, collection: PropTypes.object, columns: PropTypes.array, data: PropTypes.array, options: PropTypes.object, emptyState: PropTypes.object, }; const DatatableComponent = registerComponent('Datatable', Datatable, { hocs: [withUser] }); export default Datatable; const DatatableLayout = ({ collectionName, children }) => ( <div className={`datatable datatable-${collectionName}`}> {children} </div> ); const DatatableLayoutComponent = registerComponent('DatatableLayout', DatatableLayout); /* DatatableHeader Component */ const DatatableHeader = ({ collection, column, toggleSort, currentSort }, { intl }) => { const columnName = getColumnName(column); if (collection) { const schema = getSchema(collection); /* use either: 1. the column name translation : collectionName.columnName, global.columnName, columnName 2. the column name label in the schema (if the column name matches a schema field) 3. the raw column name. */ const formattedLabel = intl.formatLabel({fieldName: columnName, collectionName: collection.collectionName, schema: schema}); // if sortable is a string, use it as the name of the property to sort by. If it's just `true`, use column.name const sortPropertyName = typeof column.sortable === 'string' ? column.sortable : column.name; return column.sortable ? <Components.DatatableSorter name={sortPropertyName} label={formattedLabel} toggleSort={toggleSort} currentSort={currentSort} /> : <Components.DatatableHeaderCellLayout>{formattedLabel}</Components.DatatableHeaderCellLayout>; } else { const formattedLabel = intl.formatMessage({ id: columnName, defaultMessage: columnName }); return ( <Components.DatatableHeaderCellLayout className={`datatable-th-${columnName.toLowerCase().replace(/\s/g, '-')}`} > {formattedLabel} </Components.DatatableHeaderCellLayout> ); } }; DatatableHeader.contextTypes = { intl: intlShape }; DatatableHeader.propTypes = { }; const DatatableHeaderComponent = registerComponent('DatatableHeader', DatatableHeader); const DatatableHeaderCellLayout = ({ children, ...otherProps }) => ( <th {...otherProps}>{children}</th> ); const DatatableHeaderCellLayoutComponent = registerComponent('DatatableHeaderCellLayout', DatatableHeaderCellLayout); const SortNone = () => <svg width='16' height='16' viewBox='0 0 438 438' fill='none' xmlns='http://www.w3.org/2000/svg'> <path d='M25.7368 247.243H280.263C303.149 247.243 314.592 274.958 298.444 291.116L171.18 418.456C161.128 428.515 144.872 428.515 134.926 418.456L7.55631 291.116C-8.59221 274.958 2.85078 247.243 25.7368 247.243ZM298.444 134.884L171.18 7.54408C161.128 -2.51469 144.872 -2.51469 134.926 7.54408L7.55631 134.884C-8.59221 151.042 2.85078 178.757 25.7368 178.757H280.263C303.149 178.757 314.592 151.042 298.444 134.884Z' transform='translate(66 6)' fill='currentColor' fillOpacity='0.2' /> </svg>; const SortDesc = () => <svg width="16" height="16" viewBox="0 0 438 438" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M25.7368 0H280.263C303.149 0 314.592 27.7151 298.444 43.8734L171.18 171.213C161.128 181.272 144.872 181.272 134.926 171.213L7.55631 43.8734C-8.59221 27.7151 2.85078 0 25.7368 0Z" transform="translate(66 253.243)" fill="currentColor" fillOpacity="0.7"/> <path d="M171.18 7.54408L298.444 134.884C314.592 151.042 303.149 178.757 280.263 178.757H25.7368C2.85078 178.757 -8.59221 151.042 7.55631 134.884L134.926 7.54408C144.872 -2.51469 161.128 -2.51469 171.18 7.54408Z" transform="translate(66 6)" fill="currentColor" fillOpacity="0.2"/> </svg>; const SortAsc = () => <svg width="16" height="16" viewBox="0 0 438 438" fill="none" xmlns="http://www.w3.org/2000/svg"> <path d="M298.444 134.884L171.18 7.54408C161.128 -2.51469 144.872 -2.51469 134.926 7.54408L7.55631 134.884C-8.59221 151.042 2.85078 178.757 25.7368 178.757H280.263C303.149 178.757 314.592 151.042 298.444 134.884Z" transform="translate(66 6)" fill="currentColor" fillOpacity="0.7"/> <path d="M280.263 0H25.7368C2.85078 0 -8.59221 27.7151 7.55631 43.8734L134.926 171.213C144.872 181.272 161.128 181.272 171.18 171.213L298.444 43.8734C314.592 27.7151 303.149 0 280.263 0Z" transform="translate(66 253.243)" fill="currentColor" fillOpacity="0.2"/> </svg>; const DatatableSorter = ({ name, label, toggleSort, currentSort }) => <th> <div className="datatable-sorter" onClick={() => {toggleSort(name);}}> <span className="datatable-sorter-label">{label}</span> <span className="sort-icon"> {!currentSort[name] ? ( <SortNone/> ) : currentSort[name] === 1 ? ( <SortAsc/> ) : ( <SortDesc/> ) } </span> </div> </th>; const DatatableSorterComponent = registerComponent('DatatableSorter', DatatableSorter); /* DatatableContents Component */ const DatatableContents = (props) => { // if no columns are provided, default to using keys of first array item const { title, collection, results, columns, loading, loadMore, count, totalCount, networkStatus, currentUser, emptyState, toggleSort, currentSort } = props; if (loading) { return <div className="datatable-list datatable-list-loading"><Components.Loading /></div>; } else if (!results || !results.length) { return emptyState || null; } const isLoadingMore = networkStatus === 2; const hasMore = totalCount > results.length; const sortedColumns = _sortBy(columns, column => column.order); return ( <Components.DatatableContentsLayout> {title && <Components.DatatableTitle title={title}/>} <Components.DatatableContentsInnerLayout> <Components.DatatableContentsHeadLayout> { sortedColumns .map((column, index) => ( <Components.DatatableHeader key={index} collection={collection} column={column} toggleSort={toggleSort} currentSort={currentSort} />) ) } </Components.DatatableContentsHeadLayout> <Components.DatatableContentsBodyLayout> {results.map((document, index) => <Components.DatatableRow {...props} collection={collection} columns={columns} document={document} key={index} currentUser={currentUser} />)} </Components.DatatableContentsBodyLayout> </Components.DatatableContentsInnerLayout> {hasMore && <Components.DatatableContentsMoreLayout> {isLoadingMore ? <Components.Loading /> : ( <Components.DatatableLoadMoreButton onClick={e => { e.preventDefault(); loadMore(); }}> Load More ({count}/{totalCount}) </Components.DatatableLoadMoreButton> ) } </Components.DatatableContentsMoreLayout> } </Components.DatatableContentsLayout> ); }; DatatableContents.propTypes = { }; const DatatableContentsComponent = registerComponent('DatatableContents', DatatableContents); const DatatableContentsLayout = ({ children }) => ( <div className="datatable-list"> {children} </div> ); const DatatableContentsLayoutComponent = registerComponent('DatatableContentsLayout', DatatableContentsLayout); const DatatableContentsInnerLayout = ({ children }) => ( <table className="table"> {children} </table> ); const DatatableContentsInnerLayoutComponent = registerComponent('DatatableContentsInnerLayout', DatatableContentsInnerLayout); const DatatableContentsHeadLayout = ({ children }) => ( <thead> <tr> {children} </tr> </thead> ); const DatatableContentsHeadLayoutComponent = registerComponent('DatatableContentsHeadLayout', DatatableContentsHeadLayout); const DatatableContentsBodyLayout = ({ children }) => ( <tbody>{children}</tbody> ); const DatatableContentsBodyLayoutComponent = registerComponent('DatatableContentsBodyLayout', DatatableContentsBodyLayout); const DatatableContentsMoreLayout = ({ children }) => ( <div className="datatable-list-load-more"> {children} </div> ); const DatatableContentsMoreLayoutComponent = registerComponent('DatatableContentsMoreLayout', DatatableContentsMoreLayout); const DatatableLoadMoreButton = ({ count, totalCount, children, ...otherProps }) => ( <Components.Button variant="primary" {...otherProps}>{children}</Components.Button> ); const DatatableLoadMoreButtonComponent = registerComponent('DatatableLoadMoreButton', DatatableLoadMoreButton); /* DatatableTitle Component */ const DatatableTitle = ({ title }) => <div className="datatable-title">{title}</div>; const DatatableTitleComponent = registerComponent('DatatableTitle', DatatableTitle); /* DatatableRow Component */ const DatatableRow = (props) => { const { columns, document, currentUser, rowClass } = props; const row = typeof rowClass === 'function' ? rowClass(document) : rowClass || ''; const sortedColumns = _sortBy(columns, column => column.order); return ( <Components.DatatableRowLayout className={`datatable-item ${row}`}> { sortedColumns .map((column, index) => ( <Components.DatatableCell key={index} column={column} document={document} currentUser={currentUser} /> ))} </Components.DatatableRowLayout> ); }; DatatableRow.propTypes = { }; const DatatableRowComponent = registerComponent('DatatableRow', DatatableRow); const DatatableRowLayout = ({ children, ...otherProps }) => ( <tr {...otherProps}> {children} </tr> ); const DatatableRowLayoutComponent = registerComponent('DatatableRowLayout', DatatableRowLayout); /* DatatableCell Component */ const DatatableCell = ({ column, document, currentUser }) => { const Component = column.component || (column.componentName && Components[column.componentName]) || Components.DatatableDefaultCell; const columnName = getColumnName(column); return ( <Components.DatatableCellLayout className={`datatable-item-${columnName.toLowerCase().replace(/\s/g, '-')}`}> <Component column={column} document={document} currentUser={currentUser} /> </Components.DatatableCellLayout> ); }; DatatableCell.propTypes = { }; const DatatableCellComponent = registerComponent('DatatableCell', DatatableCell); const DatatableCellLayout = ({ children, ...otherProps }) => ( <td {...otherProps}>{children}</td> ); const DatatableCellLayoutComponent = registerComponent('DatatableCellLayout', DatatableCellLayout); /* DatatableDefaultCell Component */ const DatatableDefaultCell = ({ column, document }) => <div>{typeof column === 'string' ? getFieldValue(document[column]) : getFieldValue(document[column.name])}</div>; const DatatableDefaultCellComponent = registerComponent('DatatableDefaultCell', DatatableDefaultCell); declare global { interface ComponentTypes { Datatable: typeof DatatableComponent, DatatableLayout: typeof DatatableLayoutComponent, DatatableHeader: typeof DatatableHeaderComponent, DatatableHeaderCellLayout: typeof DatatableHeaderCellLayoutComponent, DatatableSorter: typeof DatatableSorterComponent, DatatableContents: typeof DatatableContentsComponent, DatatableContentsLayout: typeof DatatableContentsLayoutComponent, DatatableContentsInnerLayout: typeof DatatableContentsInnerLayoutComponent, DatatableContentsHeadLayout: typeof DatatableContentsHeadLayoutComponent, DatatableContentsBodyLayout: typeof DatatableContentsBodyLayoutComponent, DatatableContentsMoreLayout: typeof DatatableContentsMoreLayoutComponent, DatatableLoadMoreButton: typeof DatatableLoadMoreButtonComponent, DatatableTitle: typeof DatatableTitleComponent, DatatableRow: typeof DatatableRowComponent, DatatableRowLayout: typeof DatatableRowLayoutComponent, DatatableCell: typeof DatatableCellComponent, DatatableCellLayout: typeof DatatableCellLayoutComponent, DatatableDefaultCell: typeof DatatableDefaultCellComponent, } }
the_stack
import Log from '@secret-agent/commons/Logger'; import { IBlockedResourceType } from '@secret-agent/interfaces/ITabOptions'; import * as Url from 'url'; import IWaitForResourceOptions from '@secret-agent/interfaces/IWaitForResourceOptions'; import Timer from '@secret-agent/commons/Timer'; import IResourceMeta from '@secret-agent/interfaces/IResourceMeta'; import { createPromise } from '@secret-agent/commons/utils'; import TimeoutError from '@secret-agent/commons/interfaces/TimeoutError'; import { IPuppetPage, IPuppetPageEvents } from '@secret-agent/interfaces/IPuppetPage'; import { CanceledPromiseError } from '@secret-agent/commons/interfaces/IPendingWaitEvent'; import { TypedEventEmitter } from '@secret-agent/commons/eventUtils'; import { IBoundLog } from '@secret-agent/interfaces/ILog'; import IWebsocketResourceMessage from '@secret-agent/interfaces/IWebsocketResourceMessage'; import IWaitForOptions from '@secret-agent/interfaces/IWaitForOptions'; import IScreenshotOptions from '@secret-agent/interfaces/IScreenshotOptions'; import MitmRequestContext from '@secret-agent/mitm/lib/MitmRequestContext'; import { IJsPath } from 'awaited-dom/base/AwaitedPath'; import { IInteractionGroups, InteractionCommand } from '@secret-agent/interfaces/IInteractions'; import IExecJsPathResult from '@secret-agent/interfaces/IExecJsPathResult'; import IWaitForElementOptions from '@secret-agent/interfaces/IWaitForElementOptions'; import { ILocationTrigger, IPipelineStatus } from '@secret-agent/interfaces/Location'; import IFrameMeta from '@secret-agent/interfaces/IFrameMeta'; import { LoadStatus } from '@secret-agent/interfaces/INavigation'; import IPuppetDialog from '@secret-agent/interfaces/IPuppetDialog'; import IFileChooserPrompt from '@secret-agent/interfaces/IFileChooserPrompt'; import FrameNavigations from './FrameNavigations'; import CommandRecorder from './CommandRecorder'; import FrameEnvironment from './FrameEnvironment'; import IResourceFilterProperties from '../interfaces/IResourceFilterProperties'; import InjectedScripts from './InjectedScripts'; import Session from './Session'; import SessionState from './SessionState'; import FrameNavigationsObserver from './FrameNavigationsObserver'; import DomChangesTable, { IDomChangeRecord, IFrontendDomChangeEvent, } from '../models/DomChangesTable'; import DetachedTabState from './DetachedTabState'; const { log } = Log(module); export default class Tab extends TypedEventEmitter<ITabEventParams> { public readonly id: number; public readonly parentTabId?: number; public readonly session: Session; public readonly frameEnvironmentsById = new Map<number, FrameEnvironment>(); public readonly frameEnvironmentsByPuppetId = new Map<string, FrameEnvironment>(); public puppetPage: IPuppetPage; public isClosing = false; public isReady: Promise<void>; public isDetached = false; protected readonly logger: IBoundLog; private readonly commandRecorder: CommandRecorder; private readonly createdAtCommandId: number; private waitTimeouts: { timeout: NodeJS.Timeout; reject: (reason?: any) => void }[] = []; private lastFileChooserEvent: { event: IPuppetPageEvents['filechooser']; atCommandId: number; }; private onFrameCreatedResourceEventsByFrameId: { [frameId: string]: { type: keyof IPuppetPageEvents; event: IPuppetPageEvents[keyof IPuppetPageEvents]; }[]; } = {}; public get navigations(): FrameNavigations { return this.mainFrameEnvironment.navigations; } public get navigationsObserver(): FrameNavigationsObserver { return this.mainFrameEnvironment.navigationsObserver; } public get url(): string { return this.navigations.currentUrl; } public get sessionState(): SessionState { return this.session.sessionState; } public get lastCommandId(): number | undefined { return this.sessionState.lastCommand?.id; } public get sessionId(): string { return this.session.id; } public get mainFrameId(): number { return this.mainFrameEnvironment.id; } public get mainFrameEnvironment(): FrameEnvironment { return this.frameEnvironmentsByPuppetId.get(this.puppetPage.mainFrame.id); } // eslint-disable-next-line @typescript-eslint/member-ordering private constructor( session: Session, puppetPage: IPuppetPage, isDetached: boolean, parentTabId?: number, windowOpenParams?: { url: string; windowName: string; loaderId: string }, ) { super(); this.setEventsToLog(['child-tab-created', 'close']); this.id = session.nextTabId(); this.logger = log.createChild(module, { tabId: this.id, sessionId: session.id, }); this.session = session; this.parentTabId = parentTabId; this.createdAtCommandId = session.sessionState.lastCommand?.id; this.puppetPage = puppetPage; this.isDetached = isDetached; for (const puppetFrame of puppetPage.frames) { const frame = new FrameEnvironment(this, puppetFrame); this.frameEnvironmentsByPuppetId.set(frame.devtoolsFrameId, frame); this.frameEnvironmentsById.set(frame.id, frame); } if (windowOpenParams) { this.navigations.onNavigationRequested( 'newFrame', windowOpenParams.url, this.lastCommandId, windowOpenParams.loaderId, ); } this.listen(); this.isReady = this.waitForReady(); this.commandRecorder = new CommandRecorder(this, this.session, this.id, this.mainFrameId, [ this.focus, this.dismissDialog, this.getFrameEnvironments, this.goto, this.goBack, this.goForward, this.reload, this.takeScreenshot, this.waitForFileChooser, this.waitForMillis, this.waitForNewTab, this.waitForResource, this.runPluginCommand, // DO NOT ADD waitForReady ]); } public isAllowedCommand(method: string): boolean { return ( this.commandRecorder.fnNames.has(method) || method === 'close' || method === 'getResourceProperty' ); } public checkForResolvedNavigation( browserRequestId: string, resource: IResourceMeta, error?: Error, ): boolean { if (resource.type !== 'Document') return; const frame = this.findFrameWithUnresolvedNavigation( browserRequestId, resource.request?.method, resource.request?.url, resource.response?.url, ); if (frame && !resource.isRedirect) { frame.navigations.onResourceLoaded(resource.id, resource.response?.statusCode, error); return true; } return false; } public findFrameWithUnresolvedNavigation( browserRequestId: string, method: string, requestedUrl: string, finalUrl: string, ): FrameEnvironment { for (const frame of this.frameEnvironmentsById.values()) { const top = frame.navigations.top; if (!top || top.resourceId.isResolved) continue; if ( (top.finalUrl && finalUrl === top.finalUrl) || requestedUrl === top.requestedUrl || browserRequestId === top.browserRequestId ) { return frame; } } } public async setBlockedResourceTypes( blockedResourceTypes: IBlockedResourceType[], ): Promise<void> { const mitmSession = this.session.mitmRequestSession; const blockedResources = mitmSession.blockedResources.types; let enableJs = true; if (blockedResourceTypes.includes('None')) { blockedResources.length = 0; } else if (blockedResourceTypes.includes('All')) { blockedResources.push('Image', 'Stylesheet', 'Script', 'Font', 'Ico', 'Media'); enableJs = false; } else if (blockedResourceTypes.includes('BlockAssets')) { blockedResources.push('Image', 'Stylesheet', 'Script'); } else { if (blockedResourceTypes.includes('BlockImages')) { blockedResources.push('Image'); } if (blockedResourceTypes.includes('BlockCssResources')) { blockedResources.push('Stylesheet'); } if (blockedResourceTypes.includes('BlockJsResources')) { blockedResources.push('Script'); } if (blockedResourceTypes.includes('JsRuntime')) { enableJs = false; } } await this.puppetPage.setJavaScriptEnabled(enableJs); mitmSession.blockedResources.urls = []; } public async close(): Promise<void> { if (this.isClosing) return; this.isClosing = true; const parentLogId = this.logger.stats('Tab.Closing'); const errors: Error[] = []; try { const cancelMessage = 'Terminated command because session closing'; Timer.expireAll(this.waitTimeouts, new CanceledPromiseError(cancelMessage)); for (const frame of this.frameEnvironmentsById.values()) { frame.close(); } this.cancelPendingEvents(cancelMessage); } catch (error) { if (!error.message.includes('Target closed') && !(error instanceof CanceledPromiseError)) { errors.push(error); } } try { this.puppetPage.off('close', this.close); // run this one individually await this.puppetPage.close(); } catch (error) { if (!error.message.includes('Target closed') && !(error instanceof CanceledPromiseError)) { errors.push(error); } } this.emit('close'); this.logger.stats('Tab.Closed', { parentLogId, errors }); } public async setOrigin(origin: string): Promise<void> { const mitmSession = this.session.mitmRequestSession; const originalBlocker = mitmSession.blockedResources; mitmSession.blockedResources = { types: [], urls: [origin], handlerFn(request, response) { response.end(`<html lang="en"><body>Empty</body></html>`); return true; }, }; try { await this.puppetPage.navigate(origin); } finally { // restore originals mitmSession.blockedResources = originalBlocker; } } public async getResourceProperty<T = string | number | Buffer>( resourceId: number, propertyPath: string, ): Promise<T> { let finalResourceId = resourceId; // if no resource id, this is a request for the default resource (page) if (!resourceId) { finalResourceId = await this.navigationsObserver.waitForNavigationResourceId(); } if (propertyPath === 'data' || propertyPath === 'response.data') { return (await this.sessionState.getResourceData(finalResourceId, true)) as any; } const resource = this.sessionState.getResourceMeta(finalResourceId); const pathParts = propertyPath.split('.'); let propertyParent: any = resource; if (pathParts.length > 1) { const parentProp = pathParts.shift(); if (parentProp === 'request' || parentProp === 'response') { propertyParent = propertyParent[parentProp]; } } const property = pathParts.shift(); return propertyParent[property]; } /////// DELEGATED FNS //////////////////////////////////////////////////////////////////////////////////////////////// public interact(...interactionGroups: IInteractionGroups): Promise<void> { return this.mainFrameEnvironment.interact(...interactionGroups); } public getJsValue<T>(path: string): Promise<{ value: T; type: string }> { return this.mainFrameEnvironment.getJsValue(path); } public execJsPath<T>(jsPath: IJsPath): Promise<IExecJsPathResult<T>> { return this.mainFrameEnvironment.execJsPath<T>(jsPath); } public getLocationHref(): Promise<string> { return this.mainFrameEnvironment.getLocationHref(); } public waitForElement(jsPath: IJsPath, options?: IWaitForElementOptions): Promise<boolean> { return this.mainFrameEnvironment.waitForElement(jsPath, options); } public waitForLoad(status: IPipelineStatus, options?: IWaitForOptions): Promise<void> { return this.mainFrameEnvironment.waitForLoad(status, options); } public waitForLocation( trigger: ILocationTrigger, options?: IWaitForOptions, ): Promise<IResourceMeta> { return this.mainFrameEnvironment.waitForLocation(trigger, options); } /////// COMMANDS ///////////////////////////////////////////////////////////////////////////////////////////////////// public getFrameEnvironments(): Promise<IFrameMeta[]> { return Promise.resolve( [...this.frameEnvironmentsById.values()].filter(x => x.isAttached).map(x => x.toJSON()), ); } public async goto(url: string, timeoutMs = 30e3): Promise<IResourceMeta> { const formattedUrl = Url.format(url); const navigation = this.navigations.onNavigationRequested( 'goto', formattedUrl, this.lastCommandId, null, ); const timeoutMessage = `Timeout waiting for "tab.goto(${url})"`; const timer = new Timer(timeoutMs, this.waitTimeouts); const loader = await timer.waitForPromise( this.puppetPage.navigate(formattedUrl), timeoutMessage, ); this.navigations.assignLoaderId(navigation, loader.loaderId); const resource = await timer.waitForPromise( this.navigationsObserver.waitForNavigationResourceId(), timeoutMessage, ); return this.sessionState.getResourceMeta(resource); } public async goBack(timeoutMs?: number): Promise<string> { const navigation = this.navigations.onNavigationRequested( 'goBack', null, this.lastCommandId, null, ); const backUrl = await this.puppetPage.goBack(); this.navigations.assignLoaderId( navigation, this.puppetPage.mainFrame.activeLoader?.id, backUrl, ); await this.navigationsObserver.waitForLoad('PaintingStable', { timeoutMs }); return this.url; } public async goForward(timeoutMs?: number): Promise<string> { const navigation = this.navigations.onNavigationRequested( 'goForward', null, this.lastCommandId, null, ); const url = await this.puppetPage.goForward(); this.navigations.assignLoaderId(navigation, this.puppetPage.mainFrame.activeLoader?.id, url); await this.navigationsObserver.waitForLoad('PaintingStable', { timeoutMs }); return this.url; } public async reload(timeoutMs?: number): Promise<IResourceMeta> { const navigation = this.navigations.onNavigationRequested( 'reload', this.url, this.lastCommandId, null, ); const timer = new Timer(timeoutMs, this.waitTimeouts); const timeoutMessage = `Timeout waiting for "tab.reload()"`; let loaderId = this.puppetPage.mainFrame.activeLoader.id; await timer.waitForPromise(this.puppetPage.reload(), timeoutMessage); if (this.puppetPage.mainFrame.activeLoader.id === loaderId) { const frameNavigated = await timer.waitForPromise( this.puppetPage.mainFrame.waitOn('frame-navigated', null, timeoutMs), timeoutMessage, ); loaderId = frameNavigated.loaderId; } this.navigations.assignLoaderId( navigation, loaderId ?? this.puppetPage.mainFrame.activeLoader?.id, ); const resource = await timer.waitForPromise( this.navigationsObserver.waitForNavigationResourceId(), timeoutMessage, ); return this.sessionState.getResourceMeta(resource); } public async focus(): Promise<void> { await this.puppetPage.bringToFront(); } public takeScreenshot(options: IScreenshotOptions = {}): Promise<Buffer> { if (options.rectangle) options.rectangle.scale ??= 1; return this.puppetPage.screenshot(options.format, options.rectangle, options.jpegQuality); } public async dismissDialog(accept: boolean, promptText?: string): Promise<void> { const resolvable = createPromise(); this.mainFrameEnvironment.interactor.play( [[{ command: InteractionCommand.willDismissDialog }]], resolvable, ); await resolvable.promise; return this.puppetPage.dismissDialog(accept, promptText); } public async waitForNewTab(options: IWaitForOptions = {}): Promise<Tab> { // last command is the one running right now const startCommandId = Number.isInteger(options.sinceCommandId) ? options.sinceCommandId : this.lastCommandId - 1; let newTab: Tab; const startTime = new Date(); if (startCommandId >= 0) { for (const tab of this.session.tabsById.values()) { if (tab.parentTabId === this.id && tab.createdAtCommandId >= startCommandId) { newTab = tab; break; } } } if (!newTab) newTab = await this.waitOn('child-tab-created', undefined, options?.timeoutMs); // wait for a real url to be requested if (newTab.url === 'about:blank' || !newTab.url) { let timeoutMs = options?.timeoutMs ?? 10e3; const millis = Date.now() - startTime.getTime(); timeoutMs -= millis; await newTab.navigations.waitOn('navigation-requested', null, timeoutMs).catch(() => null); } await newTab.navigationsObserver.waitForNavigationResourceId(); return newTab; } public async waitForResource( filter: IResourceFilterProperties, opts?: IWaitForResourceOptions, ): Promise<IResourceMeta[]> { const timer = new Timer(opts?.timeoutMs ?? 60e3, this.waitTimeouts); const resourceMetas: IResourceMeta[] = []; const promise = createPromise(); const onResource = (resourceMeta: IResourceMeta) => { if (resourceMeta.tabId !== this.id) return; if (resourceMeta.seenAtCommandId === undefined) { resourceMeta.seenAtCommandId = this.lastCommandId; // need to set directly since passed in object is a copy this.sessionState.getResourceMeta(resourceMeta.id).seenAtCommandId = this.lastCommandId; } if (resourceMeta.seenAtCommandId <= opts?.sinceCommandId ?? -1) return; if (filter.type && resourceMeta.type !== filter.type) return; if (filter.url) { if (typeof filter.url === 'string') { // don't let query string url if (filter.url.match(/[\w.:/_\-@;$]\?[-+;%@.\w_]+=.+/) && !filter.url.includes('\\?')) { filter.url = filter.url.replace('?', '\\?'); } } if (!resourceMeta.url.match(filter.url)) return; } // if already included, skip if (resourceMetas.some(x => x.id === resourceMeta.id)) return; resourceMetas.push(resourceMeta); // resolve if any match promise.resolve(); }; try { this.on('resource', onResource); for (const resource of this.sessionState.getResources(this.id)) { onResource(resource); } await timer.waitForPromise(promise.promise, 'Timeout waiting for DomContentLoaded'); } catch (err) { const isTimeout = err instanceof TimeoutError; if (isTimeout && opts?.throwIfTimeout === false) { return resourceMetas; } throw err; } finally { this.off('resource', onResource); timer.clear(); } return resourceMetas; } public async waitForFileChooser(options?: IWaitForOptions): Promise<IFileChooserPrompt> { let startCommandId = options?.sinceCommandId && Number.isInteger(options.sinceCommandId) ? options.sinceCommandId : null; if (!startCommandId && this.sessionState.commands.length >= 2) { startCommandId = this.sessionState.commands[this.sessionState.commands.length - 2]?.id; } let event: IPuppetPageEvents['filechooser']; if (this.lastFileChooserEvent) { const { atCommandId } = this.lastFileChooserEvent; if (atCommandId >= startCommandId) { event = this.lastFileChooserEvent.event; } } if (!event) { event = await this.puppetPage.waitOn('filechooser', null, options?.timeoutMs ?? 30e3); } const frameEnvironment = this.frameEnvironmentsByPuppetId.get(event.frameId); const nodeId = await frameEnvironment.getDomNodeId(event.objectId); return { jsPath: [nodeId], frameId: frameEnvironment.id, selectMultiple: event.selectMultiple, }; } public waitForMillis(millis: number): Promise<void> { return new Timer(millis, this.waitTimeouts).waitForTimeout(); } public async runPluginCommand(toPluginId, args: any[]): Promise<any> { const commandMeta = { puppetPage: this.puppetPage, puppetFrame: this.mainFrameEnvironment?.puppetFrame, }; return await this.session.plugins.onPluginCommand(toPluginId, commandMeta, args); } public async getMainFrameDomChanges(sinceCommandId?: number): Promise<IFrontendDomChangeEvent[]> { const frameDomNodePaths = this.sessionState.db.frames.frameDomNodePathsById; return (await this.getFrameDomChanges(this.mainFrameId, sinceCommandId)).map(x => DomChangesTable.toFrontendRecord(x, frameDomNodePaths), ); } public async getFrameDomChanges( frameId: number, sinceCommandId: number, ): Promise<IDomChangeRecord[]> { await this.mainFrameEnvironment.flushPageEventsRecorder(); this.sessionState.db.flush(); return this.sessionState.db.domChanges.getFrameChanges(this.mainFrameId, sinceCommandId); } public async createDetachedState(): Promise<DetachedTabState> { // need the dom to be loaded on the page await this.navigationsObserver.waitForLoad(LoadStatus.DomContentLoaded); // find last page load const lastLoadedNavigation = this.navigations.getLastLoadedNavigation(); const domChanges = await this.getFrameDomChanges( this.mainFrameId, lastLoadedNavigation.startCommandId - 1, ); const resources = this.sessionState.getResourceLookupMap(this.id); this.logger.info('DetachingTab', { url: lastLoadedNavigation.finalUrl, domChangeIndices: domChanges.length > 0 ? [domChanges[0].eventIndex, domChanges[domChanges.length - 1].eventIndex] : [], domChanges: domChanges.length, resources: Object.keys(resources).length, }); return new DetachedTabState(this.session, lastLoadedNavigation, domChanges, resources); } /////// UTILITIES //////////////////////////////////////////////////////////////////////////////////////////////////// public toJSON() { return { id: this.id, parentTabId: this.parentTabId, sessionId: this.sessionId, url: this.url, createdAtCommandId: this.createdAtCommandId, isDetached: this.isDetached, }; } private async waitForReady(): Promise<void> { await this.mainFrameEnvironment.isReady; if (!this.isDetached && this.session.options?.blockedResourceTypes) { await this.setBlockedResourceTypes(this.session.options.blockedResourceTypes); } } private listen(): void { const page = this.puppetPage; this.close = this.close.bind(this); page.on('close', this.close); page.on('page-error', this.onPageError.bind(this), true); page.on('crashed', this.onTargetCrashed.bind(this)); page.on('console', this.onConsole.bind(this), true); page.on('frame-created', this.onFrameCreated.bind(this), true); page.on('page-callback-triggered', this.onPageCallback.bind(this)); page.on('dialog-opening', this.onDialogOpening.bind(this)); page.on('filechooser', this.onFileChooser.bind(this)); // resource requested should registered before navigations so we can grab nav on new tab anchor clicks page.on('resource-will-be-requested', this.onResourceWillBeRequested.bind(this), true); page.on('resource-was-requested', this.onResourceWasRequested.bind(this), true); page.on('resource-loaded', this.onResourceLoaded.bind(this), true); page.on('resource-failed', this.onResourceFailed.bind(this), true); page.on('navigation-response', this.onNavigationResourceResponse.bind(this), true); // websockets page.on('websocket-handshake', ev => { this.session.mitmRequestSession?.registerWebsocketHeaders(this.id, ev); }); page.on('websocket-frame', this.onWebsocketFrame.bind(this)); } private onPageCallback(event: IPuppetPageEvents['page-callback-triggered']): void { if (event.name === InjectedScripts.PageEventsCallbackName) { const { frameId, payload } = event; if (!frameId || !this.frameEnvironmentsByPuppetId.has(frameId)) { log.warn('DomRecorder.bindingCalledBeforeExecutionTracked', { sessionId: this.sessionId, payload, }); return; } this.frameEnvironmentsByPuppetId.get(frameId).onPageRecorderEvents(JSON.parse(payload)); } } /////// REQUESTS EVENT HANDLERS ///////////////////////////////////////////////////////////////// private onResourceWillBeRequested(event: IPuppetPageEvents['resource-will-be-requested']): void { const { session, lastCommandId } = this; const { resource, isDocumentNavigation, frameId, redirectedFromUrl } = event; const { browserRequestId } = resource; const url = resource.url.href; let navigations = this.frameEnvironmentsByPuppetId.get(frameId)?.navigations; // if no frame id provided, use default if (!frameId && !navigations) { navigations = this.navigations; } if (!navigations && frameId) { this.onFrameCreatedResourceEventsByFrameId[frameId] ??= []; const events = this.onFrameCreatedResourceEventsByFrameId[frameId]; if (!events.some(x => x.event === event)) { events.push({ event, type: 'resource-will-be-requested' }); } return; } if (isDocumentNavigation && !navigations.top) { navigations.onNavigationRequested( 'newFrame', url, lastCommandId, browserRequestId, event.loaderId, ); } resource.hasUserGesture ||= navigations.didGotoUrl(url); session.mitmRequestSession.browserRequestMatcher.onBrowserRequestedResource(resource, this.id); if (isDocumentNavigation && !event.resource.browserCanceled) { navigations.onHttpRequested( url, lastCommandId, redirectedFromUrl, browserRequestId, event.loaderId, ); } } private onResourceWasRequested(event: IPuppetPageEvents['resource-was-requested']): void { this.session.mitmRequestSession.browserRequestMatcher.onBrowserRequestedResourceExtraDetails( event.resource, this.id, ); } private onResourceLoaded(event: IPuppetPageEvents['resource-loaded']): void { this.session.mitmRequestSession.browserRequestMatcher.onBrowserRequestedResourceExtraDetails( event.resource, this.id, ); let frame = this.frameEnvironmentsByPuppetId.get(event.frameId); // if no frame id provided, use default if (!frame && !event.frameId) frame = this.mainFrameEnvironment; if (!frame && event.frameId) { this.onFrameCreatedResourceEventsByFrameId[event.frameId] ??= []; const events = this.onFrameCreatedResourceEventsByFrameId[event.frameId]; if (!events.some(x => x.event === event)) { events.push({ event, type: 'resource-loaded' }); } return; } const resourcesWithBrowserRequestId = this.sessionState.getBrowserRequestResources( event.resource.browserRequestId, ); const navigationTop = frame.navigations?.top; if (navigationTop && !navigationTop.resourceId.isResolved) { const url = event.resource.url?.href; // hash won't be in the http request const frameRequestedUrl = navigationTop.requestedUrl?.split('#')?.shift(); if (url === frameRequestedUrl) { if (event.resource.browserServedFromCache) { frame.navigations.onHttpResponded( event.resource.browserRequestId, event.resource.responseUrl ?? event.resource.url?.href, event.loaderId, ); } if (resourcesWithBrowserRequestId?.length) { const resource = resourcesWithBrowserRequestId[resourcesWithBrowserRequestId.length - 1]; frame.navigations.onResourceLoaded(resource.resourceId, event.resource.status); } } } if (!resourcesWithBrowserRequestId?.length) { // first check if this is a mitm error const errorsMatchingUrl = this.session.mitmErrorsByUrl.get(event.resource.url.href); // if this resource error-ed out, for (let i = 0; i < errorsMatchingUrl?.length ?? 0; i += 1) { const error = errorsMatchingUrl[i]; const request = error.event?.request?.request; if (!request) continue; if ( request.method === event.resource.method && Math.abs(request.timestamp - event.resource.requestTime.getTime()) < 500 ) { errorsMatchingUrl.splice(i, 1); this.sessionState.captureResourceRequestId( error.resourceId, event.resource.browserRequestId, this.id, ); return; } } setImmediate(r => this.checkForResourceCapture(r), event); } } private async checkForResourceCapture( event: IPuppetPageEvents['resource-loaded'], ): Promise<void> { const resourcesWithBrowserRequestId = this.sessionState.getBrowserRequestResources( event.resource.browserRequestId, ); if (resourcesWithBrowserRequestId?.length) return; const ctx = MitmRequestContext.createFromPuppetResourceRequest(event.resource); const resourceDetails = MitmRequestContext.toEmittedResource(ctx); if (!event.resource.browserServedFromCache) { resourceDetails.body = await event.body(); if (resourceDetails.body) { delete resourceDetails.response.headers['content-encoding']; delete resourceDetails.response.headers['Content-Encoding']; } } const resource = this.sessionState.captureResource(this.id, resourceDetails, true); this.checkForResolvedNavigation(event.resource.browserRequestId, resource); } private onResourceFailed(event: IPuppetPageEvents['resource-failed']): void { const { resource } = event; let loadError: Error; if (resource.browserLoadFailure) { loadError = new Error(resource.browserLoadFailure); } else if (resource.browserBlockedReason) { loadError = new Error(`Resource blocked: "${resource.browserBlockedReason}"`); } else if (resource.browserCanceled) { loadError = new Error('Load canceled'); } else { loadError = new Error( 'Resource failed to load, but the reason was not provided by devtools.', ); } const browserRequestId = event.resource.browserRequestId; let resourceId = this.session.mitmRequestSession.browserRequestMatcher.onBrowserRequestFailed({ resource, tabId: this.id, loadError, }); if (!resourceId) { const resources = this.sessionState.getBrowserRequestResources(browserRequestId); if (resources?.length) { resourceId = resources[resources.length - 1].resourceId; } } // this function will resolve any pending resourceId for a navigation const resourceMeta = this.sessionState.captureResourceFailed( this.id, MitmRequestContext.toEmittedResource({ id: resourceId, ...resource } as any), loadError, ); if (resourceMeta) this.checkForResolvedNavigation(browserRequestId, resourceMeta, loadError); } private onNavigationResourceResponse(event: IPuppetPageEvents['navigation-response']): void { let frame = this.frameEnvironmentsByPuppetId.get(event.frameId); // if no frame id provided, use default if (!frame && !event.frameId) { frame = this.mainFrameEnvironment; } if (event.frameId && !frame) { this.onFrameCreatedResourceEventsByFrameId[event.frameId] ??= []; const events = this.onFrameCreatedResourceEventsByFrameId[event.frameId]; if (!events.some(x => x.event === event)) { events.push({ event, type: 'navigation-response' }); } return; } frame.navigations.onHttpResponded(event.browserRequestId, event.url, event.loaderId); this.session.mitmRequestSession.recordDocumentUserActivity(event.url); } private onWebsocketFrame(event: IPuppetPageEvents['websocket-frame']): void { const wsResource = this.sessionState.captureWebsocketMessage(event); this.emit('websocket-message', wsResource); } private onFrameCreated(event: IPuppetPageEvents['frame-created']): void { if (this.frameEnvironmentsByPuppetId.has(event.frame.id)) return; const frame = new FrameEnvironment(this, event.frame); this.frameEnvironmentsByPuppetId.set(frame.devtoolsFrameId, frame); this.frameEnvironmentsById.set(frame.id, frame); const resourceEvents = this.onFrameCreatedResourceEventsByFrameId[frame.devtoolsFrameId]; if (resourceEvents) { for (const { event: resourceEvent, type } of resourceEvents) { if (type === 'resource-will-be-requested') this.onResourceWillBeRequested(resourceEvent as any); else if (type === 'navigation-response') this.onNavigationResourceResponse(resourceEvent as any); else if (type === 'resource-loaded') this.onResourceLoaded(resourceEvent as any); } } delete this.onFrameCreatedResourceEventsByFrameId[frame.devtoolsFrameId]; } /////// LOGGING EVENTS /////////////////////////////////////////////////////////////////////////// private onPageError(event: IPuppetPageEvents['page-error']): void { const { error, frameId } = event; this.logger.info('Window.pageError', { error, frameId }); const translatedFrameId = this.frameEnvironmentsByPuppetId.get(frameId)?.id; this.sessionState.captureError(this.id, translatedFrameId, `events.page-error`, error); } private onConsole(event: IPuppetPageEvents['console']): void { const { frameId, type, message, location } = event; const translatedFrameId = this.frameEnvironmentsByPuppetId.get(frameId)?.id; this.sessionState.captureLog(this.id, translatedFrameId, type, message, location); } private onTargetCrashed(event: IPuppetPageEvents['crashed']): void { const error = event.error; const errorLevel = event.fatal ? 'error' : 'info'; this.logger[errorLevel]('BrowserEngine.Tab.crashed', { error }); this.sessionState.captureError(this.id, this.mainFrameId, `events.error`, error); } /////// DIALOGS ////////////////////////////////////////////////////////////////////////////////// private onDialogOpening(event: IPuppetPageEvents['dialog-opening']): void { this.emit('dialog', event.dialog); } private onFileChooser(event: IPuppetPageEvents['filechooser']): void { this.lastFileChooserEvent = { event, atCommandId: this.lastCommandId }; } // CREATE public static create( session: Session, puppetPage: IPuppetPage, isDetached?: boolean, parentTab?: Tab, openParams?: { url: string; windowName: string; loaderId: string }, ): Tab { const tab = new Tab(session, puppetPage, isDetached, parentTab?.id, openParams); tab.logger.info('Tab.created', { parentTab: parentTab?.id, openParams, }); return tab; } } interface ITabEventParams { close: null; 'resource-requested': IResourceMeta; resource: IResourceMeta; dialog: IPuppetDialog; 'websocket-message': IWebsocketResourceMessage; 'child-tab-created': Tab; }
the_stack
const SEND_TEST_UPDATE_PACKETS = false; import * as express from 'express'; import { isEqual } from 'lodash'; import { Op } from 'sequelize'; import * as WebSocket from 'ws'; import { logger } from '../../logger'; import { Article, Category, ModerationRule, Preselect, Tag, TaggingSensitivity, User, } from '../../models'; import {clearInterested, INotificationData, registerInterest} from '../../notification_router'; import { countAssignments } from './assignments'; import { ARTICLE_FIELDS, CATEGORY_FIELDS, PRESELECT_FIELDS, RULE_FIELDS, serialiseObject, TAGGING_SENSITIVITY_FIELDS, TAG_FIELDS, USER_FIELDS, } from './serializer'; // TODO: Can't find a good way to get rid of the any types below. And typing is generally a mess. // Revisit when sequelize has been updated interface ISystemData { users: any; tags: any; taggingSensitivities: any; rules: any; preselects: any; } interface IAllArticlesData { categories: any; articles: any; } interface IArticleUpdateData { category: any; article: any; } interface IPerUserData { assignments: number; } interface IMessage { type: 'system' | 'global' | 'article-update' | 'user'; data: ISystemData | IAllArticlesData | IArticleUpdateData | IPerUserData; } async function getSystemData() { const users = await User.findAll({where: {group: {[Op.in]: ['admin', 'general']}}}); const userdata = users.map((u: User) => { return serialiseObject(u, USER_FIELDS); }); const tags = await Tag.findAll({}); const tagdata = tags.map((t: Tag) => { return serialiseObject(t, TAG_FIELDS); }); const taggingSensitivities = await TaggingSensitivity.findAll({}); const tsdata = taggingSensitivities.map((t: TaggingSensitivity) => { return serialiseObject(t, TAGGING_SENSITIVITY_FIELDS); }); const rules = await ModerationRule.findAll({}); const ruledata = rules.map((r: ModerationRule) => { return serialiseObject(r, RULE_FIELDS); }); const preselects = await Preselect.findAll({}); const preselectdata = preselects.map((p: Preselect) => { return serialiseObject(p, PRESELECT_FIELDS); }); return { type: 'system', data: { users: userdata, tags: tagdata, taggingSensitivities: tsdata, rules: ruledata, preselects: preselectdata, }, } as IMessage; } async function getGlobalData() { const categories = await Category.findAll({ include: [{ model: User, as: 'assignedModerators', attributes: ['id']}], }); const categoryIds: Array<number> = []; const categorydata = categories.map((c: Category) => { categoryIds.push(c.id); return serialiseObject(c, CATEGORY_FIELDS); }); const articles = await Article.findAll({ where: {[Op.or]: [{categoryId: null}, {categoryId: categoryIds}]}, include: [{ model: User, as: 'assignedModerators', attributes: ['id']}], }); const articledata = articles.map((a: Article) => { return serialiseObject(a, ARTICLE_FIELDS); }); return { type: 'global', data: { categories: categorydata, articles: articledata, }, } as IMessage; } async function getCategoryUpdate(categoryId: number) { const category = await Category.findByPk( categoryId, {include: [{ model: User, as: 'assignedModerators', attributes: ['id']}]}, ); const cData = category ? serialiseObject(category, CATEGORY_FIELDS) : undefined; return { type: 'article-update', data: { categories: [cData], articles: [], }, } as IMessage; } async function getArticleUpdate(articleId: number) { const article = await Article.findByPk( articleId, {include: [{ model: User, as: 'assignedModerators', attributes: ['id']}]}, ); if (!article) { return null; } const aData = serialiseObject(article, ARTICLE_FIELDS); const category = article.categoryId ? await Category.findByPk( article.categoryId, {include: [{ model: User, as: 'assignedModerators', attributes: ['id']}]}, ) : null; const cData = category ? serialiseObject(category, CATEGORY_FIELDS) : undefined; return { type: 'article-update', data: { categories: [cData], articles: [aData], }, } as IMessage; } async function getPerUserData(userId: number) { const user = (await User.findByPk(userId))!; const assignments = await countAssignments(user); return { type: 'user', data: { assignments: assignments, }, } as IMessage; } interface ISocketItem { userId: number; ws: Array<WebSocket>; lastPerUserMessage: IPerUserData | null; sentInitialMessages: boolean; } let lastSystemMessage: IMessage | null = null; const socketItems = new Map<number, ISocketItem>(); async function refreshSystemMessage(): Promise<boolean> { const newMessage = await getSystemData(); if (!lastSystemMessage) { lastSystemMessage = newMessage; return true; } const send = !isEqual(newMessage.data, lastSystemMessage.data); if (send) { lastSystemMessage = newMessage; } return send; } function removeSocket(si: ISocketItem, ws: WebSocket) { const index = si.ws.indexOf(ws); if (index >= 0) { si.ws.splice(index, 1); } if (si.ws.length === 0) { socketItems.delete(si.userId); } } async function refreshMessages(alwaysSend: boolean) { const sendSystem = (await refreshSystemMessage() || alwaysSend); return {sendSystem, sendUser: alwaysSend}; } async function maybeSendUpdateToUser(si: ISocketItem, {sendSystem, sendUser}: {sendSystem: boolean, sendUser: boolean}) { const userSummaryMessage = await getPerUserData(si.userId); sendUser = sendUser || !si.lastPerUserMessage || !isEqual(userSummaryMessage.data, si.lastPerUserMessage); for (const ws of si.ws) { try { if (sendSystem) { logger.info(`Sending system data to user ${si.userId}`); await ws.send(JSON.stringify(lastSystemMessage)); } if (sendUser) { logger.info(`Sending per user data to user ${si.userId}`); await ws.send(JSON.stringify(userSummaryMessage)); } } catch (e) { logger.warn(`Websocket faulty for ${si.userId}`, e.message); ws.terminate(); removeSocket(si, ws); } } si.lastPerUserMessage = userSummaryMessage.data as IPerUserData; } async function maybeSendUpdates() { for (const si of socketItems.values()) { const updateFlags = await refreshMessages(false); await maybeSendUpdateToUser(si, updateFlags); } } async function sendUpdate(type: string, update: string) { for (const si of socketItems.values()) { if (!si.sentInitialMessages) { continue; } for (const ws of si.ws) { logger.info(`Sending ${type} to user ${si.userId}`); await ws.send(update); } } } async function sendGlobal() { const update = await getGlobalData(); await sendUpdate('global', JSON.stringify(update)); } async function sendCategoryUpdate(categoryId: number) { const update = await getCategoryUpdate(categoryId); await sendUpdate('category update', JSON.stringify(update)); } async function sendArticleUpdate(articleId: number) { const update = await getArticleUpdate(articleId); await sendUpdate('article update', JSON.stringify(update)); } function sendTestUpdatePackets(si: ISocketItem) { logger.info(`*** settng up fake update notifications for user ${si.userId}`); let counter = 1; setInterval(async () => { const update = await getArticleUpdate(counter); if (!update) { logger.info(`no such article ${counter}`); counter = 1; return; } const data = update.data as IArticleUpdateData; let msg = `fake update message ${counter}`; if (counter % 3 === 1) { // Just send the category delete data.article; msg += ' category'; } else if (counter % 3 === 2) { // just send the article delete data.category; msg += ' article'; } else { msg += ' both'; } if (counter % 4 === 2) { // pretend its a new object msg += ' new'; if (data.article) { data.article.id = data.article.id + 10000 + Math.floor(Math.random() * 1000); } if (data.category) { data.category.id = data.category.id + 10000 + Math.floor(Math.random() * 1000); } } if (counter % 4 === 3) { msg += ' faked data'; // Mess with the data if (data.article) { data.article.unmoderatedCount = data.article.unmoderatedCount + Math.floor(Math.random() * 10000); } if (data.category) { data.category.unmoderatedCount = data.category.unmoderatedCount + Math.floor(Math.random() * 10000); } } logger.info(msg); counter ++; logger.info(`Sending **fake** article update to user ${si.userId} -- ${msg}`); for (const ws of si.ws) { await ws.send(JSON.stringify(update)); } }, 1000); } // Introduce a simple task queue to ensure messages are processed in the order in which they arrive const taskQueue: Array<() => Promise<void>> = []; let taskQueueProcessing = false; async function processNotification(data: INotificationData) { if (data.objectType === 'category' && data.id) { taskQueue.unshift(() => sendCategoryUpdate(data.id!)); } else if (data.objectType === 'article' && data.id) { taskQueue.unshift(() => sendArticleUpdate(data.id!)); } else { taskQueue.unshift(maybeSendUpdates); } if (taskQueueProcessing) { return; } taskQueueProcessing = true; while (taskQueue.length > 0) { const task = taskQueue.pop(); await task!(); } taskQueueProcessing = false; } let registered = false; export function createUpdateNotificationService(): express.Router { const router = express.Router({ caseSensitive: true, mergeParams: true, }); router.ws('/summary', async (ws, req) => { if (!req.user) { logger.error(`Attempt to create a socket without authentication. Bail...`); ws.terminate(); return; } const userId = (req.user as User).id; let si = socketItems.get(userId); if (!si) { si = {userId, ws: [], lastPerUserMessage: null, sentInitialMessages: false}; socketItems.set(userId, si); if (SEND_TEST_UPDATE_PACKETS) { sendTestUpdatePackets(si); } } si.ws.push(ws); if (!registered) { logger.info(`Setting up notifications`); registerInterest({ processNotification }); registered = true; } ws.on('close', () => { removeSocket(si!, ws); }); logger.info(`Websocket opened to ${(req.user as User).email}`); const updateFlags = await refreshMessages(true); await maybeSendUpdateToUser(si, updateFlags); si.sentInitialMessages = true; await sendGlobal(); }); return router; } export function destroyUpdateNotificationService() { registered = false; clearInterested(); for (const si of socketItems.values()) { for (const ws of si.ws) { ws.close(); } } socketItems.clear(); }
the_stack
import React from "react"; import ReactDOM from "react-dom"; import { Box, Button, CircularProgress, FormControl, Link as HyperLink, InputLabel, MenuItem, Stack, Select, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, TextField, } from "@mui/material"; import FilePresentIcon from '@mui/icons-material/FilePresent'; import { useWallet, } from "@solana/wallet-adapter-react"; import { Keypair, PublicKey, } from "@solana/web3.js"; import { MintInfo, } from "@solana/spl-token"; import { notify, shortenAddress, } from "@oyster/common"; import BN from 'bn.js'; import { useConnection, Connection, } from "../contexts"; import { GUMDROP_DISTRIBUTOR_ID, GUMDROP_TEMPORAL_SIGNER, } from "../utils/ids"; import { ClaimantInfo, Claimants, buildGumdrop, dropInfoFor, parseClaimants, validateTransferClaims, validateCandyClaims, validateEditionClaims, } from "../utils/claimant"; import { AuthKeys, DropInfo, Response as DResponse, distributeAwsSes, distributeManual, distributeWallet, urlAndHandleFor, } from "../utils/communication"; import { envFor, explorerLinkFor, } from "../utils/transactions"; import { DragAndDrop } from "./DragAndDrop"; import { DefaultModal } from "./DefaultModal"; // NB: assumes no overflow const randomBytes = () : Uint8Array => { // TODO: some predictable seed? sha256? const buf = new Uint8Array(4); window.crypto.getRandomValues(buf); return buf; } const WHITESPACE = "\u00A0"; const distribute = ( method : string, auth : AuthKeys, source : string, claimants : Claimants, drop : DropInfo, ) => { if (method === "AWS SES") { return distributeAwsSes(auth, source, claimants, drop); } else if (method === "Manual") { return distributeManual(auth, source, claimants, drop); } else if (method === "Wallets") { return distributeWallet(auth, source, claimants, drop); } else { throw new Error(`Unrecognized claim distribution method ${method}`); } } const reactModal = (renderModal) => { const container = document.createElement('div'); document.body.appendChild(container); const displayModal = ({ onSubmit, onDismiss }) => { ReactDOM.render(renderModal({ onSubmit, onDismiss, show: true }), container); }; const hideModal = ({ onSubmit, onDismiss }, callback) => { ReactDOM.render(renderModal({ onSubmit, onDismiss, show: false }), container, callback); }; const destroyModal = () => { ReactDOM.unmountComponentAtNode(container); document.body.removeChild(container); }; const confirmation = new Promise((resolve) => { const onSubmit = (value) => resolve(value); const onDismiss = () => resolve(undefined); displayModal({ onSubmit, onDismiss }); }); return confirmation.finally(() => { const onSubmit = () => {}; const onDismiss = () => {}; hideModal({ onSubmit, onDismiss }, destroyModal); }); }; const resendOnlyRender = ({ show, onSubmit, onDismiss }) => { const options = [ { click: () => onSubmit("create"), name: "Create and Send" }, { click: () => onSubmit("send") , name: "Send only" }, ]; return ( <DefaultModal visible={show} onCancel={onDismiss} width="70ch"> <p style={{ color: "white", fontSize: "0.9rem", marginTop: 8, width: "90%", }}> Uploaded distribution list has URLs for all claimants. Skip creation of airdrop and only re-send links? </p> <br /> <Stack direction="row" spacing={2} style={{width: "100%"}}> {options.map((opt) => { return ( <Button key={opt.name} style={{ width: "100%", color: "white", marginBottom: 8, }} variant="outlined" onClick={opt.click} > {opt.name} </Button> ); })} </Stack> </DefaultModal> ); }; const displayMintTokens = (amount : number, mintInfo : MintInfo) : string => { // TODO: better decimal rounding return String(amount / Math.pow(10, mintInfo.decimals)); }; const hyperLinkData = (data) => { const encoded = encodeURIComponent(JSON.stringify(data)); return `data:text/plain;charset=utf-8,${encoded}`; }; const shouldSendRender = (claimants, needsPin, claimMethod, claimInfo, baseKey) => { const limit = 1000; // eslint-disable-next-line react/prop-types return function ClaimPreviewC({ show, onSubmit, onDismiss }) { return ( <DefaultModal visible={show} onCancel={onDismiss} width="70ch"> <h2 style={{ color: "white", fontWeight: "bold", fontSize: "1.2rem", }} > Claim Distribution Preview{claimants.length > limit ? ` (First ${limit})` : ""} </h2> <p style={{ color: "white", fontSize: "1rem", textAlign: "center" }}> Approving will save the keypair authority generated for gumdrop state. This keypair is necessary to close the gumdrop later! </p> <TableContainer sx={{ "td, th": { color: "white" }, backgroundColor: "#444444", borderRadius: "5px", maxHeight: "30ch", }} > <Table size="small"> <TableHead> <TableRow> <TableCell>Handle</TableCell> <TableCell> {claimMethod === "edition" ? "Edition" : "Tokens" } </TableCell> {needsPin && <TableCell>Pin</TableCell>} </TableRow> </TableHead> <TableBody> {claimants.slice(0, limit).map((c, idx) => ( <TableRow key={idx} sx={{ 'td, th': { border: 0 } }} > <TableCell component="th" scope="row">{c.handle} </TableCell> <TableCell> { claimMethod === "transfer" ? displayMintTokens(c.amount, claimInfo.mint.info) : claimMethod === "candy" ? c.amount : /* === "edition" */ c.edition } </TableCell> {needsPin && <TableCell>{c.pin.toNumber()}</TableCell>} </TableRow> ))} </TableBody> </Table> </TableContainer> <Box style={{ height: "3ch" }} /> <Stack direction="row" spacing={2} style={{width: "100%"}}> <Button style={{ width: "100%", color: "white", marginBottom: 8, }} variant="outlined" onClick={() => onSubmit(false)} > Cancel </Button> <HyperLink href={hyperLinkData(Array.from(baseKey.secretKey))} download={`${baseKey.publicKey.toBase58()}.json`} underline="none" style={{width: "100%"}} > <Button style={{ width: "100%", color: "white", marginBottom: 8, }} variant="outlined" onClick={() => onSubmit(true)} > Approve </Button> </HyperLink> </Stack> </DefaultModal> ); } }; export const Create = () => { const connection = useConnection(); const wallet = useWallet(); // claim state const [claimMethod, setClaimMethod] = React.useState(localStorage.getItem("claimMethod") || ""); const [candyConfig, setCandyConfig] = React.useState(localStorage.getItem("candyConfig") || ""); const [candyUUID, setCandyUUID] = React.useState(localStorage.getItem("candyUUID") || ""); const [mint, setMint] = React.useState(localStorage.getItem("mint") || ""); const [masterMint, setMasterMint] = React.useState(localStorage.getItem("masterMint") || ""); const [filename, setFilename] = React.useState(""); const [text, setText] = React.useState(""); // response state const [claimURLs, setClaimURLs] = React.useState<Array<{ [key: string]: any }>>([]); const [responses, setResponses] = React.useState<Array<DResponse>>([]); // auth state const [otpAuth, setOtpAuth] = React.useState(localStorage.getItem("otpAuth") || "default"); const [commMethod, setCommMethod] = React.useState(localStorage.getItem("commMethod") || ""); const [commAuth, setCommAuth] = React.useState<AuthKeys>({}); const [commSource, setCommSource] = React.useState(localStorage.getItem("commSource") || ""); const [awsAccessKeyId, setAwsAccessKeyId] = React.useState(""); const [awsSecretKey, setAwsSecretKey] = React.useState(""); const explorerUrlFor = (key : PublicKey) => { return `https://explorer.solana.com/address/${key.toBase58()}?cluster=${envFor(connection)}`; } const distributeClaims = async (claimants, drop) => { const responses = await distribute( commMethod, commAuth, commSource, claimants, drop); console.log("Responses", responses); setResponses(responses); // notify if the above routine is actually supposed to do anything // (manual and wallet do nothing atm) if (commMethod === "AWS SES") { notify({ message: "Gumdrop email distribution completed", }); } } const submit = async (e : React.SyntheticEvent) => { e.preventDefault(); setClaimURLs([]); setResponses([]); if (!wallet.connected || wallet.publicKey === null) { throw new Error(`Wallet not connected`); } const claimants = parseClaimants(text, filename, commMethod); if (claimants.length === 0) { throw new Error(`No claimants provided`); } const dropInfo = dropInfoFor(envFor(connection), claimMethod, mint, candyConfig, masterMint); // check that auth is correct... await distribute( commMethod, commAuth, commSource, [], dropInfo); const mightHaveExisting = (info : ClaimantInfo) => { return info.url !== undefined && info.url !== null; }; if (claimants.reduce((acc, c) => acc && mightHaveExisting(c), true)) { const resendOnly = await reactModal(resendOnlyRender); console.log("Resend only", resendOnly); if (resendOnly === "send") { setClaimURLs(urlAndHandleFor(claimants)); await distributeClaims(claimants, dropInfo); return; } else if (resendOnly === "create") { // fallthrough to full create } else { // dismissed. don't use exceptions for control flow? throw new Error("Dismissed"); } } let claimInfo; switch (claimMethod) { case "transfer": { claimInfo = await validateTransferClaims( connection, wallet.publicKey, claimants, mint, ); break; } case "candy": { claimInfo = await validateCandyClaims( connection, wallet.publicKey, claimants, candyConfig, candyUUID, ); break; } case "edition": { claimInfo = await validateEditionClaims( connection, wallet.publicKey, claimants, masterMint, ); break; } default: throw new Error(`Unknown claim method ${claimMethod}`); } console.log("Claims info", claimInfo); claimants.forEach(c => { c.pin = new BN(randomBytes()); c.seed = claimMethod === "transfer" ? claimInfo.mint.key : claimMethod === "candy" ? claimInfo.config : /* === edition */ claimInfo.masterMint.key; }); // temporal auth is the AWS signer by 'default' and a no-op key otherwise let temporalSigner; if (commMethod === "Wallets") { // TODO: this is a bit jank. There should be no form option to set the // OTP auth if we are using a wallet but there's still a defaulted value // atm... // NB: We also need this to not be 'none' since there is a special check // for claimant_secret==accounts.temporal temporalSigner = GUMDROP_DISTRIBUTOR_ID; } else if (otpAuth === "default") { temporalSigner = GUMDROP_TEMPORAL_SIGNER; } else if (otpAuth === "none") { temporalSigner = PublicKey.default; } else { throw new Error(`Unknown OTP authorization type ${otpAuth}`); } console.log(`Temporal signer: ${temporalSigner.toBase58()}`); const base = Keypair.generate(); console.log(`Base ${base.publicKey.toBase58()}`); const needsPin = commMethod !== "Wallets"; const instructions = await buildGumdrop( connection, wallet.publicKey, needsPin, claimMethod, `${window.location.origin}/gumdrop`, base.publicKey, temporalSigner, claimants, claimInfo ); const shouldSend = await reactModal( shouldSendRender(claimants, needsPin, claimMethod, claimInfo, base) ) as boolean | undefined; if (shouldSend !== true) { // dismissed. don't use exceptions for control flow? throw new Error("Claim distribution preview not approved"); } setClaimURLs(urlAndHandleFor(claimants)); const createResult = await Connection.sendTransactionWithRetry( connection, wallet, instructions, [base] ); console.log(createResult); if (typeof createResult === "string") { throw new Error(createResult); } else { notify({ message: "Gumdrop creation succeeded", description: ( <HyperLink href={explorerLinkFor(createResult.txid, connection)}> View transaction on explorer </HyperLink> ), }); } console.log("Distributing claim URLs"); await distributeClaims(claimants, dropInfo); }; const handleFiles = (files : FileList | null) => { if (files === null || files.length !== 1) { notify({ message: "File upload failed", description: `Received ${files?.length} files`, }); return; } const file = files[0]; const reader = new FileReader(); reader.onload = (e) => { if (e !== null && e.target !== null) { if (typeof e.target.result === "string") { try { parseClaimants(e.target.result, file.name, commMethod); } catch { notify({ message: `File upload failed for: ${file.name}`, description: ( <span> Could not parse uploaded file.{WHITESPACE} <HyperLink href="#/"> Does it follow the JSON scheme? </HyperLink> </span> ), }); setFilename(""); setText(""); return; } setFilename(file.name); setText(e.target.result); } else { notify({ message: `File upload failed for: ${file.name}`, description: "Could not read uploaded file", }); } } }; reader.readAsText(file); }; const claimData = (claimMethod) => { if (claimMethod === "candy") { return ( <React.Fragment> <TextField id="config-text-field" label="Candy Config" value={candyConfig} onChange={e => { setCandyConfig(e.target.value); localStorage.setItem("candyConfig", e.target.value); }} /> <TextField id="config-uuid-text-field" label="Candy UUID" value={candyUUID} onChange={e => { setCandyUUID(e.target.value); localStorage.setItem("candyUUID", e.target.value); }} /> </React.Fragment> ); } else if (claimMethod === "transfer") { return ( <TextField id="mint-text-field" label="Mint" value={mint} onChange={(e) => { localStorage.setItem("mint", e.target.value); setMint(e.target.value); }} /> ); } else if (claimMethod === "edition") { // transfers master mint token from this account to the distributor // wallet ATA return ( <TextField id="master-mint-text-field" label="Master Mint" value={masterMint} onChange={(e) => { localStorage.setItem("masterMint", e.target.value); setMasterMint(e.target.value); }} /> ); } }; const commAuthorization = (commMethod) => { if (commMethod === "AWS SES") { return ( <React.Fragment> <TextField id="comm-access-key-id-field" label={`${commMethod} Access Key Id`} value={awsAccessKeyId} onChange={(e) => { setCommAuth(prev => ({...prev, accessKeyId: e.target.value})); setAwsAccessKeyId(e.target.value) }} /> <TextField id="comm-secret-access-key-field" label={`${commMethod} Secret Access Key`} value={awsSecretKey} onChange={(e) => { setCommAuth(prev => ({...prev, secretAccessKey: e.target.value})); setAwsSecretKey(e.target.value) }} /> <TextField id="comm-source-field" label={`${commMethod} Source`} value={commSource} onChange={(e) => { localStorage.setItem("commSource", e.target.value); setCommSource(e.target.value) }} /> </React.Fragment> ); } // commMethod === "Manual" || commMethod === "Wallets" return null; }; const fileUpload = ( <React.Fragment> <DragAndDrop handleDrop={handleFiles} > <Stack direction="row" style={{ height: "15ch", }} sx={{ border: '1px dashed grey', justifyContent: "center", alignContent: "center", }} > <Button variant="text" component="label" style={{ padding: 0, // don't make the button click field too large... marginTop: "5ch", marginBottom: "5ch", }} > Upload a {filename === "" ? "distribution" : "different"} list <input type="file" onChange={(e) => { handleFiles(e.target.files); // re-parse every time... e.target.value = ''; }} hidden /> </Button> {WHITESPACE} {/*For display alignment...*/} <Button variant="text" component="label" disabled={true} style={{ padding: 0, color: "#eee", }} > or drag it here </Button> </Stack> </DragAndDrop> {filename !== "" ? (<Button variant="text" component="label" disabled={true} style={{ padding: 0, color: "#eee", }} > <FilePresentIcon /> <span>{WHITESPACE} Uploaded {filename}</span> </Button> ) : (<Box/>)} </React.Fragment> ); const [loading, setLoading] = React.useState(false); const loadingProgress = () => ( <CircularProgress size={24} sx={{ position: 'absolute', top: '50%', left: '50%', marginTop: '-12px', marginLeft: '-12px', }} /> ); const createAirdrop = ( <Box sx={{ position: "relative" }}> <Button disabled={!wallet.connected || !commMethod || !filename || loading} variant="contained" style={{ width: "100%" }} onClick={(e) => { setLoading(true); const wrap = async () => { try { await submit(e); setLoading(false); } catch (err) { notify({ message: "Create failed", description: `${err}`, }); setLoading(false); } }; wrap(); }} > Create{claimURLs.length > 0 ? " Another " : " "}Gumdrop </Button> {loading && loadingProgress()} </Box> ); const otpAuthC = ( <React.Fragment> <FormControl fullWidth> <InputLabel id="otp-auth-label">OTP Authorization</InputLabel> <Select labelId="otp-auth-label" id="otp-auth-select" value={otpAuth} label="OTP Authorization" onChange={(e) => { localStorage.setItem("otpAuth", e.target.value); setOtpAuth(e.target.value); }} style={{textAlign: "left"}} > <MenuItem value={"default"}> Default{WHITESPACE} <HyperLink href={explorerUrlFor(GUMDROP_TEMPORAL_SIGNER)} underline="none" target="_blank" rel="noopener noreferrer" > ({shortenAddress(GUMDROP_TEMPORAL_SIGNER.toBase58())}) </HyperLink> </MenuItem> <MenuItem value={"none"}>None</MenuItem> </Select> </FormControl> </React.Fragment> ); return ( <Stack spacing={2}> <FormControl fullWidth> <InputLabel id="claim-method-label">Claim Method</InputLabel> <Select labelId="claim-method-label" id="claim-method-select" value={claimMethod} label="Claim Method" onChange={(e) => { localStorage.setItem("claimMethod", e.target.value); setClaimMethod(e.target.value); }} style={{textAlign: "left"}} > <MenuItem value={"transfer"}>Token Transfer</MenuItem> <MenuItem value={"candy"}>Candy Machine</MenuItem> <MenuItem value={"edition"}>Limited Edition</MenuItem> </Select> </FormControl> {claimMethod !== "" && claimData(claimMethod)} <FormControl fullWidth> <InputLabel id="comm-method-label">Distribution Method</InputLabel> <Select labelId="comm-method-label" id="comm-method-select" value={commMethod} label="Distribution Method" onChange={(e) => { if (e.target.value === "Discord") { notify({ message: "Discord distribution unavailable", description: "Please use the CLI for this. Discord does not support browser-connection requests", }); return; } localStorage.setItem("commMethod", e.target.value); setCommMethod(e.target.value); }} style={{textAlign: "left"}} > <MenuItem value={"AWS SES"}>AWS SES</MenuItem> <MenuItem value={"Discord"}>Discord</MenuItem> <MenuItem value={"Wallets"}>Wallets</MenuItem> <MenuItem value={"Manual"}>Manual</MenuItem> </Select> </FormControl> {commMethod !== "" && commAuthorization(commMethod)} {commMethod !== "" && commMethod !== "Wallets" && otpAuthC} {commMethod !== "" && fileUpload} {createAirdrop} {claimURLs.length > 0 && ( <HyperLink href={hyperLinkData(claimURLs)} download="claimURLs.json" underline="none" style={{width: "100%"}} > <Button variant="contained" style={{width: "100%"}} > Download claim URLs </Button> </HyperLink> )} {responses.length > 0 && ( <HyperLink href={hyperLinkData(responses)} download="responses.json" underline="none" style={{width: "100%"}} > <Button variant="contained" style={{width: "100%"}} > Download distribution responses </Button> </HyperLink> )} </Stack> ); };
the_stack
import { Request } from "express"; import { RequestInfo } from "./RequestInfo"; import { MeterManagement } from "./MeterManagement"; import { MeterInfo } from "./MeterInfo"; import { TradeInfo } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/TradeInfo"; import { transactionManagement } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/routes/index"; import { verifierFactory } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/routing-interface/routes/index"; import { BusinessLogicBase } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/business-logic-plugin/BusinessLogicBase"; import { makeRawTransaction } from "./TransactionEthereum"; import { LedgerEvent } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/verifier/LedgerPlugin"; import { json2str } from "../../packages/cactus-cmd-socketio-server/src/main/typescript/verifier/DriverCommon"; const fs = require("fs"); const path = require("path"); const yaml = require("js-yaml"); //const config: any = JSON.parse(fs.readFileSync("/etc/cactus/default.json", 'utf8')); const config: any = yaml.safeLoad( fs.readFileSync("/etc/cactus/default.yaml", "utf8") ); import { getLogger } from "log4js"; const moduleName = "BusinessLogicElectricityTrade"; const logger = getLogger(`${moduleName}`); logger.level = config.logLevel; export class BusinessLogicElectricityTrade extends BusinessLogicBase { businessLogicID: string; meterManagement: MeterManagement; constructor(businessLogicID: string) { super(); this.businessLogicID = businessLogicID; this.meterManagement = new MeterManagement(); } startTransaction(req: Request, businessLogicID: string, tradeID: string) { logger.debug("called startTransaction()"); // set RequestInfo const requestInfo: RequestInfo = new RequestInfo(); requestInfo.businessLogicID = businessLogicID; // set TradeID requestInfo.setTradeID(tradeID); // Create trade information const tradeInfo: TradeInfo = new TradeInfo( requestInfo.businessLogicID, requestInfo.tradeID ); this.startMonitor(tradeInfo); } startMonitor(tradeInfo: TradeInfo) { // Get Verifier Instance logger.debug( `##startMonitor(): businessLogicID: ${tradeInfo.businessLogicID}` ); const useValidator = JSON.parse( transactionManagement.getValidatorToUse(tradeInfo.businessLogicID) ); logger.debug( `filterKey: ${config.electricityTradeInfo.sawtooth.filterKey}` ); const options = { filterKey: config.electricityTradeInfo.sawtooth.filterKey, }; // const verifierSawtooth = transactionManagement.getVerifier(useValidator['validatorID'][0], options); const verifierSawtooth = verifierFactory.getVerifier( useValidator["validatorID"][0], "BusinessLogicElectricityTrade", options ); logger.debug("getVerifierSawtooth"); } remittanceTransaction(transactionSubset: object) { logger.debug( `called remittanceTransaction(), accountInfo = ${json2str( transactionSubset )}` ); const accountInfo = this.getAccountInfo(transactionSubset); if (Object.keys(accountInfo).length === 0) { logger.debug(`remittanceTransaction(): skip (No target meter)`); return; } const txParam: { fromAddress: string; fromAddressPkey: string; toAddress: string; amount: number; gas: number; } = { fromAddress: accountInfo["fromAddress"], fromAddressPkey: accountInfo["fromAddressPkey"], toAddress: accountInfo["toAddress"], amount: Number(transactionSubset["Value"]), gas: config.electricityTradeInfo.ethereum.gas, }; logger.debug(`####txParam = ${json2str(txParam)}`); // Get Verifier Instance logger.debug( `##remittanceTransaction(): businessLogicID: ${this.businessLogicID}` ); const useValidator = JSON.parse( transactionManagement.getValidatorToUse(this.businessLogicID) ); // const verifierEthereum = transactionManagement.getVerifier(useValidator['validatorID'][1]); const verifierEthereum = verifierFactory.getVerifier( useValidator["validatorID"][1], "BusinessLogicElectricityTrade" ); logger.debug("getVerifierEthereum"); // Generate parameters for// sendRawTransaction logger.debug(`####exec makeRawTransaction!!`); makeRawTransaction(txParam) .then((result) => { logger.info("remittanceTransaction txId : " + result.txId); // Set Parameter logger.debug("remittanceTransaction data : " + json2str(result.data)); const contract = {}; // NOTE: Since contract does not need to be specified, specify an empty object. const method = { type: "web3Eth", command: "sendRawTransaction" }; const args = { args: [result.data["serializedTx"]] }; // Run Verifier (Ethereum) verifierEthereum .sendAsyncRequest(contract, method, args) .then(() => { logger.debug(`##remittanceTransaction sendAsyncRequest finish`); }) .catch((err) => { logger.error(err); }); }) .catch((err) => { logger.error(err); }); } onEvent(ledgerEvent: LedgerEvent, targetIndex: number): void { logger.debug(`##in BLP:onEvent()`); logger.debug( `##onEvent(): ${json2str(ledgerEvent["data"]["blockData"][targetIndex])}` ); switch (ledgerEvent.verifierId) { case config.electricityTradeInfo.sawtooth.validatorID: this.onEventSawtooth(ledgerEvent.data, targetIndex); break; case config.electricityTradeInfo.ethereum.validatorID: this.onEventEthereum(ledgerEvent.data, targetIndex); break; default: logger.error( `##onEvent(), invalid verifierId: ${ledgerEvent.verifierId}` ); return; } } onEventSawtooth(event: object, targetIndex: number): void { logger.debug(`##in onEventSawtooth()`); const tx = this.getTransactionFromSawtoothEvent(event, targetIndex); if (tx == null) { logger.error(`##onEventSawtooth(): invalid event: ${json2str(event)}`); return; } try { const txId = tx["header_signature"]; logger.debug(`##txId = ${txId}`); if (tx["payload_decoded"][0].Verb !== "set") { const transactionSubset = { Name: tx["payload_decoded"][0].Name, Value: tx["payload_decoded"][0].Value, Verb: tx["payload_decoded"][0].Verb, }; this.remittanceTransaction(transactionSubset); } } catch (err) { logger.error( `##onEventSawtooth(): err: ${err}, event: ${json2str(event)}` ); } } getTransactionFromSawtoothEvent( event: object, targetIndex: number ): object | null { try { const retTransaction = event["blockData"][targetIndex]; logger.debug( `##getTransactionFromSawtoothEvent(), retTransaction: ${retTransaction}` ); return retTransaction; } catch (err) { logger.error( `##getTransactionFromSawtoothEvent(): invalid even, err:${err}, event:${event}` ); } } onEventEthereum(event: object, targetIndex: number): void { logger.debug(`##in onEventEthereum()`); const tx = this.getTransactionFromEthereumEvent(event, targetIndex); if (tx == null) { logger.error(`##onEventEthereum(): invalid event: ${json2str(event)}`); return; } try { const txId = tx["hash"]; const status = event["status"]; logger.debug(`##txId = ${txId}`); logger.debug(`##status =${status}`); if (status !== 200) { logger.error( `##onEventEthereum(): error event, status: ${status}, txId: ${txId}` ); return; } } catch (err) { logger.error( `##onEventEthereum(): err: ${err}, event: ${json2str(event)}` ); } } getTransactionFromEthereumEvent( event: object, targetIndex: number ): object | null { try { const retTransaction = event["blockData"]["transactions"][targetIndex]; logger.debug( `##getTransactionFromEthereumEvent(), retTransaction: ${retTransaction}` ); return retTransaction; } catch (err) { logger.error( `##getTransactionFromEthereumEvent(): invalid even, err:${err}, event:${event}` ); } } getOperationStatus(tradeID: string): object { logger.debug(`##in getOperationStatus()`); return {}; } getTxIDFromEvent( ledgerEvent: LedgerEvent, targetIndex: number ): string | null { logger.debug(`##in getTxIDFromEvent`); // logger.debug(`##event: ${json2str(ledgerEvent)}`); switch (ledgerEvent.verifierId) { case config.electricityTradeInfo.sawtooth.validatorID: return this.getTxIDFromEventSawtooth(ledgerEvent.data, targetIndex); case config.electricityTradeInfo.ethereum.validatorID: return this.getTxIDFromEventEtherem(ledgerEvent.data, targetIndex); default: logger.error( `##getTxIDFromEvent(): invalid verifierId: ${ledgerEvent.verifierId}` ); } return null; } getTxIDFromEventSawtooth(event: object, targetIndex: number): string | null { logger.debug(`##in getTxIDFromEventSawtooth()`); const tx = this.getTransactionFromSawtoothEvent(event, targetIndex); if (tx == null) { logger.warn(`#getTxIDFromEventSawtooth(): skip(not found tx)`); return null; } try { const txId = tx["header_signature"]; if (typeof txId !== "string") { logger.warn( `#getTxIDFromEventSawtooth(): skip(invalid block, not found txId.), event: ${json2str( event )}` ); return null; } logger.debug(`###getTxIDFromEventSawtooth(): txId: ${txId}`); return txId; } catch (err) { logger.error( `##getTxIDFromEventSawtooth(): err: ${err}, event: ${json2str(event)}` ); return null; } } getTxIDFromEventEtherem(event: object, targetIndex: number): string | null { logger.debug(`##in getTxIDFromEventEtherem()`); const tx = this.getTransactionFromEthereumEvent(event, targetIndex); if (tx == null) { logger.warn(`#getTxIDFromEventEtherem(): skip(not found tx)`); return null; } try { const txId = tx["hash"]; if (typeof txId !== "string") { logger.warn( `#getTxIDFromEventEtherem(): skip(invalid block, not found txId.), event: ${json2str( event )}` ); return null; } logger.debug(`###getTxIDFromEventEtherem(): txId: ${txId}`); return txId; } catch (err) { logger.error( `##getTxIDFromEventEtherem(): err: ${err}, event: ${json2str(event)}` ); return null; } } getEventDataNum(ledgerEvent: LedgerEvent): number { logger.debug( `##in BLP:getEventDataNum(), ledgerEvent.verifierId: ${ledgerEvent.verifierId}` ); const event = ledgerEvent.data; let retEventNum = 0; try { switch (ledgerEvent.verifierId) { case config.electricityTradeInfo.sawtooth.validatorID: retEventNum = event["blockData"].length; break; case config.electricityTradeInfo.ethereum.validatorID: retEventNum = event["blockData"]["transactions"].length; break; default: logger.error( `##getEventDataNum(): invalid verifierId: ${ledgerEvent.verifierId}` ); break; } logger.debug( `##getEventDataNum(): retEventNum: ${retEventNum}, verifierId: ${ledgerEvent.verifierId}` ); return retEventNum; } catch (err) { logger.error( `##getEventDataNum(): invalid even, err: ${err}, event: ${event}` ); return 0; } } getAccountInfo(transactionSubset: object): object { const transactionInfo = {}; // Get Meter Information. const meterInfo: MeterInfo | null = this.meterManagement.getMeterInfo( transactionSubset["Name"] ); if (meterInfo === null) { logger.debug(`Not registered. meterID = ${transactionSubset["Name"]}`); return transactionInfo; } logger.debug(`getAccountInfo(): Verb = ${transactionSubset["Verb"]}`); if (transactionSubset["Verb"] === "inc") { logger.debug("getAccountInfo(): Verb = inc"); transactionInfo["fromAddress"] = "0x" + meterInfo.bankAccount; transactionInfo["fromAddressPkey"] = meterInfo.bankAccountPKey; transactionInfo["toAddress"] = "0x" + meterInfo.powerCompanyAccount; } return transactionInfo; } setConfig(meterParams: string[]): object { logger.debug("called setConfig()"); // add MeterInfo const meterInfo = new MeterInfo(meterParams); const result: {} = this.meterManagement.addMeterInfo(meterInfo); return result; } }
the_stack
import def = require("raml-definition-system"); import builder = require("../parser/ast.core/builder"); import typeSystem = def.rt; import tsInterfaces = typeSystem.tsInterfaces; import _ = require("underscore"); import ll = require("../parser/lowLevelAST"); import yaml = require("yaml-ast-parser"); import hlImpl = require("../parser/highLevelImpl"); import hl = require("../parser/highLevelAST"); import referencePatcher=require("../parser/ast.core/referencePatcher"); import typeExpressions = def.rt.typeExpressions; import jsonSerializerHL = require("./jsonSerializerHL"); export type IPropertyInfo = tsInterfaces.IPropertyInfo; export type IParsedType = tsInterfaces.IParsedType; export type ITypeFacet = tsInterfaces.ITypeFacet; export type IExample = tsInterfaces.IExample; export type IAnnotation = tsInterfaces.IAnnotation; export type IConstraint = tsInterfaces.IConstraint; export type ElementSourceInfo = tsInterfaces.ElementSourceInfo; export interface BranchingData{ branchingOption(branchId:number):number; typeMap():TypeMap; expander():TypeExpander; } export interface TypeMap{ addType(t:TypeEntry):void; removeType(t:TypeEntry):void; hasType(t:TypeEntry):boolean; hasTypeByName(name:string):boolean; typeByName(name:string):TypeEntry; addProperty(typeName:string,propName:string,prop:Entry); property(typeName:string,propName:string):Entry; } export interface BranchingRegistry{ nextBranchId(optionsCount:number):number; possibleBranches(tm?:TypeMap):BranchingData[]; expander():TypeExpander; } export interface Entry{ append(te:GeneralTypeEntry,bd:BranchingData):void; } export class PropertyEntry implements Entry{ constructor(protected _original:IPropertyInfo, protected _name:string, protected _type:TypeEntry, protected _required:boolean, protected isFacet=false, protected _metadata:any, protected _src:IPropertyInfo=null){ } name():string{ return this._original ? this._original.name() : this._name; } original(){ return this._original; } append(te:GeneralTypeEntry,bd:BranchingData):void{ let propType:TypeEntry; if(this._type.isUnion()){ const union = (<UnionTypeEntry>this._type); let optionId = bd.branchingOption(union.branchId()); let option = union.options()[optionId]; if(option.isBuiltIn()){ propType = option; } else { let etp = new GeneralTypeEntry(option.original(), [], null, [], [], option.name()); option.append(etp, bd); propType = etp; } } else { let etp = new GeneralTypeEntry(this._type.original(), [], null, [], [], this._type.name()); this._type.append(etp,bd); propType = etp; } let newPropEntry = new PropertyEntry(this._original,this._name,propType,this.required(),this.isFacet,this.metadata(),this._src); if(this.isFacet){ te.addFacet(newPropEntry); } else { te.addProperty(newPropEntry); } } setType(t:TypeEntry){ this._type = t; } type():TypeEntry{ return this._type; } required():boolean{ if(this._required!=null){ return this._required; } return this._original.required(); } metadata():any{ return this._metadata; } annotations(){ return this._original ? this._original.annotations() : []; } source(){ let src = this._original || this._src; if(!src){ return null; } return new GeneralTypeEntry(src.declaredAt(),[],null,[],[],null); } } export interface TypeEntry extends Entry{ name():string; displayName():string; original():IParsedType; isUnion():boolean; isBuiltIn():boolean; isExternal():boolean; isUnknown():boolean; schema():string; isIntersection():boolean; addSuperType(type:TypeEntry):void; superTypes():TypeEntry[]; clone():TypeEntry; possibleBuiltInTypes(occured:{[key:string]:boolean}):string[]; branchingRegistry(): BranchingRegistry; allFacets():ITypeFacet[]; declaredFacets():ITypeFacet[]; isRecursionPoint():boolean; examples(expand:boolean):IExample[] meta():ITypeFacet[]; schemaPath():string; id():string; typeAttributeValue():any; } export class AbstractTypeEntry implements TypeEntry{ constructor(protected _original:IParsedType,protected _superTypes:TypeEntry[]){ this._id = ""+(globalId++); } protected _branchingRegistry:BranchingRegistry; private _id:string; protected _typeAttrVal:string; id(){ return this._id; } branchingRegistry(): BranchingRegistry { return this._branchingRegistry; } setBranchingRegistry(value: BranchingRegistry) { this._branchingRegistry = value; } name():string{ return this._original && this._original.name(); } isUnion():boolean{ return false; } isBuiltIn():boolean{ return false; } isExternal():boolean{ if(this._original){ return this._original.isExternal(); } for(let st of this.superTypes()){ if(st.isExternal()){ return true; } } return false; } isUnknown():boolean{ if(this._original && this._original.isUnknown()){ return _.find(this._original.allFacets(),x=>x.facetName()=="importedByChain")==null; } return false; } schema():string{ if(this._original){ let et = _.find([this._original].concat(this._original.allSuperTypes()),x=> (<IParsedType>x).kind()=="external"); if(et) { return (<any>et).schema(); } return null; } for(let st of this.superTypes()){ let sch = st.schema(); if(sch){ return sch; } } return null; } isIntersection():boolean{ return false; } addSuperType(type:TypeEntry):void{ this._superTypes = this._superTypes || []; if(this._superTypes.indexOf(type)<0) { this._superTypes.push(type); } } superTypes():TypeEntry[]{ return this._superTypes; } original():IParsedType{ return this._original; } append(te:GeneralTypeEntry,bd:BranchingData):void{ // if(!te._original){ // te._original = this.original(); // } } clone():TypeEntry{ throw new Error("not implemented"); } possibleBuiltInTypes():string[]{ throw new Error("not implemented"); } declaredFacets() { let result:ITypeFacet[] = []; if(this._original){ result = this._original.declaredFacets(); result = result.filter(x=>x.kind()!=tsInterfaces.MetaInformationKind.Example && x.kind()!=tsInterfaces.MetaInformationKind.Examples); } return result; } allFacets(){ let meta = this.meta(); let result = meta.filter(x=>x.kind()!=tsInterfaces.MetaInformationKind.FacetDeclaration); return result; } isRecursionPoint():boolean{ return false; } examples(expand:boolean):IExample[]{ if(this._original){ let examples = <IExample[]>this._original.examples(); return examples; } return []; } declaredExampleFacets() { let result:ITypeFacet[] = []; if(this._original){ result = this._original.declaredFacets(); result = result.filter(x=>x.kind()==tsInterfaces.MetaInformationKind.Example || x.kind()==tsInterfaces.MetaInformationKind.Examples); } return result; } meta(){ let result:ITypeFacet[] = []; if(this._original){ result = this._original.allFacets(); } else{ for(let st of this.superTypes()){ st.allFacets().forEach(x=>result.push(x)); } } result = result.filter(x=> x.kind()!=tsInterfaces.MetaInformationKind.Example && x.kind()!=tsInterfaces.MetaInformationKind.Examples && x.kind()!=tsInterfaces.MetaInformationKind.FacetDeclaration); return result; } schemaPath():string{ if(!this.original()||!this.original().superTypes().filter(x=>{ return x.superTypes().length==1 && x.superTypes()[0].name()=="external" }).length){ return null; } let schPath = _.find(this.meta(),x=>x.kind()==tsInterfaces.MetaInformationKind.SchemaPath); return schPath && schPath.value(); } sourceMap():ElementSourceInfo{ return this.getOneMetaValue(tsInterfaces.MetaInformationKind.SchemaPath); } displayName():string{ return this.getOneMetaValue(tsInterfaces.MetaInformationKind.DisplayName); } private getOneMetaValue(kind:tsInterfaces.MetaInformationKind){ let sourceMap = _.find(this.declaredFacets(),x=>x.kind()==kind); if(sourceMap){ return sourceMap.value(); } return null; } typeAttributeValue():any{ return typeAttributeValue(this._original)||this._typeAttrVal; } setTypeAttributeValue(val:string){ this._typeAttrVal = val; } } var globalId = 0; export class GeneralTypeEntry extends AbstractTypeEntry{ protected facets:PropertyEntry[] = []; constructor( _original:IParsedType, _superTypes:TypeEntry[]=[], protected _componentType: TypeEntry, protected _properties: PropertyEntry[]=[], protected _facets: PropertyEntry[]=[], protected _name:string){ super(_original,_superTypes); } private _isRecursionPoint:boolean; private _depth:number; private metadataSource:TypeEntry; setDepth(d:number){ this._depth = d; } depth(){ return this._depth; } clone(ct?:TypeEntry):GeneralTypeEntry{ return new GeneralTypeEntry(this._original,[],ct, [], [], this.name()); } possibleBuiltInTypes(occured:{[key:string]:boolean}={}):string[]{ if(this.name()){ if(occured[this.name()]){ return []; } occured[this.name()] = true; } let result:string[] = []; // if(this.original()&&!this.original().isUnion()) { // let possibleTypes = [this.original()].concat(this.original().allSuperTypes()).filter(x => x.isBuiltin()); // for (let o of this.original().allOptions()) { // possibleTypes = possibleTypes.concat([o].concat(o.allSuperTypes()).filter(x => x.isBuiltin())); // } // possibleTypes = _.unique(possibleTypes); // let map:{[key:string]:typeSystem.IParsedType} = {}; // possibleTypes.forEach(x=>map[x.name()]=x); // possibleTypes.forEach(x=>{ // x.allSuperTypes().forEach(y=>delete map[y.name()]); // }); // result = _.unique(Object.keys(map)); // } // else { for(let st of this.superTypes()){ //if(!st.isUnion()) { result = result.concat(st.possibleBuiltInTypes(occured)); // } // else{ // for(let o of (<UnionTypeEntry>st).options()){ // result = result.concat(o.possibleBuiltInTypes(occured)); // } // } } let map:{[key:string]:boolean} = {}; result.forEach(x=>map[x]=true); result.forEach(x=>{ let t = typeSystem.builtInTypes().get(x); if(t) { t.allSuperTypes().forEach(y => delete map[y.name()]); } }); delete map["unknown"]; result = Object.keys(map); // } return result; } componentType():TypeEntry{ return this._componentType; } setComponentType(componentType:TypeEntry){ this._componentType = componentType; } properties():PropertyEntry[]{ return this._properties; } definedFacets():PropertyEntry[]{ return this._facets; } addProperty(propertyEntry:PropertyEntry){ this._properties.push(propertyEntry); } addFacet(propertyEntry:PropertyEntry){ this._facets.push(propertyEntry); } append(te:GeneralTypeEntry,bd:BranchingData):void{ if (this._original && this._original.kind() != "union") { te._original = this._original; } if (this.isExternal()) { return; } if(bd.typeMap().hasType(this)&&this.depth()==0){//isRecursionPoint()){ te.setIsRecursionPoint(); return; } if(this._typeAttrVal!=null) { te.setTypeAttributeValue(this._typeAttrVal); } bd.typeMap().addType(this); try { if (this._componentType) { let ct = bd.expander().expandHierarchy( this._componentType, this._componentType.branchingRegistry(), bd.typeMap()); //if(!te.componentType()) { te.setComponentType(ct); // } // else{ // let cType = new GeneralTypeEntry(null,[],null,[],[],null); // te.componentType().append(cType,null); // ct.append(cType,null); // te.setComponentType(cType); // } } if (this._properties.length > 0) { let pMap:{[key:string]:PropertyEntry[]} = {}; for (let p of this._properties) { let pName = p.name(); let pArr = pMap[pName]; if(!pArr){ pArr = []; pMap[pName] = pArr; } pArr.push(p); } for (let pName of Object.keys(pMap)) { let pArr = pMap[pName]; if(pArr.length==1) { pArr[0].append(te, bd); } else{ let pType = new GeneralTypeEntry(null,[],null,[], [], null); let required = false; pArr.forEach(x=>{ pType.addSuperType(x.type()); required = required || x.required(); }); let mergedProp = new PropertyEntry(null,pName,pType,required,false,null,pArr[0].original()); mergedProp.append(te, bd); } } } if (this._facets.length > 0) { for (let f of this._facets) { f.append(te, bd); } } for (let st of this.superTypes()) { st.append(te, bd); if(!st.isUnion()) { te.addSuperType(st); } } } finally { bd.typeMap().removeType(this); } } name(){ return this._name || super.name(); } setName(n:string){ return this._name = n; } isRecursionPoint():boolean{ return this._isRecursionPoint; } setIsRecursionPoint(val:boolean=true){ this._isRecursionPoint = val; } } export class BuiltInTypeEntry extends AbstractTypeEntry{ constructor(protected _original:IParsedType){ super(_original,[]); } possibleBuiltInTypes():string[]{ return [ this._original.name() ]; } isBuiltIn():boolean{ return true; } append(te:GeneralTypeEntry,bd:BranchingData):void{ te.addSuperType(this); } } export class UnionTypeEntry extends AbstractTypeEntry{ constructor( original:IParsedType, protected _options:TypeEntry[], protected _branchId:number){ super(original,[]); } isUnion():boolean{ return true; } branchId():number{ return this._branchId; } append(te:GeneralTypeEntry,bd:BranchingData):void{ let optionId = bd.branchingOption(this._branchId); let option = this._options[optionId]; if(!option.isBuiltIn()&&option.name()!=null){ te.setName(option.name()); } else{ te.setName(this.name()); } option.append(te,bd); } clone():TypeEntry{ throw new Error("Not implemented"); } possibleBuiltInTypes(occured:{[key:string]:boolean}={}):string[]{ let result:string[] = []; if(this.name()){ if(occured[this.name()]){ return []; } occured[this.name()] = true; } this._options.forEach(x=>result=result.concat(x.possibleBuiltInTypes(occured))); result = _.unique(result); return result; } options():TypeEntry[]{ return this._options; } } export class IntersectionTypeEntry extends AbstractTypeEntry{ constructor(original:IParsedType, protected options:TypeEntry[]){ super(original,[]); } isIntersection():boolean{ return true; } append(te:TypeEntry,bd:BranchingData):void{ throw new Error("not implemented"); } clone():TypeEntry{ throw new Error("Not implemented"); } possibleBuiltInTypes(occured:{[key:string]:boolean}={}):string[]{ if(this.name()){ if(occured[this.name()]){ return []; } occured[this.name()] = true; } let possibleTypes = this.options.map(x=>x.possibleBuiltInTypes(occured)); let result = possibleTypes[0]; for(let i = 1 ; i < possibleTypes.length ; i++){ result = _.intersection(result,possibleTypes[i]); } return result; } } function mergeMeta(to,from){ if(!from){ return; } else if(!to){ return from; } for(let key of Object.keys(from)){ if(!to.hasOwnProperty(key)){ to[key] = from[key]; } else if(key=="primitiveValuesMeta"){ for(let key1 of Object.keys(from.primitiveValuesMeta)){ if(!to.primitiveValuesMeta.hasOwnProperty(key1)) { to.primitiveValuesMeta[key1] = from.primitiveValuesMeta[key1]; } } } } } export class BasicTypeMap implements TypeMap{ private typeMapById:{[key:string]:AbstractTypeEntry} = {}; private typeMapByName:{[key:string]:AbstractTypeEntry} = {}; private propertiesMap:{[key:string]:PropertyEntry} = {}; addType(t:AbstractTypeEntry):void{ let n = t.id(); if(n){ this.typeMapById[n] = t; } if(t.name()){ this.typeMapByName[t.name()] = t; } } removeType(t:AbstractTypeEntry):void{ if(t.id()){ delete this.typeMapById[t.id()]; } if(t.name()){ delete this.typeMapByName[t.name()]; } } hasType(t:AbstractTypeEntry):boolean{ let n = t.id(); return this.typeMapById[n] !== undefined; } hasTypeByName(name:string):boolean{ return this.typeMapByName[name] !== undefined; } typeByName(name:string):AbstractTypeEntry{ return this.typeMapByName[name]; } addProperty(typeName:string,propName:string,prop:PropertyEntry){ const propKey = this.propKey(typeName, propName); this.propertiesMap[propKey] = prop; } property(typeName:string,propName:string):PropertyEntry{ const propKey = this.propKey(typeName, propName); return this.propertiesMap[propKey]; } private propKey(typeName:string, propName:string) { return `${typeName}/${propName}`; } } class BasicBranchingData implements BranchingData{ constructor( private arr:number[], private _expander:TypeExpander, private _typeMap:TypeMap = new BasicTypeMap()){} branchingOption(branchId:number){ if(branchId>this.arr.length-1){ throw new Error("Branch index exceeds total branches count"); } return this.arr[branchId]; } typeMap(){ return this._typeMap; } expander(){ return this._expander; } } class BasicBranchingRegistry implements BranchingRegistry{ constructor(protected _expander:TypeExpander){} private arr:number[] = []; expander(){ return this._expander; } nextBranchId(optionsCount:number):number{ let result = this.arr.length; this.arr.push(optionsCount); return result; } possibleBranches(typeMap:TypeMap):BranchingData[]{ let steps:number[] = []; let ranks:number[] = []; let count = 1; let rank = 1; let l = this.arr.length; for(let i = 0 ; i < l ; i++){ steps.push(count); ranks.push(rank); count *= this.arr[i]; rank *= this.arr[l-1-i]; } ranks = ranks.reverse(); let sequences:number[][]= []; for(let i = 0 ; i < count ; i++){ sequences.push([]); } // 2,3,3 // r l c ------------------ // 9 2 1 000000000111111111 // 3 3 2 000111222000111222 // 1 3 6 123123123123123123 for(let i = 0 ; i < l ; i++){ let ind = 0; let currentOptionsCount = this.arr[i]; for(let j0 = 0 ; j0 < steps[i] ; j0++ ){ for(let j1 = 0 ; j1 < currentOptionsCount ; j1++){ for(let j2 = 0 ; j2 < ranks[i] ; j2++){ sequences[ind++].push(j1); } } } } let result = sequences.map(x=>new BasicBranchingData(x,this.expander(),typeMap)); return result; } } export interface Options{ typeCollection?: tsInterfaces.IParsedTypeCollection; node?: hl.IHighLevelNode typeExpansionRecursionDepth?: number; serializeMetadata?: boolean; sourceMap?: boolean; isInsideTemplate?:boolean isAnnotationType?:boolean } export class TypeExpander { constructor(protected options:Options={}){ if(typeof(this.options.typeExpansionRecursionDepth) !== "number"){ this.options.typeExpansionRecursionDepth = -1; } if(typeof(this.options.serializeMetadata) !== "boolean"){ this.options.serializeMetadata = false; } } serializeType(t: IParsedType) { let he: TypeEntry = this.createHierarchyEntry(t, this.options.typeExpansionRecursionDepth); const expand = this.options.typeExpansionRecursionDepth >= 0; if (expand) { he = this.expandHierarchy(he, he.branchingRegistry()); } let result = this.dump(he, expand); return result; } protected createHierarchyEntry( t:IParsedType, typeExpansionRecursionDepth:number, occured:BasicTypeMap=new BasicTypeMap(), branchingRegistry?:BranchingRegistry):AbstractTypeEntry{ let isNewTree = false; if(!branchingRegistry){ isNewTree = true; branchingRegistry = new BasicBranchingRegistry(this); } let result = this.doCreateHierarchyEntry(t, typeExpansionRecursionDepth, occured, branchingRegistry); if(isNewTree){ result.setBranchingRegistry(branchingRegistry); } return result; } protected doCreateHierarchyEntry( t:IParsedType, typeExpansionRecursionDepth:number, occured:BasicTypeMap=new BasicTypeMap(), branchingRegistry:BranchingRegistry):AbstractTypeEntry{ if(t.isBuiltin()){ let result = occured.typeByName(t.name()); if(!result){ result = new BuiltInTypeEntry(t); occured.addType(result); } return result; } let d = 0; //unwrapping library chaining if(!t.name()&&t.isEmpty()&&t.superTypes().length==2&&t.superTypes().filter(x=>x.name()!="unknown").length==1){ t = _.find(t.superTypes(),x=>x.name()!="unknown"); } if(t.name() && occured.hasTypeByName(t.name())){ if(typeExpansionRecursionDepth<=0) { return occured.typeByName(t.name()); } else{ d = typeExpansionRecursionDepth; typeExpansionRecursionDepth--; } } if(this.options.isInsideTemplate&&t.superTypes().length==1){ let expr:string; const typeAttrVal = typeAttributeValue(t); if(typeAttrVal){ expr = typeAttrVal; } else if(t.superTypes()[0].isBuiltin()){ expr = t.name(); } else { expr = t.superTypes()[0].name(); } if(expr && expr.indexOf("<<")>=0){ let res = this.processExpression(expr,typeExpansionRecursionDepth,occured,branchingRegistry,t); if(res){ return res; } } } if(t.isUnion()&&t.superTypes().length==0){ let options = t.options(); let optionEntries:TypeEntry[] = []; for(let o of options){ optionEntries.push( this.createHierarchyEntry(o,typeExpansionRecursionDepth,occured,branchingRegistry)); } let branchId = branchingRegistry.nextBranchId(optionEntries.length); let unionSuperType = new UnionTypeEntry(t, optionEntries, branchId); return unionSuperType; } let result = new GeneralTypeEntry(t, [],null,[], [], t.name()); result.setDepth(d); if(t.name()!=null && !occured.hasTypeByName(t.name())) { occured.addType(result); } let superTypeEntries:TypeEntry[] = []; if(typeExpansionRecursionDepth==-1){ const allSuperTypes:IParsedType[] = t.superTypes(); let superTypes = allSuperTypes;//.filter(x=>!x.isUnion()); for (let st of superTypes) { let ste = this.createHierarchyEntry( st, typeExpansionRecursionDepth, occured, branchingRegistry); superTypeEntries.push(ste); } } else { const allSuperTypes:IParsedType[] = t.allSuperTypes(); let superTypes = allSuperTypes.filter(x=>!x.isUnion()); for (let st of superTypes) { if (st.isBuiltin()) { let ste = this.createHierarchyEntry( st, typeExpansionRecursionDepth, occured, branchingRegistry); superTypeEntries.push(ste); } } } let options = t.allOptions(); let properties = typeExpansionRecursionDepth>=0 ? t.properties() : t.declaredProperties(); if(typeExpansionRecursionDepth>=0&&options.length>1){ let optionEntries:TypeEntry[] = []; for(let o of options){ optionEntries.push(this.createHierarchyEntry( o,typeExpansionRecursionDepth,occured,branchingRegistry)); } let branchId = branchingRegistry.nextBranchId(optionEntries.length); let unionSuperType = new UnionTypeEntry(t, optionEntries, branchId); superTypeEntries.push(unionSuperType); } if(t.isArray()){ let ct = t.componentType(); if(ct) { if(isEmpty(ct)){ ct = ct.superTypes()[0]; } let componentTypeEntry = this.createHierarchyEntry( ct,typeExpansionRecursionDepth, occured); result.setComponentType(componentTypeEntry); } } let propertyEntries:PropertyEntry[] = []; if(properties.length>0){ for(let p of properties){ let pe = this.processPropertyHierarchy(p, typeExpansionRecursionDepth, t, occured, branchingRegistry); propertyEntries.push(pe); } } for(let st of superTypeEntries) { result.addSuperType(st); } for(let pe of propertyEntries){ result.addProperty(pe); } let definedFacets = typeExpansionRecursionDepth>=0 ? t.allDefinedFacets() : t.definedFacets(); if(definedFacets.length>0){ for(let p of definedFacets){ let fe = this.processPropertyHierarchy(p, typeExpansionRecursionDepth, t, occured, branchingRegistry,true); result.addFacet(fe); } } if(typeExpansionRecursionDepth==this.options.typeExpansionRecursionDepth) { occured.removeType(result); } return result; } protected processExpression( expression:string, typeExpansionRecursionDepth:number, occured:BasicTypeMap=new BasicTypeMap(), branchingRegistry:BranchingRegistry, original?:tsInterfaces.IParsedType):AbstractTypeEntry{ let gotExpression = referencePatcher.checkExpression(expression); if (!gotExpression) { return null; } let escapeData = referencePatcher.escapeTemplateParameters(expression); let str:string; if (escapeData.status == referencePatcher.ParametersEscapingStatus.OK) { str = escapeData.resultingString; gotExpression = referencePatcher.checkExpression(str); if (!gotExpression) { return null; } } else { return null; } let parsedExpression: any; try { parsedExpression = typeExpressions.parse(str); if (!parsedExpression) { return null; } let exprObj = this.expressionToObject(parsedExpression,escapeData,typeExpansionRecursionDepth,occured,branchingRegistry,original); return exprObj; } catch (exception) { return null; } } protected expressionToObject( expr:typeExpressions.BaseNode, escapeData:referencePatcher.EscapeData, typeExpansionRecursionDepth:number, occured:BasicTypeMap=new BasicTypeMap(), branchingRegistry:BranchingRegistry, original?:tsInterfaces.IParsedType):AbstractTypeEntry{ let result:AbstractTypeEntry; let arr = 0; if(expr.type=="name"){ let literal = <typeExpressions.Literal>expr; arr = literal.arr; let name = literal.value; if(escapeData.status==referencePatcher.ParametersEscapingStatus.OK){ let unescapeData = referencePatcher.unescapeTemplateParameters(name,escapeData.substitutions); if(unescapeData.status==referencePatcher.ParametersEscapingStatus.OK){ name = unescapeData.resultingString; } } let t = def.rt.builtInTypes().get(name); if(!t){ t = this.options.typeCollection.getType(name); } if(t){ result = this.createHierarchyEntry(t,typeExpansionRecursionDepth,occured,branchingRegistry); } else{ let UTE = new GeneralTypeEntry(def.rt.builtInTypes().get("unknown"),[],null,[],[],"unknown"); let orig = (arr === 0) ? original : null; result = new GeneralTypeEntry(orig,[UTE],null,[],[],name); result.setTypeAttributeValue(name); } } else if(expr.type=="union"){ let union = <typeExpressions.Union>expr; let components = jsonSerializerHL.toOptionsArray(union); let optionEntries:AbstractTypeEntry[] = []; for(var c of components){ if(c==null){ result = null; break; } let c1 = this.expressionToObject(c,escapeData,typeExpansionRecursionDepth,occured,branchingRegistry); optionEntries.push(c1); } let branchId = branchingRegistry.nextBranchId(optionEntries.length); result = new UnionTypeEntry(original, optionEntries, branchId); } else if(expr.type=="parens"){ let parens = <typeExpressions.Parens>expr; arr = parens.arr; result = this.expressionToObject(parens.expr,escapeData,typeExpansionRecursionDepth,occured,branchingRegistry,original); } if(result!=null && arr>0) { let ATE = new BuiltInTypeEntry(def.rt.builtInTypes().get("array")); while (arr-- > 0) { let orig = (arr === 0) ? original : null; result = new GeneralTypeEntry(null,[ATE],result,[],[],null); } } return result; } protected extractParserMetadata(pt: IParsedType) { let meta: any; let metaArr = pt.declaredFacets().filter(x => x.facetName() == "__METADATA__"); if (metaArr.length) { meta = metaArr[0].value(); } return meta; } protected processPropertyHierarchy( p:tsInterfaces.IPropertyInfo, typeExpansionRecursionDepth: number, t: IParsedType, occured:BasicTypeMap, branchingRegistry: BranchingRegistry, isFacet=false) { let pt = p.range(); let meta = this.extractParserMetadata(pt); let owner = p.declaredAt(); let d = typeExpansionRecursionDepth; if (owner.name() && (!t.name() || owner.name() != t.name()) && occured.hasTypeByName(owner.name())) { if (typeExpansionRecursionDepth <= 0) { const e = occured.property(owner.name(),p.name()); if(e) { return e; } d--; } } if (isEmpty(pt)) { pt = pt.superTypes()[0]; if(typeExpansionRecursionDepth>=0) { mergeMeta(meta, this.extractParserMetadata(pt)); } } let pe = new PropertyEntry(p, null, null, p.required(),isFacet,meta); if(owner.name()) { occured.addProperty(owner.name(), p.name(), pe); } let pte: TypeEntry = this.createHierarchyEntry( pt, d, occured, branchingRegistry); pe.setType(pte); return pe; } expandHierarchy(e:TypeEntry,reg:BranchingRegistry,typeMap?:TypeMap):TypeEntry{ if(!reg){ return e; } let entries:GeneralTypeEntry[] = []; for(let bd of reg.possibleBranches(typeMap)){ let branchEntry = new GeneralTypeEntry(null,[],null,[], [], null); e.append(branchEntry,bd); entries.push(branchEntry); } if(entries.length==1){ return entries[0]; } let result = new UnionTypeEntry(e.original(),entries,-1); return result; } protected appendSourceFromExtras(result: any, te: TypeEntry) { if(!this.options.sourceMap){ return; } if (!result.sourceMap) { let sourceMap:any; let src = te.original() && te.original().getExtra("SOURCE"); if (src) { let llSrc: ll.ILowLevelASTNode; if (hlImpl.LowLevelWrapperForTypeSystem.isInstance(src)) { llSrc = src.node(); } else if (hlImpl.ASTNodeImpl.isInstance(src)) { let schemaPath:string; if(te.isExternal()){ schemaPath = jsonSerializerHL.getSchemaPath(src); if(schemaPath){ result.schemaPath = schemaPath; sourceMap = { path: schemaPath }; } } if(!sourceMap){ sourceMap = { path: hlImpl.actualPath(src) }; } } else if (src.obj && src.obj.sourceMap) { sourceMap = src.obj.sourceMap; } if (llSrc) { if(llSrc.includePath()){ sourceMap = { path: llSrc.unit().resolve(llSrc.includePath()).path() }; } else { sourceMap = { path: llSrc.unit().path() } } } } if(sourceMap){ this.spreadSources(result,sourceMap); } } } spreadSources(result:any,src:any){ if(typeof result !== "object"){ return; } else if(!result.sourceMap) { result.sourceMap = src; } else{ return; } if(result.items){ result.items.forEach(x=>this.spreadSources(x,src)); } if(result.anyOf){ result.anyOf.forEach(x=>this.spreadSources(x,src)); } if(result.properties){ result.properties.forEach(x=>this.spreadSources(x,src)); } if(result.facets){ result.facets.forEach(x=>this.spreadSources(x,src)); } if(result.xml){ this.spreadSources(result.xml,src); } } protected dump(te: TypeEntry, expand: boolean): any { let result: any = {}; let name = te.name(); if (name) { result.name = name; if (te.isRecursionPoint()) { result = { type: ["any"] }; this.appendSourceFromExtras(result, te); return result; } } const superTypes = te.superTypes(); if (te.isBuiltIn()) { result = { type: [name], typePropertyKind: "TYPE_EXPRESSION" } } else if (te.isExternal()) { if (!expand && superTypes[0].name() && te.original().allSuperTypes().length > 3) { result.type = [superTypes[0].name()]; result.typePropertyKind = "TYPE_EXPRESSION"; } else { let sch = te.schema(); if (sch) { sch = sch.trim(); let resolved = resolveSchemaFragment(this.options.node,sch); if(resolved){ sch = resolved; } result.type = [sch]; if (te.schemaPath()) { result.schemaPath = te.schemaPath(); } var canBeJson = (sch[0] === "{" && sch[sch.length - 1] === "}"); var canBeXml = (sch[0] === "<" && sch[sch.length - 1] === ">"); if (canBeJson) { result.typePropertyKind = "JSON"; } else if (canBeXml) { result.typePropertyKind = "XML"; } else { result.typePropertyKind = "TYPE_EXPRESSION"; } } } } else if (te.isUnion()) { result.typePropertyKind = "TYPE_EXPRESSION"; let ute = <UnionTypeEntry>te; let options = ute.options(); if (options.length > 0) { result.type = ["union"]; let anyOf: any[] = []; result.anyOf = anyOf; for (let o of options) { if (!expand && o.name()) { anyOf.push(o.name()); } else { let dumpedOption = this.dump(o, expand); this.appendSourceFromExtras(dumpedOption, ute); if(this.options.isInsideTemplate) { if (dumpedOption.name == te.name() && dumpedOption.type) { let dot = dumpedOption.type; if (dot.length && dot[0].indexOf("<<") >= 0) { dumpedOption = dot[0]; } } else if(dumpedOption.name&&dumpedOption.name.indexOf("<<")>=0){ dumpedOption = dumpedOption.name; } } anyOf.push(dumpedOption); } } } } else { if (superTypes.length && (superTypes[0].name() || superTypes[0].isUnion())) { result.typePropertyKind = "TYPE_EXPRESSION"; } else { result.typePropertyKind = "INPLACE"; } let gte = <GeneralTypeEntry>te; let typeAttrVal:any; if(this.options.isInsideTemplate){ typeAttrVal = te.typeAttributeValue(); if(!typeAttrVal){ let supertypes = te.original()&&te.original().superTypes(); if(supertypes && supertypes.length==1 && supertypes[0].isUnknown()){ let stName = supertypes[0].name(); if(stName.indexOf("<<")>=0){ typeAttrVal = stName; } } } if(typeAttrVal && ! Array.isArray(typeAttrVal)){ typeAttrVal = [ typeAttrVal ]; } } if(typeAttrVal) { result.type = typeAttrVal; result.typePropertyKind = "TYPE_EXPRESSION"; } else if (expand) { let type = gte.possibleBuiltInTypes(); if (type.length > 0) { result.type = type; } } else { let type: any[] = []; for (let st of superTypes) { if (st.name()) { type.push(st.name()); } else { const dumped = this.dump(st, expand); dumped.name = "type"; const stDisplayName = st.displayName(); dumped.displayName = stDisplayName||"type"; if(!stDisplayName) { this.appendMeta(dumped, "displayName", "calculated"); } type.push(dumped); } } result.type = type; } let properties = gte.properties(); if (properties && properties.length > 0) { let props: any[] = []; result.properties = props; for (let p of properties) { const dumpedPropertyType = this.dumpProperty(p, gte, expand); props.push(dumpedPropertyType); } } let facets = gte.definedFacets(); if (facets && facets.length > 0) { let facetArr: any[] = []; result.facets = facetArr; for (let f of facets) { const dumpedFacetType = this.dumpProperty(f, gte, expand, true); facetArr.push(dumpedFacetType); } } let ct = gte.componentType(); if (ct) { let ctArr = [ct]; if(!expand && isEmpty(ct.original(),true)&&ct.superTypes().length>1){ ctArr = ct.superTypes(); } result.items = ctArr.map(x=> { if (!expand && x.name()) { return x.name(); //this.appendMeta(result.items[0], "displayName", "calculated"); //this.appendSourceFromExtras(result.items[0], gte); } else { let dumpedComponentType = this.dump(ct, expand); this.appendSourceFromExtras(dumpedComponentType, gte); if (!ct.isUnion() && !dumpedComponentType.name) { dumpedComponentType.name = "items"; dumpedComponentType.displayName = "items"; this.appendMeta(dumpedComponentType, "displayName", "calculated"); } if(this.options.isInsideTemplate) { if (dumpedComponentType.name == te.name() && dumpedComponentType.type) { let dot = dumpedComponentType.type; if (dot.length && dot[0].indexOf("<<") >= 0) { dumpedComponentType = dot[0]; } } else if(dumpedComponentType.name&&dumpedComponentType.name.indexOf("<<")>=0){ dumpedComponentType = dumpedComponentType.name; } } return dumpedComponentType; } }); } this.dumpFacets(te, result, expand); } let examples = te.examples(expand); if (examples.length > 0) { let simplified: any[] = []; let examplesArr: any[] = []; result.examples = examplesArr; result.simplifiedExamples = simplified; for (let e of examples) { this.processExample(e, simplified, examplesArr); } } let annotations = te.original() && te.original().annotations(); this.dumpAnnotations(annotations, result); this.dumpScalarsAnnotations(te, result, expand); this.dumpMeta(te, result, expand); this.appendSourceFromExtras(result, te); this.patchDisplayName(te,result); this.checkIfTypePropertyIsDefault(te, result); return result; } private dumpScalarsAnnotations(te, result,expand){ const sAnnotations = te.original()&&( expand ? te.original().scalarsAnnotations():te.original().declaredScalarsAnnotations()); if(sAnnotations){ const keys = Object.keys(sAnnotations); if(keys.length) { let sAObj: any = {}; result.scalarsAnnotations = sAObj; for (let pName of keys) { sAObj[pName] = sAnnotations[pName].map(x=>x.map(y=>{ return { name: y.name(), value: y.value() }; })); } } } } private processExample(e, simplified: any[], examplesArr: any[]) { let val; if (e.isJSONString() || e.isYAML()) { let asJSON = e.asJSON(); val = asJSON!=null ? asJSON : e.original(); } else { val = e.original(); } let needStringify = false; if (Array.isArray(val)) { for (let c of val) { if (Array.isArray(c) || (typeof val == "object")) { needStringify = true; break; } } } else if (typeof val == "object" && val != null) { needStringify = true; } let simpleValue = needStringify ? JSON.stringify(val) : val; simplified.push(simpleValue); let eObj: any = { strict: e.strict(), value: val }; if (e.name()) { eObj.name = e.name(); } if (e.displayName() != null) { eObj.displayName = e.displayName(); } if (e.description()) { eObj.description = e.description(); } let annotations = e.annotations(); this.dumpAnnotations(annotations, eObj); if(e.hasScalarAnnotations()){ let sAnnotations = e.scalarsAnnotations(); let resSAnnotations:any = {}; for(let fName of Object.keys(sAnnotations)){ if(sAnnotations[fName]){ resSAnnotations[fName] = [[]]; for(let aName of Object.keys(sAnnotations[fName])){ resSAnnotations[fName][0].push({ name:aName, value: sAnnotations[fName][aName].value() }); } } } if(Object.keys(resSAnnotations).length){ eObj.scalarsAnnotations = resSAnnotations; } } examplesArr.push(eObj); } protected checkIfTypePropertyIsDefault(te: TypeEntry, result: any) { if (te.isBuiltIn()) { return; } if (te.original() && te.original().isUnion()) { return; } if (!te.isUnknown()&&(te.original()&&!this.sourceHasKey(te, "type")&&!this.sourceHasKey(te, "schema"))) { let byDefault = false; if (!Array.isArray(result.type) || !result.type.length) { byDefault = true; } else { byDefault = result.type[0] != "array"; } if (byDefault) { this.appendMeta(result, "type", "insertedAsDefault"); } } else{ this.removeMeta(result, "type"); } } protected dumpProperty( p: PropertyEntry, gte: GeneralTypeEntry, expand: boolean, isFacet = false) { let dumpedPropertyType: any; const propType = p.type(); if (!expand && propType.name()) { dumpedPropertyType = { type: [propType.name()], displayName: p.name(), typePropertyKind: "TYPE_EXPRESSION" }; this.appendMeta(dumpedPropertyType, "displayName", "calculated"); } else { dumpedPropertyType = this.dump(propType, expand); if(this.options.isInsideTemplate){ if(dumpedPropertyType.name!=null && dumpedPropertyType.name.indexOf("<<")>=0){ dumpedPropertyType = { type: [ dumpedPropertyType.name ], typePropertyKind: "TYPE_EXPRESSION" }; } } if(dumpedPropertyType.__METADATA__){ dumpedPropertyType.__METADATA__ = JSON.parse( JSON.stringify(dumpedPropertyType.__METADATA__)); } if (dumpedPropertyType.displayName == null || propType.name()) { dumpedPropertyType.displayName = p.name(); this.appendMeta(dumpedPropertyType, "displayName", "calculated"); } } this.appendSourceFromExtras(dumpedPropertyType, p.source()||gte); dumpedPropertyType.name = p.name(); if (!isFacet) { dumpedPropertyType.required = p.required(); } // if (p.metadata()) { // //dumpedPropertyType.__METADATA__ = p.metadata(); // } //else if (!isFacet) { if (p.required()) { let processed = false; if(p.original()) { if (p.original().range().getExtra("HAS_FACETS")) { let hf = p.original().range().getExtra("HAS_FACETS"); if (hf.length && hf.indexOf("required") >= 0) { processed = true; } } if (!processed) { this.appendMeta(dumpedPropertyType, "required", "insertedAsDefault"); } } else{ if (propType.name() || propType.isBuiltIn()) { this.appendMeta(dumpedPropertyType, "required", "insertedAsDefault"); } else if (!this.sourceHasKey(propType, "required")) { this.appendMeta(dumpedPropertyType, "required", "insertedAsDefault"); } } } } let typeChecked = false; let pte = propType; if(propType.isBuiltIn()||(propType.original()&&propType.original().isBuiltin())){ if (p.original()) { let range = p.original().range(); if (!range.isBuiltin()) { pte = new GeneralTypeEntry(range, [], null, [], [], null); } } } if(expand || pte!=propType) { this.checkIfTypePropertyIsDefault(pte, dumpedPropertyType); } this.checkIfPropertyTypeIsCalculated(dumpedPropertyType, p, isFacet, expand); if(p.annotations() && p.annotations().length){ let scalarsAnnotations = dumpedPropertyType.scalarsAnnotations; if(!scalarsAnnotations){ scalarsAnnotations = {}; dumpedPropertyType.scalarsAnnotations =scalarsAnnotations; } scalarsAnnotations['required'] = [[]]; for(let a of p.annotations()){ scalarsAnnotations['required'][0].push({ name: a.name(), value: a.value() }); } } return dumpedPropertyType; } protected dumpAnnotations(annotations: IAnnotation[], obj: any) { if (annotations && annotations.length > 0) { let aArr: any[] = []; obj.annotations = aArr; annotations.forEach(x => { aArr.push({ name: x.name(), value: x.value() }) }) } }; protected dumpFacets(te: TypeEntry, result: any, expand: boolean) { let customFacets: ITypeFacet[]=[]; if (te.original()) { if (expand) { customFacets = te.original().allCustomFacets()||[]; } else { customFacets = te.original().customFacets()||[]; } let map:any = {}; te.original().allDefinedFacets().forEach(x=>map[x.name()]=true); customFacets = customFacets.filter(x=>map[x.facetName()]===true); } if(this.options.isInsideTemplate){ let parametrized:tsInterfaces.ITypeFacet[] = []; customFacets = customFacets.filter(x=>{ if(x.facetName().indexOf("<<")>=0){ parametrized.push(x); return false; } return true; }); for(let p of parametrized){ result[p.facetName()] = p.value(); } } if (customFacets && customFacets.length > 0) { let facetsObj: { name: string, value: any }[] = []; result.fixedFacets = facetsObj; customFacets.forEach(x => { try { let val = x.value(); if (typeof val == 'object') { JSON.stringify(val); } facetsObj.push({ name: x.facetName(), value: val }); } catch (e) { console.log('Error while dumping ' + x.facetName()); console.log(e); } }); } let builtInTypes = te.possibleBuiltInTypes({}); let propMap = propertiesForBuiltinTypes(builtInTypes); let facetsMap: { [key: string]: ITypeFacet[] } = {}; const facets = expand ? te.allFacets() : te.declaredFacets(); for (let f of facets) { if (f.kind() == tsInterfaces.MetaInformationKind.DiscriminatorValue) { if (!(<any>f).isStrict()) { continue; } } let fn = f.facetName(); if (propMap[fn]) { let fArr = facetsMap[fn]; if (!fArr) { fArr = []; facetsMap[fn] = fArr; } fArr.push(f); } } for (let fn of Object.keys(facetsMap)) { let fArr = facetsMap[fn]; let val: any; if (fArr.length == 1) { val = fArr[0].value(); } else { val = this.mergeFacetValues(fArr); } if (typeof val == "string" || typeof val == "number" || typeof val == "boolean") { if(fn=="allowedTargets"&&!Array.isArray(val)){ val = [ val ]; } else if(fn=="enum"){ if(!Array.isArray(val)){ val = [val]; } if(te.original()&&te.original().isString()){ val = val.map(x=>""+x); } } result[fn] = val; } } } protected mergeFacetValues(arr: ITypeFacet[]): any { if (arr.length == 0) { return null; } let c: IConstraint; for (let f of arr) { if (!c) { if (!f.isConstraint()) { return f.value(); } c = <IConstraint>f; continue; } if (!f.isConstraint()) { continue; } c = c.composeWith(<IConstraint>f); } if (!c) { return arr[0].value(); } return c.value(); } protected dumpMeta(te: TypeEntry, result: any, expand: boolean) { const meta = expand ? te.meta() : te.declaredFacets(); for (let m of meta) { let name = m.facetName(); if (MetaNamesProvider.getInstance().hasProperty(name)) { if (!result.hasOwnProperty(name)) { result[name] = m.value(); if(name=="allowedTargets"&&!Array.isArray(m.value())){ result[name] = [ m.value() ]; } else if(name=="enum"){ if(!Array.isArray(m.value())){ result[name] = [m.value()]; } if(te.original()&&te.original().isString()){ result[name] = result[name].map(x=>""+x); } } } } else if (name == "closed") { const val = m.value(); result["additionalProperties"] = val; } } } protected sourceHasKey(te: TypeEntry, key: string) { let src = te.original() && te.original().getExtra("SOURCE"); let result: boolean = null; if (src) { if (hlImpl.LowLevelWrapperForTypeSystem.isInstance(src)) { const childWithKey = src.childWithKey(key); result = childWithKey && childWithKey.value() != null; } else if (hlImpl.ASTNodeImpl.isInstance(src)) { const attr = src.attr(key); result = attr && attr.value() != null; } else if (src.obj) { result = src.obj[key] != null; } } return result; } protected appendMeta(obj:any,field:string,kind:string){ if(!this.options.serializeMetadata){ return; } let metaObj = obj.__METADATA__; if(!metaObj){ metaObj = {}; obj.__METADATA__ = metaObj; } let scalarsObj = metaObj.primitiveValuesMeta; if(!scalarsObj){ scalarsObj = {}; metaObj.primitiveValuesMeta = scalarsObj; } let fObj = scalarsObj[field]; if(!fObj){ fObj = {}; scalarsObj[field] = fObj; } fObj[kind] = true; } protected removeMeta(obj:any,field:string){ if(!this.options.serializeMetadata){ return; } let metaObj = obj.__METADATA__; if(!metaObj){ return; } let scalarsObj = metaObj.primitiveValuesMeta; if(!scalarsObj){ return; } let fObj = scalarsObj[field]; if(!fObj){ return; } delete scalarsObj[field]; if(Object.keys(metaObj.primitiveValuesMeta)){ return; } delete metaObj.primitiveValuesMeta; if(Object.keys(metaObj)){ return; } delete obj.__METADATA__; } private checkIfPropertyTypeIsCalculated( dumpedPropertyType: any, p: PropertyEntry, isFacet: boolean, expand: boolean) { if(!this.options.serializeMetadata){ return; } let domSrc = p.original() && p.original().declaredAt().getExtra("SOURCE"); if (domSrc) { let llDomSrc: ll.ILowLevelASTNode; if (hlImpl.ASTNodeImpl.isInstance(domSrc)) { llDomSrc = domSrc.lowLevel(); } else if (hlImpl.LowLevelWrapperForTypeSystem.isInstance(domSrc)) { llDomSrc = domSrc.node(); } if (llDomSrc) { let propsSrc = _.find(llDomSrc.children(), x => x.key() == (isFacet ? "facets" : "properties")); if (propsSrc) { let pSrc = _.find(propsSrc.children(), x => x.key() == p.name()); if (pSrc) { if (pSrc.resolvedValueKind() == yaml.Kind.SCALAR) { if (!expand || def.rt.builtInTypes().get(pSrc.value())) { this.removeMeta(dumpedPropertyType, "type"); } } else if (pSrc.resolvedValueKind() == yaml.Kind.SEQ) { const typeNodes = pSrc.children(); if (typeNodes.length > 1) { this.removeMeta(dumpedPropertyType, "type"); } else if (typeNodes.length == 1 && typeNodes[0].resolvedValueKind() == yaml.Kind.SCALAR) { let tNode = typeNodes[0]; if (!expand || def.rt.builtInTypes().get(tNode.value())) { this.removeMeta(dumpedPropertyType, "type"); } } } else { let typeChild = _.find(pSrc.children(), x => x.key() == "type"); if(!typeChild){ typeChild = _.find(pSrc.children(), x => x.key() == "schema"); } if (typeChild) { if (typeChild.resolvedValueKind() == yaml.Kind.SEQ) { const typeNodes = typeChild.children(); if (typeNodes.length > 1) { this.removeMeta(dumpedPropertyType, "type"); } else if (typeNodes.length == 1 && typeNodes[0].resolvedValueKind() == yaml.Kind.SCALAR) { let tNode = typeNodes[0]; if (!expand || def.rt.builtInTypes().get(tNode.value())) { this.removeMeta(dumpedPropertyType, "type"); } } } else if (typeChild.resolvedValueKind() == yaml.Kind.SCALAR) { if (!expand || def.rt.builtInTypes().get(typeChild.value())) { this.removeMeta(dumpedPropertyType, "type"); } } } } } } } } } patchDisplayName(te:TypeEntry,result:any){ if (!result.displayName && result.name) { result.displayName = result.name; let llSrc: ll.ILowLevelASTNode; let src = te.original() && te.original().getExtra("SOURCE"); if (src) { if (hlImpl.LowLevelWrapperForTypeSystem.isInstance(src)) { llSrc = src.node(); } else if (hlImpl.ASTNodeImpl.isInstance(src)) { let schemaPath:string; llSrc = src.lowLevel(); } } if (llSrc) { jsonSerializerHL.patchDisplayName(result,llSrc); } else{ result.displayName = result.name; } this.appendMeta(result, "displayName", "calculated"); } if(result.hasOwnProperty("displayName")&&result.displayName != null){ result.displayName = "" + result.displayName; } } } function propertiesForBuiltinTypes(builtInTypes: string[]):{[key:string]:boolean} { let types: def.ITypeDefinition[] = []; for (let tn of builtInTypes) { let t = typeSystem.builtInTypes().get(tn); if (t) { let ts = builder.mapType(t); ts.forEach(x => types.push(x)); } } let propMap: any = {}; types.forEach(x => { x.properties().forEach(p => propMap[p.nameId()] = true); }); return propMap; } class MetaNamesProvider{ private static instance:MetaNamesProvider = new MetaNamesProvider(); public static getInstance():MetaNamesProvider{ if(!MetaNamesProvider.instance){ MetaNamesProvider.instance = new MetaNamesProvider(); } return MetaNamesProvider.instance; } constructor(){ this.init(); } private map:{[key:string]:boolean} = {}; private init(){ let types = [ def.getUniverse("RAML10").type(def.universesInfo.Universe10.TypeDeclaration.name), def.getUniverse("RAML10").type(def.universesInfo.Universe10.StringTypeDeclaration.name), def.getUniverse("RAML10").type(def.universesInfo.Universe10.FileTypeDeclaration.name) ]; for(let t of types) { for (let p of t.properties()) { if (p.nameId() != def.universesInfo.Universe10.TypeDeclaration.properties.schema.name) { this.map[p.nameId()] = true; } } } this.map["sourceMap"] = true; this.map["__METADATA__"] = true; } public hasProperty(n:string):boolean{ return this.map.hasOwnProperty(n); } } const filterOut = [ "typePropertyKind","sourceMap", "required","__METADATA__", "notScalar" ]; function isEmpty(t:tsInterfaces.IParsedType,ignoreSupertypesCount=false):boolean{ if(t.isUnion()||t.isBuiltin()||t.name()){ return false; } if(!ignoreSupertypesCount&&t.superTypes().length!=1){ return false; } let meta = t.declaredFacets().filter(x=>{ const fn = x.facetName(); if(filterOut.indexOf(fn)>=0){ return false; } if(fn=="discriminatorValue"){ const strict = x['isStrict']; return (typeof strict != "function") || strict.call(x); } else if(fn=="__METADATA__"){ const meta = x.value(); let pMeta = meta.primitiveValuesMeta; if(!pMeta && Object.keys(meta).length==0){ return false; } else if(pMeta){ if(!Object.keys(pMeta).filter(y=>y!="displayName"&&y!="required").length){ return false; } return true; } return true; } return true; }); return meta.length==0; } function typeAttributeValue(t:tsInterfaces.IParsedType):any{ if(!t){ return null; } let tAttr = _.find(t.declaredFacets(),x=>x.kind()==tsInterfaces.MetaInformationKind.TypeAttributeValue); if(tAttr){ return tAttr.value(); } return null; } function resolveSchemaFragment(node:any,value:string):string{ if(!node || !hlImpl.ASTNodeImpl.isInstance(node)){ return null; } let n:hl.IParseResult = node.attr("type")||node.attr("schema") || node; return hlImpl.resolveSchemaFragment(n,value); }
the_stack
export function addExtensionsToContext(gl: WebGLRenderingContext); export function bindTransformFeedbackInfo(gl: WebGLRenderingContext, transformFeedbackInfo?: ProgramInfo | { [key: string]: AttribInfo }): void; export function createTransformFeedback(gl: WebGLRenderingContext, programInfo: ProgramInfo, bufferInfo?: BufferInfo | { [key: string]: AttribInfo }): WebGLObject; export function createTransformFeedbackInfo(gl: WebGLRenderingContext, program: WebGLProgram): { [key: string]: TransformFeedbackInfo }; export function getContext(canvas: HTMLCanvasElement, attribs?: WebGLContextAttributes): WebGLRenderingContext; export function getWebGLContext(canvas: HTMLCanvasElement, attribs?: WebGLContextAttributes): WebGLRenderingContext; export function isWebGL1(gl: WebGLRenderingContext): boolean; export function isWebGL2(gl: WebGLRenderingContext): boolean; export function resizeCanvasToDisplaySize(canvas: HTMLCanvasElement, multiplier?: number): boolean; export function setDefaults(newDefaults: Defaults): void; export interface Arrays { [key: string]: number[] | ArrayBuffer | FullArraySpec } export type ArraySpec = number[] | ArrayBuffer | FullArraySpec; export interface AttachmentOptions extends TextureOptions { attach?: number; format?: number; type?: number; target?: number; level?: number; attachment?: WebGLObject; } export interface AttribInfo { numComponents?: number; size?: number; type?: number; normalize?: boolean; offset?: number; stride?: number; buffer?: WebGLBuffer; drawType?: number; } export interface BlockSpec { index: number; size: number; uniformIndices: number[]; usedByVertexShader: boolean; usedByFragmentShader: boolean; used: boolean; } export interface BufferInfo { numElements: number; elementType?: number; indices: WebGLBuffer; attribs: { [key: string]: AttribInfo }; } export type CubemapReadyCallback = (err: any, tex: WebGLTexture, imgs: HTMLImageElement[]) => void; export interface Defaults { attribPrefix?: string; textureColor?: number[]; crossOrigin?: string; enableVertexArrayObjects?: boolean; } export interface DrawObject { active?: boolean; type?: number; programInfo: ProgramInfo; bufferInfo?: BufferInfo; vertexArrayInfo?: VertexArrayInfo; uniforms: { [key: string]: any }; offset?: number; count?: number; } export type ErrorCallback = (msg: string, lineOffset?: number) => void; export interface FramebufferInfo { framebuffer: WebGLFramebuffer; attachments: WebGLObject[]; } export interface FullArraySpec { data: number | number[] | ArrayBuffer; numComponents?: number; type?: new (...args: any[]) => ArrayBuffer; size?: number; normalize?: boolean; stride?: number; offset?: number; name?: string; attribName?: string; } export interface ProgramInfo { program: WebGLProgram; uniformSetters: { [key: string]: (...para: any[]) => void }, attribSetters: { [key: string]: (...para: any[]) => void }, transformFeedbackInfo: { [key: string]: TransformFeedbackInfo } } export interface ProgramOptions { errorCallback?: (error: any) => void; attribLocations?: { [key: string]: number }; transformFeedbackVaryings?: BufferInfo | { [key: string]: AttribInfo } | string[]; transformFeedbackMode?: number; } export type FullTextureSrc = number[] | ArrayBuffer | HTMLCanvasElement | HTMLImageElement | HTMLVideoElement | string | string[] | TextureFunc; export type TextureFunc = (gl: WebGLRenderingContext, options: TextureOptions) => FullTextureSrc; export interface TextureOptions { target?: number; width?: number; height?: number; depth?: number; min?: number; mag?: number; minMag?: number; internalFormat?: number; format?: number; type?: number; wrap?: number; wrapS?: number; wrapT?: number; wrapR?: number; minLod?: number; maxLod?: number; baseLevel?: number; maxLevel?: number; unpackAlignment?: number; premultiplyAlpha?: number; flipY?: number; colorspaceConversion?: number; color?: number[] | ArrayBuffer; auto?: boolean; cubeFaceOrder?: number[]; src?: FullTextureSrc; crossOrigin?: string; } export type TextureReadyCallback = (err: any, texture: WebGLTexture, source: TextureSrc) => void; export type TextureSrc = HTMLImageElement | HTMLImageElement[]; export type TexturesReadyCallback = (err: any, textures: { [key: string]: WebGLTexture }, sources: { [key: string]: TextureSrc }) => void; export type ThreeDReadyCallback = (err: any, tex: WebGLTexture, imgs: HTMLImageElement[]) => void; export interface TransformFeedbackInfo { index: number; type: number; size: number; } export interface UniformBlockInfo { name: string; array: ArrayBuffer; asFloat: Float32Array; buffer: WebGLBuffer; offset?: number; uniforms: { [key: string]: ArrayBufferView } } export interface UniformBlockSpec { blockSpecs: { [key: string]: BlockSpec }; uniformData: UniformData[]; } export interface UniformData { type: number; size: number; blockNdx: number; offset: number; } export interface VertexArrayInfo { numElements: number; elementType: number; vertexArrayObject?: WebGLObject; } export function createBufferFromTypedArray(gl: WebGLRenderingContext, typedArray: ArrayBuffer | ArrayBufferView | WebGLBuffer, type?: number, drawType?: number): WebGLBuffer; // attributes module export function createAttribsFromArrays(gl: WebGLRenderingContext, arrays: Arrays): { [name: string]: AttribInfo }; export function createBufferFromArray(gl: WebGLRenderingContext, array: ArraySpec, arrayName: string): WebGLBuffer; export function createBufferFromTypedArray(gl: WebGLRenderingContext, typedArray: ArrayBuffer | ArrayBufferView | WebGLBuffer, type?: number, drawType?: number): WebGLBuffer; export function createBufferInfoFromArrays(gl: WebGLRenderingContext, arrays: Arrays): BufferInfo; export function createBuffersFromArrays(gl: WebGLRenderingContext, arrays: Arrays): { [name: string]: WebGLBuffer }; export function setAttribInfoBufferFromArray(gl: WebGLRenderingContext, attribInfo: AttribInfo, array: ArraySpec, offset?: number): void; export function setAttributePrefix(prefix: string): void; // draw module export function drawBufferInfo(gl: WebGLRenderingContext, bufferInfo: BufferInfo | VertexArrayInfo, type?: number, count?: number, offset?: number): void; export function drawObjectList(objectsToDraw: DrawObject[]): void; // framebuffers module export function bindFramebufferInfo(gl: WebGLRenderingContext, framewbufferInfo?: FramebufferInfo, target?: number): void; export function createFramebufferInfo(gl: WebGLRenderingContext, attachments?: AttachmentOptions[], widt?: number, height?: number): FramebufferInfo; export function resizeFramebufferInfo(gl: WebGLRenderingContext, framebufferInfo: FramebufferInfo, attachments?: AttachmentOptions[], width?: number, height?: number): void; export type Mat4 = number[] | Float32Array; export type Vec3 = number[] | Float32Array; export namespace m4 { export function axisRotate(m: Mat4, axis: Vec3, angleInRadians: number, dst?: Mat4): Mat4; export function axisRotation(axis: Vec3, angleInRadians: number, dst?: Mat4): Mat4; export function copy(m: Mat4, dst?: Mat4): Mat4; export function frustum(left: number, right: number, bottom: number, top: number, near: number, far: number, dst?: Mat4): Mat4; export function getAxis(m: Mat4, axis: number): Vec3 export function getTranslation(m: Mat4, dst?: Vec3): Vec3 export function identity(dst?: Mat4): Mat4; export function inverse(m: Mat4, dst?: Mat4): Mat4; export function lookAt(eye: Vec3, target: Vec3, up: Vec3, dst?: Mat4): Mat4; export function multiply(a: Mat4, b: Mat4, dst?: Mat4): Mat4; export function negate(m: Mat4, dst?: Mat4): Mat4; export function ortho(left: number, right: number, top: number, bottom: number, near: number, far: number, dst?: Mat4): Mat4; export function perspective(fieldOfViewYInRadians: number, aspect: number, zNear: number, zFar: number, dst?: Mat4): Mat4; export function rotateX(m: Mat4, angleInRadians: number, dst?: Mat4): Mat4; export function rotateY(m: Mat4, angleInRadians: number, dst?: Mat4): Mat4; export function rotateZ(m: Mat4, angleInRadians: number, dst?: Mat4): Mat4; export function rotationX(angleInRadians: number, dst?: Mat4): Mat4; export function rotationY(angleInRadians: number, dst?: Mat4): Mat4; export function rotationZ(angleInRadians: number, dst?: Mat4): Mat4; export function scale(m: Mat4, v: Vec3, dst?: Mat4): Mat4; export function scaling(v: Vec3, dst?: Mat4): Mat4; export function setAxis(v: Vec3, axis: number, dst?: Mat4): Mat4; export function setTranslation(a: Mat4, v: Vec3, dst?: Mat4): Mat4; export function transformDirection(m: Mat4, v: Vec3, dst?: Vec3): Vec3; export function transformNormal(m: Mat4, v: Vec3, dst?: Vec3): Vec3; export function transformPoint(m: Mat4, v: Vec3, dst?: Vec3): Vec3; export function translate(m: Mat4, v: Vec3, dst?: Mat4): Mat4; export function translation(v: Vec3, dst?: Mat4): Mat4; export function transpose(m: Mat4, dst?: Mat4): Mat4; } export type TypedArray = Uint16Array | Uint8Array | Uint32Array | Int32Array | Int16Array | Int8Array | Float32Array | Float64Array; export namespace primitives { export interface RandomVerticesOptions { rand: RandomColorFunc; vertsPerColor: number; } export interface AugmentedTypedArray extends ArrayLike<number> { push(value: number[] | number, ...values: number[]): void; buffer: ArrayBuffer; } export type RandomColorFunc = (ndx: number, channel: number) => number; export type TypedArrayConstructor = Uint8ArrayConstructor | Uint16ArrayConstructor | Uint32ArrayConstructor | Int8ArrayConstructor | Int16ArrayConstructor | Int32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor; export function concatVertices(arrays: Arrays): Arrays; export function create3DFBufferInfo(gl: WebGLRenderingContext): BufferInfo; export function create3DFBuffers(gl: WebGLRenderingContext): { [key: string]: WebGLBuffer }; export function create3DFVertices(): { [key: string]: TypedArray }; export function createAugmentedTypedArray(numComponents: number, numElements: number, opt_type?: TypedArrayConstructor): AugmentedTypedArray; export function createCresentBufferInfo(gl: WebGLRenderingContext, verticalRadius: number, outerRadius: number, innerRadius: number, thickness: number, subdivisionsDown: number, subdivisionsThick: number, startOffset?: number, endOffset?: number): BufferInfo; export function createCresentBuffers(gl: WebGLRenderingContext, verticalRadius: number, outerRadius: number, innerRadius: number, thickness: number, subdivisionsDown: number, subdivisionsThick: number, startOffset?: number, endOffset?: number): { [key: string]: WebGLBuffer }; export function createCresentVertices(verticalRadius: number, outerRadius: number, innerRadius: number, thickness: number, subdivisionsDown: number, subdivisionsThick: number, startOffset?: number, endOffset?: number): { [key: string]: TypedArray }; export function createCubeBufferInfo(gl: WebGLRenderingContext, size?: number): BufferInfo; export function createCubeBuffers(gl: WebGLRenderingContext, size?: number): { [key: string]: WebGLBuffer }; export function createCubeVertices(size?: number): { [key: string]: TypedArray }; export function createCylinderBufferInfo(gl: WebGLRenderingContext, radius: number, height: number, radialSubdivisions: number, verticalSubdivisions: number, topCap?: boolean, bottomCap?: boolean): { [key: string]: BufferInfo }; export function createCylinderBuffers(gl: WebGLRenderingContext, radius: number, height: number, radialSubdivisions: number, verticalSubdivisions: number, topCap?: boolean, bottomCap?: boolean): { [key: string]: WebGLBuffer }; export function createCylinderVertices(radius: number, height: number, radialSubdivisions: number, verticalSubdivisions: number, topCap: boolean, bottomCap: boolean): { [key: string]: TypedArray }; export function createDiscBufferInfo(gl: WebGLRenderingContext, radius: number, divisions: number, stacks?: number, innerRadius?: number, stackPower?: number): BufferInfo; export function createDiscBuffers(gl: WebGLRenderingContext, radius: number, divisions: number, stacks?: number, innerRadius?: number, stackPower?: number): { [key: string]: WebGLBuffer }; export function createDiscVertices(radius: number, divisions: number, stacks?: number, innerRadius?: number, stackPower?: number): { [key: string]: TypedArray }; export function createPlaneBufferInfo(gl: WebGLRenderingContext, width?: number, depth?: number, subdivisionsWidth?: number, subdivisionsDepth?: number, matrix?: number): BufferInfo; export function createPlaneBuffers(gl: WebGLRenderingContext, width?: number, depth?: number, subdivisionsWidth?: number, subdivisionsDepth?: number, matrix?: Mat4): { [key: string]: WebGLBuffer }; export function createPlaneVertices(width?: number, depth?: number, subdivisionsWidth?: number, subdivisionsDepth?: number, matrix?: number): { [key: string]: TypedArray }; export function createSphereBufferInfo(gl: WebGLRenderingContext, radius: number, subdivisionsAxis: number, subdivisionsHeight: number, opt_startLatitudeInRadians?: number, opt_endLatitudeInRadians?: number, opt_startLongitudeInRadians?: number, opt_endLongitudeInRadians?: number): BufferInfo; export function createSphereBuffers(gl: WebGLRenderingContext, radius: number, subdivisionsAxis: number, subdivisionsHeight: number, opt_startLatitudeInRadians?: number, opt_endLatitudeInRadians?: number, opt_startLongitudeInRadians?: number, opt_endLongitudeInRadians?: number): { [key: string]: WebGLBuffer }; export function createSphereVertices(radius: number, subdivisionsAxis: number, subdivisionsHeight: number, opt_startLatitudeInRadians?: number, opt_endLatitudeInRadians?: number, opt_startLongitudeInRadians?: number, opt_endLongitudeInRadians?: number): { [key: string]: TypedArray }; export function createTorusBufferInfo(gl: WebGLRenderingContext, radius: number, thickness: number, radialSubdivisions: number, bodySubdivisions: number, startAngle?: number, endAngle?: number): BufferInfo; export function createTorusBuffers(gl: WebGLRenderingContext, radius: number, thickness: number, radialSubdivisions: number, bodySubdivisions: number, startAngle?: number, endAngle?: number): { [key: string]: WebGLBuffer }; export function createTorusVertices(radius: number, thickness: number, radialSubdivisions: number, bodySubdivisions: number, startAngle?: number, endAngle?: number): { [key: string]: TypedArray }; export function createTruncatedConeBufferInfo(gl: WebGLRenderingContext, bottomRadius: number, topRadius: number, height: number, radialSubdivisions: number, verticalSubdivisions: number, opt_topCapopt?: boolean, opt_bottomCap?: boolean): BufferInfo; export function createTruncatedConeBuffers(gl: WebGLRenderingContext, bottomRadius: number, topRadius: number, height: number, radialSubdivisions: number, verticalSubdivisions: number, opt_topCap?: boolean, opt_bottomCap?: boolean): { [key: string]: WebGLBuffer }; export function createTruncatedConeVertices(bottomRadius: number, topRadius: number, height: number, radialSubdivisions: number, verticalSubdivisions: number, opt_topCap?: boolean, opt_bottomCap?: boolean): { [key: string]: TypedArray }; export function createXYQuadBufferInfo(gl: WebGLRenderingContext, size?: number, xOffset?: number, yOffset?: number): { [key: string]: WebGLBuffer }; export function createXYQuadBuffers(gl: WebGLRenderingContext, size?: number, xOffset?: number, yOffset?: number): BufferInfo; export function createXYQuadVertices(size?: number, xOffset?: number, yOffset?: number): any; export function deindexVertices(vertices: { [key: string]: TypedArray }): { [key: string]: TypedArray }; export function duplicateVertices(arrays: Arrays): Arrays; export function flattenNormals(vertices: { [key: string]: TypedArray }): { [key: string]: TypedArray }; export function makeRandomVertexColors(vertices: { [key: string]: AugmentedTypedArray }, options?: AugmentedTypedArray): { [key: string]: AugmentedTypedArray }; export function reorientDirections(array: number[] | TypedArray, matrix: Mat4): number[] | TypedArray; export function reorientNormals(array: number[] | TypedArray, matrix: Mat4): number[] | TypedArray; export function reorientPositions(array: number[] | TypedArray, matrix: Mat4): number[] | TypedArray; export function reorientVertices(arrays: { [key: string]: number[] | TypedArray }, matrix: Mat4): { [key: string]: number[] | TypedArray }; } // Not sure how to type this properly. type WebGL2RenderingContext = WebGLRenderingContext; // programs module export function bindUniformBlock(gl: WebGL2RenderingContext, programInfo: ProgramInfo | UniformBlockSpec, uniformBlockInfo: UniformBlockInfo): boolean; export function createAttributeSetters(program: WebGLProgram): {[key:string]: (attr: any) => void}; export function createProgram(gl: WebGLRenderingContext, shaders: [WebGLShader, WebGLShader] | [string, string], options?: ProgramOptions): WebGLProgram; export function createProgramFromScripts(gl: WebGLRenderingContext, shaderScriptIds: [string, string], options?: ProgramOptions): WebGLProgram; export function createProgramFromSources(gl: WebGLRenderingContext, shaderSources: [string, string], options?: ProgramOptions): WebGLProgram; export function createProgramInfo(gl: WebGLRenderingContext, shaderSources: [string, string], options?: ProgramOptions): ProgramInfo; export function createProgramInfoFromProgram(gl: WebGLRenderingContext, program: WebGLProgram): ProgramInfo; export function createUniformBlockInfo(gl: WebGL2RenderingContext, programInfo: ProgramInfo, blockName: string): UniformBlockInfo; export function createUniformBlockInfoFromProgram(gl: WebGL2RenderingContext, program: WebGLProgram, blockName: string): UniformBlockInfo; export function createUniformBlockSpecFromProgram(gl: WebGL2RenderingContext, program: WebGLProgram): UniformBlockSpec; export function createUniformSetters(program: WebGLProgram): {[key:string]: (attr: any) => void}; /** @deprecated */ export function setAttributes(setters: {[key:string]: (attr: any) => void}, buffers: {[key: string]: AttribInfo}); export function setBlockUniforms(uniformBlockInfo: UniformBlockInfo, values: { [key: string]: number[] | ArrayBuffer | number }): void; export function setBuffersAndAttributes(gl: WebGLRenderingContext, setters: ProgramInfo | { [key: string]: (...params: any[]) => void }, buffers: BufferInfo | VertexArrayInfo): void; export function setUniformBlock(gl: WebGL2RenderingContext, programInfo: ProgramInfo | UniformBlockSpec, uniformBlockInfo: UniformBlockInfo): void; export function setUniforms(setters: ProgramInfo | { [key: string]: (...params: any[]) => void }, values: { [key: string]: any }): void; // Not sure how to type this properly. type WebGLSampler = any; // textures module export function createTexture(gl: WebGLRenderingContext, options?: TextureOptions, callback?: TextureReadyCallback): WebGLTexture; export function createTextures(gl: WebGLRenderingContext, options?: { [key: string]: TextureOptions }, callback?: TexturesReadyCallback): { [key: string]: WebGLTexture }; export function getBytesPerElementForInternalFormat(internalFormat: number, type: number): number; export function getNumComponentsForFormat(format: number): number; export function loadCubemapFromUrls(gl: WebGLRenderingContext, tex: WebGLTexture, options: TextureOptions, callback?: TextureReadyCallback); export function loadSlicesFromUrls(gl: WebGLRenderingContext, tex: WebGLTexture, options: TextureOptions, callback?: TextureReadyCallback); export function loadTextureFromUrl(gl: WebGLRenderingContext, tex: WebGLTexture, options?: TextureOptions, callback?: TextureReadyCallback): HTMLImageElement; export function resizeTexture(gl: WebGLRenderingContext, tex: WebGLTexture, options: TextureOptions, width?: number, height?: number): void; export function setDefaultTextureColor(color: [number, number, number, number]); export function setEmptyTexture(gl: WebGLRenderingContext, tex: WebGLTexture, options: TextureOptions); export function setSamplerParameters(gl: WebGLRenderingContext, sampler: WebGLSampler, options: TextureOptions); export function setTextureFilteringForSize(gl: WebGLRenderingContext, tex: WebGLTexture, options?:TextureOptions, width?: number, height?: number, internalFormat?: number, type?: number); export function setTextureFromArray(gl: WebGLRenderingContext, tex: WebGLTexture, src: number[] | ArrayBuffer, options?: TextureOptions): void; export function setTextureFromElement(gl: WebGLRenderingContext, tex: WebGLTexture, element: HTMLElement, options?: TextureOptions); export function setTextureParameters(gl: WebGLRenderingContext, tex: WebGLTexture, options: TextureOptions); export function setTextureTo1PixelColor(gl: WebGLRenderingContext, tex: WebGLTexture, options?: TextureOptions); type TypedArrayConstructor = Int8ArrayConstructor | Uint8ArrayConstructor | Uint16ArrayConstructor | Int32ArrayConstructor | Uint32ArrayConstructor | Float32ArrayConstructor | Float64ArrayConstructor; // typedArray module export function getGLTypeForTypedArray(typedArray: ArrayBuffer | ArrayBufferView): number; export function getGLTypeForTypedArrayType(typedArrayType: TypedArrayConstructor): number; export function getTypedArrayTypeForGLType(type: number): TypedArrayConstructor; export namespace v3 { export function add(a: Vec3, b: Vec3, dest?: Vec3): Vec3; export function copy(v: Vec3): Vec3; export function create(): Vec3; export function cross(a: Vec3, b: Vec3, dest?: Vec3): Vec3; export function distance(a: Vec3, b: Vec3): number; export function distanceSq(a: Vec3, b: Vec3): number; export function divide(a: Vec3, b: Vec3, dest?: Vec3): Vec3; export function divScalar(v: Vec3, k: number, dest?: Vec3): Vec3; export function dot(a: Vec3, b: Vec3): number; export function length(v: Vec3): number; export function lengthSq(v: Vec3): number; export function lerp(a: Vec3, b: Vec3, t: number, dest?: Vec3): Vec3; export function mulScalar(v: Vec3, k: number, dest?: Vec3): Vec3; export function multiply(a: Vec3, b: Vec3, dest?: Vec3): Vec3; export function negate(v: Vec3, dest?: Vec3): Vec3; export function normalize(v: Vec3, dest?: Vec3): Vec3; export function subtract(a: Vec3, b: Vec3, dest?: Vec3): Vec3; export function setDefaultType(ctor: ArrayConstructor | TypedArrayConstructor): ArrayConstructor | TypedArrayConstructor; } // vertexArrays module export function createVAOAndSetAttributes(gl: WebGLRenderingContext, setters: {[key: string]: (value: any) => void}, attribs: {[key: string]: AttribInfo}, indices?: WebGLBuffer); export function createVAOFromBufferInfo(gl: WebGLRenderingContext, programInfo: {[key: string]: (value: any) => void} | ProgramInfo, bufferInfo: BufferInfo, indices?: WebGLBuffer); export function createVertexArrayInfo(gl: WebGLRenderingContext, programInfo: ProgramInfo | Array<ProgramInfo>, bufferInfo: BufferInfo);
the_stack
import { AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, EventEmitter, HostBinding, HostListener, Input, OnDestroy, Output, ViewChild, ViewEncapsulation, } from "@angular/core"; import { SecureUtils } from "@batch-flask/utils"; import * as elementResizeDetectorMaker from "element-resize-detector"; import { ScrollableService } from "./scrollable.service"; enum Orientation { Horizontal, Vertical, } @Component({ encapsulation: ViewEncapsulation.None, selector: "bl-scrollable", templateUrl: "scrollable.html", changeDetection: ChangeDetectionStrategy.OnPush, }) export class ScrollableComponent implements OnDestroy, AfterViewInit { public orientations = Orientation; public dragOffset = { [Orientation.Horizontal]: 0, [Orientation.Vertical]: 0 }; /** * If the content is long enough to need a scrollbar */ public isScrollbarNeeded = { [Orientation.Horizontal]: true, [Orientation.Vertical]: true }; /** * If the scrollbar should be displayed */ public scrollbarVisible = { [Orientation.Horizontal]: false, [Orientation.Vertical]: false }; /** * If we are currently dragging the scrollbar */ public dragging = false; /** * Margin at which the scrolledToBottom will be triggered. * If 0 the content needs to be scroll all the way to the bottom * otherwise at x pixel from the bottom it will start triggering. */ @Input() public scrollMargin: number = 0; @Output() public scrollBottom = new EventEmitter<number>(); @ViewChild("scrollable", { static: false }) public scrollable; @ViewChild("trackY", { static: false }) public trackY; @ViewChild("scrollbarY", { static: false }) public scrollbarY; @ViewChild("trackX", { static: false }) public trackX; @ViewChild("scrollbarX", { static: false }) public scrollbarX; @ViewChild("scrollContent", { static: false }) public scrollContent; @ViewChild("content", { static: false }) public simpleBarContent; @HostBinding("attr.sid") public id: string; private flashTimeout: any; private erd: any; private _currentDragEventCallbacks: any; private _lastScroll = { left: 0, top: 0 }; constructor( private elementRef: ElementRef, private scrollableService: ScrollableService, private changeDetector: ChangeDetectorRef) { this.id = SecureUtils.uuid(); this.scrollableService.registerScrollable(this); } public ngAfterViewInit() { this.resizeScrollContent(); this.resizeScrollbar(); this.drag = this.drag.bind(this); this.startDrag = this.startDrag.bind(this); this.endDrag = this.endDrag.bind(this); this.erd = elementResizeDetectorMaker({ strategy: "scroll", }); this.erd.listenTo(this.elementRef.nativeElement, (element) => { this.update(); const contentHeight = this.simpleBarContent.nativeElement.offsetHeight; const containerHeight = this.scrollable.nativeElement.offsetHeight; if (contentHeight + this.scrollMargin <= containerHeight) { this.scrollBottom.emit(); } }); } @HostListener("scroll") public onScroll() { const currentSroll = { left: this.scrollContent.nativeElement.scrollLeft, top: this.scrollContent.nativeElement.scrollTop, }; if (currentSroll.left !== this._lastScroll.left) { this.flashScrollbar(Orientation.Horizontal); } if (currentSroll.top !== this._lastScroll.top) { this.flashScrollbar(Orientation.Vertical); } this._lastScroll = currentSroll; if (this.scrolledToBottom()) { this.scrollBottom.emit(this.scrollTop()); } } public update() { this.resizeScrollContent(); this.resizeScrollbar(Orientation.Vertical); // this.resizeScrollbar(Orientation.Horizontal); } /** * Scroll the content to a specific position */ public scrollTo(position: number) { this.scrollContent.nativeElement.scrollTop = position; this.update(); } /** * Scroll to the bottom of the content */ public scrollToBottom() { this.scrollTo(this.scrollContent.nativeElement.scrollHeight); } public ngOnDestroy() { if (this.erd) { this.erd.uninstall(this.elementRef.nativeElement); } this.scrollableService.unregisterScrollable(this); } /** * Resize content element */ public resizeScrollContent() { this.scrollContent.nativeElement.style.width = `${this.scrollable.nativeElement.offsetWidth}px`; this.scrollContent.nativeElement.style.height = `${this.scrollable.nativeElement.offsetHeight}px`; } /** * Resize scrollbar */ public resizeScrollbar(orientation = Orientation.Vertical) { const track = this._track(orientation); const scrollbar = this._scrollbar(orientation); const contentSize = this._contentSize(orientation); const scrollOffset = this._scrollOffset(orientation); const scrollbarSize = this._scrollbarSize(orientation); const scrollbarRatio = scrollbarSize / contentSize; // Calculate new height/position of drag handle. // Offset of 2px allows for a small top/bottom or left/right margin around handle. const handleOffset = Math.round(scrollbarRatio * scrollOffset) + 2; const handleSize = Math.floor(scrollbarRatio * (scrollbarSize - 2)) - 2; // Set isVisible to false if scrollbar is not necessary (content is shorter than wrapper) this.isScrollbarNeeded[orientation] = scrollbarSize < contentSize; if (this.isScrollbarNeeded[orientation]) { track.style.visibility = "visible"; if (orientation === Orientation.Vertical) { scrollbar.style.top = `${handleOffset}px`; scrollbar.style.height = `${handleSize}px`; } else { scrollbar.style.left = `${handleOffset}px`; scrollbar.style.width = `${handleSize}px`; } } else { track.style.visibility = "hidden"; } } /** * Flash scrollbar visibility */ public flashScrollbar(orientation: Orientation = null) { if (orientation !== null) { this.resizeScrollbar(orientation); this.showScrollbar(orientation); } else { this.resizeScrollbar(Orientation.Vertical); this.resizeScrollbar(Orientation.Horizontal); this.showScrollbar(Orientation.Vertical); this.showScrollbar(Orientation.Horizontal); } } /** * Show scrollbar */ public showScrollbar(orientation: Orientation) { if (!this.isScrollbarNeeded) { return; } this.scrollbarVisible[orientation] = true; if (this.flashTimeout) { window.clearTimeout(this.flashTimeout); } this.flashTimeout = window.setTimeout(this.hideScrollbar.bind(this, orientation), 1000); this.changeDetector.markForCheck(); } /** * Hide Scrollbar */ public hideScrollbar(orientation: Orientation) { this.scrollbarVisible[orientation] = false; if (this.flashTimeout) { window.clearTimeout(this.flashTimeout); } this.changeDetector.markForCheck(); } /** * Start scrollbar handle drag */ public startDrag(e, orientation: Orientation) { // Preventing the event's default action stops text being // selectable during the drag. e.preventDefault(); this.dragging = true; const scrollbar = this._scrollbar(orientation); // Measure how far the user's mouse is from the top of the scrollbar drag handle. const eventOffset = orientation === Orientation.Vertical ? e.pageY : e.pageX; const val = orientation === Orientation.Vertical ? scrollbar.getBoundingClientRect().top : scrollbar.getBoundingClientRect().left; this.dragOffset[orientation] = eventOffset - val; this._currentDragEventCallbacks = { mousemove: _ => this.drag(_, orientation), mouseup: () => this.endDrag(orientation), }; document.addEventListener("mousemove", this._currentDragEventCallbacks.mousemove); document.addEventListener("mouseup", this._currentDragEventCallbacks.mouseup); } /** * Drag scrollbar handle */ public drag(e, orientation: Orientation) { e.preventDefault(); const eventOffset = orientation === Orientation.Vertical ? e.pageY : e.pageX; const track = this._track(orientation); const val = orientation === Orientation.Vertical ? track.getBoundingClientRect().top : track.getBoundingClientRect().left; // Calculate how far the user's mouse is from the top/left of the scrollbar (minus the dragOffset). const dragPos = eventOffset - val - this.dragOffset[orientation]; // Convert the mouse position into a percentage of the scrollbar height/width. const dragPerc = dragPos / this._scrollbarSize(orientation); // Scroll the content by the same percentage. const scrollPos = dragPerc * this._contentSize(orientation); if (orientation === Orientation.Vertical) { this.scrollContent.nativeElement.scrollTop = scrollPos; } else { this.scrollContent.nativeElement.scrollLeft = scrollPos; } } /** * End scroll handle drag */ public endDrag(orientation: Orientation) { this.dragging = false; // TODO fix document.removeEventListener("mousemove", this._currentDragEventCallbacks.mousemove); document.removeEventListener("mouseup", this._currentDragEventCallbacks.mouseup); } private scrollTop(): number { return this.scrollContent.nativeElement.scrollTop; } private currentHeight(): number { return this.elementRef.nativeElement.offsetHeight; } private currentContentHeight(): number { return this.simpleBarContent.nativeElement.offsetHeight; } private scrolledToBottom(): boolean { const scrollTop = this.scrollTop(); const height = this.currentHeight(); const contentHeight = this.currentContentHeight(); return height + scrollTop + this.scrollMargin >= contentHeight; } private _track(orientation: Orientation) { return orientation === Orientation.Vertical ? this.trackY.nativeElement : this.trackX.nativeElement; } private _scrollbar(orientation: Orientation) { return orientation === Orientation.Vertical ? this.scrollbarY.nativeElement : this.scrollbarX.nativeElement; } private _contentSize(orientation: Orientation) { const el = this.scrollContent.nativeElement; return orientation === Orientation.Vertical ? el.scrollHeight : el.scrollWidth; } private _scrollOffset(orientation: Orientation) { const el = this.scrollContent.nativeElement; return orientation === Orientation.Vertical ? el.scrollTop : el.scrollLeft; } private _scrollbarSize(orientation: Orientation) { const track = this._track(orientation); return orientation === Orientation.Vertical ? track.offsetHeight : track.offsetWidth; } }
the_stack
import {HttpClient, HttpErrorResponse} from "@angular/common/http"; import {Inject, Injectable, Injector} from "@angular/core"; import {TdDialogService} from "@covalent/core/dialogs"; import {Program} from "estree"; import "rxjs/add/observable/empty"; import "rxjs/add/observable/fromPromise"; import "rxjs/add/observable/interval"; import "rxjs/add/operator/expand"; import "rxjs/add/operator/map"; import "rxjs/add/operator/mergeMap"; import {Observable} from "rxjs/Observable"; import {catchError} from "rxjs/operators/catchError"; import {mergeMap} from "rxjs/operators/mergeMap"; import {take} from "rxjs/operators/take"; import {Subject} from "rxjs/Subject"; import * as _ from "underscore"; import {SchemaField} from "../../../model/schema-field"; import {TableSchema} from "../../../model/table-schema"; import {UserDatasource} from "../../../model/user-datasource"; import {DatasourcesService, TableReference} from "../../../services/DatasourcesServiceIntrefaces"; import {HiveService} from "../../../services/HiveService"; import {RestUrlService} from "../../../services/RestUrlService"; import {SqlDialect, VisualQueryService} from "../../../services/VisualQueryService"; import {DIALOG_SERVICE} from "../../wrangler/api/index"; import {SaveRequest, SaveResponse, SaveResponseStatus} from "../../wrangler/api/rest-model"; import {DialogService} from "../../wrangler/api/services/dialog.service"; import {ColumnController} from "../../wrangler/column-controller"; import {ColumnDelegate} from "../../wrangler/column-delegate"; import {QueryResultColumn} from "../../wrangler/model/query-result-column"; import {ScriptState} from "../../wrangler/model/script-state"; import {TransformResponse} from "../../wrangler/model/transform-response"; import {PageSpec, QueryEngine} from "../../wrangler/query-engine"; import {SparkColumnDelegate} from "./spark-column"; import {SparkConstants} from "./spark-constants"; import {DATASET_PROVIDER, SparkQueryParser} from "./spark-query-parser"; import {SparkScriptBuilder} from "./spark-script-builder"; import {HttpBackendClient} from "../../../../services/http-backend-client"; /** * Generates a Scala script to be executed by Kylo Spark Shell. */ @Injectable() export class SparkQueryEngine extends QueryEngine<string> { private readonly VALID_NAME_PATTERN = /[^a-zA-Z0-9\s_]|\s/g; /** * URL to the API server */ private readonly apiUrl: string; /** * Constructs a {@code SparkQueryEngine}. */ constructor(private $http: HttpClient, dialog: TdDialogService, @Inject(DIALOG_SERVICE) private wranglerDialog: DialogService, @Inject("HiveService") private HiveService: HiveService, @Inject("RestUrlService") private RestUrlService: RestUrlService, @Inject("VisualQueryService") private VisualQueryService: VisualQueryService, private $$angularInjector: Injector, @Inject("DatasourcesService") datasourcesService: any, @Inject("uiGridConstants") uiGridConstants: any, private httpBackendClient:HttpBackendClient) { super(dialog, datasourcesService, uiGridConstants, $$angularInjector); // Ensure Kylo Spark Shell is running this.apiUrl = this.RestUrlService.SPARK_SHELL_SERVICE_URL; $http.post(this.RestUrlService.SPARK_SHELL_SERVICE_URL + "/start", null).subscribe(); } /** * Indicates if both limit and sample can be applied at the same time. */ get allowLimitWithSample(): boolean { return true; } /** * Indicates if multiple data sources are allowed in the same query. */ get allowMultipleDataSources(): boolean { return true; } /** * Gets the sample formulas. */ get sampleFormulas(): { name: string; formula: string }[] { return [ {name: "Aggregate", formula: "groupBy(COLUMN).agg(count(COLUMN), sum(COLUMN))"}, {name: "Conditional", formula: "when(CONDITION, VALUE).when(CONDITION, VALUE).otherwise(VALUE)"}, {name: "Pivot", formula: "groupBy(COLUMN).pivot(COLUMN).agg(count(COLUMN))"}, {name: "Window", formula: "sum(COLUMN).over(orderBy(COLUMN))"} ]; } /** * Gets the SQL dialect used by this engine. */ get sqlDialect(): SqlDialect { return SqlDialect.HIVE; } /** * Indicates that the Hive data type should be used. */ get useNativeDataType(): boolean { return false; } /** * Creates a column delegate of the specified data type. */ createColumnDelegate(dataType: string, controller: ColumnController, column: any): ColumnDelegate { return new SparkColumnDelegate(column, dataType, controller, this.dialog, this.uiGridConstants, this.wranglerDialog, this.httpBackendClient, this.RestUrlService); } /** * Gets the field name for the specified column. */ getColumnName(column: QueryResultColumn): string { return column.displayName; } /** * Returns valid alpha numeric name * @param {string} label * @return {string} */ getValidHiveColumnName(label: string) { return label.replace(this.VALID_NAME_PATTERN, '') } /** * Gets the schema fields for the the current transformation. * * @returns the schema fields or {@code null} if the transformation has not been applied */ getFields(): SchemaField[] | null { const self = this; // Get list of columns const columns = this.getColumns(); if (columns === null) { return null; } // Get field list return columns.map(function (col: any) { let dataType; //comment out decimal to double. Decimals are supported ... will remove after testing if (col.dataType.startsWith("decimal")) { dataType = "decimal"; } else if (col.dataType === "smallint") { dataType = "int"; } else { dataType = col.dataType; } const name = (typeof col.displayName != "undefined") ? self.getValidHiveColumnName(col.displayName) : col.hiveColumnLabel; const colDef = {name: name, description: col.comment, dataType: dataType, primaryKey: false, nullable: false, sampleValues: []} as SchemaField; if (dataType === 'decimal') { //parse out the precisionScale let precisionScale = '20,2'; if (col.dataType.indexOf("(") > 0) { precisionScale = col.dataType.substring(col.dataType.indexOf("(") + 1, col.dataType.length - 1); } colDef.precisionScale = precisionScale; } colDef.derivedDataType = dataType; return colDef; }); } /** * Returns the data sources that are supported natively by this engine. */ getNativeDataSources(): Promise<UserDatasource[]> { return new Promise(resolve => resolve([{id: SparkConstants.HIVE_DATASOURCE, name: "Hive"} as UserDatasource])); } /** * Gets the Spark script. * * @param start - the index of the first transformation * @param end - the index of the last transformation * @param sample - {@code false} to disable sampling * @returns the Spark script */ getScript(start: number = null, end: number = null, sample: boolean = true): string { // Parse arguments start = (start !== null) ? start : 0; end = (end !== null) ? end + 1 : this.states_.length; // Build script let sparkScript = "import org.apache.spark.sql._\n"; if (start === 0) { if (this.hasSampleFile()) { //we are working with a file.. add the spark code to use it //extract options out from a variable to do the parsing sparkScript += this.sampleFile.script; sparkScript += "\n"; sparkScript += SparkConstants.DATA_FRAME_VARIABLE + " = " + SparkConstants.DATA_FRAME_VARIABLE; } else { sparkScript += this.source_; sparkScript += SparkConstants.DATA_FRAME_VARIABLE + " = " + SparkConstants.DATA_FRAME_VARIABLE; } //limit if (sample && this.limitBeforeSample_ && this.limit_ > 0) { sparkScript += ".limit(" + this.limit_ + ")"; } if (sample && this.sample_ > 0 && this.sample_ < 1) { sparkScript += ".sample(false, " + this.sample_ + ")"; } if (sample && !this.limitBeforeSample_ && this.limit_ > 0) { sparkScript += ".limit(" + this.limit_ + ")"; } sparkScript += "\n"; ++start; } else { sparkScript += "var " + SparkConstants.DATA_FRAME_VARIABLE + " = parent\n"; } let dsProvider = DATASET_PROVIDER; let joinDataSetIds :string[] = []; for (let i = start; i < end; ++i) { if (!this.states_[i].inactive) { let state = this.states_[i]; if(state.joinDataSet != undefined && state.joinDataSet != null) { if(joinDataSetIds.indexOf(state.joinDataSet.datasetId) <0){ joinDataSetIds.push(state.joinDataSet.datasetId); sparkScript +=state.joinDataSet.joinDataFrameVarScript+"\n"; } sparkScript += state.joinDataSet.joinScript; } sparkScript += SparkConstants.DATA_FRAME_VARIABLE + " = " + SparkConstants.DATA_FRAME_VARIABLE + this.states_[i].script + "\n"; } } sparkScript += SparkConstants.DATA_FRAME_VARIABLE + "\n"; return sparkScript; } /** * Gets the schema for the specified table. * * @param schema - name of the database or schema * @param table - name of the table * @param datasourceId - id of the datasource * @returns the table schema */ getTableSchema(schema: string, table: string, datasourceId: string): Promise<TableSchema> { if (datasourceId === SparkConstants.HIVE_DATASOURCE) { return this.$http.get<TableSchema>(this.RestUrlService.HIVE_SERVICE_URL + "/schemas/" + schema + "/tables/" + table).toPromise(); } else { return super.getTableSchema(schema, table, datasourceId); } } /** * Fetches the Ternjs definitions for this query engine. */ getTernjsDefinitions(): Promise<any> { return new Promise((resolve, reject) => { this.$http.get(this.RestUrlService.UI_BASE_URL + "/spark-functions").toPromise() .then(function (response: any) { resolve(response); }, function (err: string) { reject(err); }); }); } /** * Saves the results to the specified destination. * * @param request - save target * @returns an observable tracking the save status */ saveResults(request: SaveRequest): Observable<SaveResponse> { // Build the request body let body = { async: true, datasources: (this.datasources_ !== null) ? this.datasources_.filter(datasource => datasource.id !== SparkConstants.HIVE_DATASOURCE) : null, script: this.getFeedScript() }; if (request.jdbc && request.jdbc.id === SparkConstants.HIVE_DATASOURCE) { request.jdbc = null; } //add in the datasets if (this.datasets !== null) { body["catalogDatasets"] = this.datasets; } if(this.catalogDataSources_ != null) { body['catalogDataSources'] = this.catalogDataSources_; } // Send the request let transformId: string; return this.$http.post<TransformResponse>(this.apiUrl + "/transform", JSON.stringify(body), { headers: {"Content-Type": "application/json"}, responseType: "json" }) // Send save request .mergeMap(response => { transformId = response.table; return this.$http.post<SaveResponse>(this.apiUrl + "/transform/" + transformId + "/save", JSON.stringify(request), { headers: {"Content-Type": "application/json"}, responseType: "json" }); }) // Wait for save to complete .expand(response => { if (response.status === SaveResponseStatus.PENDING ) { return Observable.interval(1000) .pipe( take(1), mergeMap(() => this.$http.get<SaveResponse>(this.apiUrl + "/transform/" + transformId + "/save/" + response.id, {responseType: "json"})), catchError((error: SaveResponse) => { if (error.id == null) { error.id = response.id; } return Observable.throw(error); }) ); } else if (response.status === SaveResponseStatus.SUCCESS) { return Observable.empty(); } else { throw response; } }) // Map result to SaveResponse .map(save => { if (save.location != null && save.location.startsWith("./")) { save.location = this.apiUrl + "/transform/" + transformId + "/save/" + save.id + save.location.substr(1); } return save; }); } /** * Searches for table names matching the specified query. * * @param query - search query * @param datasourceId - datasource to search * @returns the list of table references */ searchTableNames(query: string, datasourceId: string): TableReference[] | Promise<TableReference[]> { if (datasourceId === SparkConstants.HIVE_DATASOURCE) { const tables = this.HiveService.queryTablesSearch(query); if (tables.then) { return new Promise((resolve, reject) => tables.then(resolve, reject)); } else { return tables as any; } } else { return super.searchTableNames(query, datasourceId); } } decodeError(msg: string): string { if (msg != null) { if (msg.indexOf("Cannot read property") > -1) { msg = "Please ensure fieldnames are correct."; } else if (msg.indexOf("Program is too long") > -1) { msg = "Please check parenthesis align." } else if (msg.indexOf("MatchError: ") > -1) { msg = "Please remove, impute, or replace all empty values and try again." } else if (msg.indexOf("AnalysisException: Can't extract value from ") > -1) { msg = "Action would invalidate downstream transformations or requires an upstream transformation that has been disabled."; } else if (msg.indexOf("Unsupported literal type class [D") > -1) { msg = "Function not available on present version of Spark."; } } return msg; } /** * Runs the current Spark script on the server. * * @return an observable for the response progress */ transform(pageSpec ?: PageSpec, doValidate: boolean = true, doProfile: boolean = false): Observable<any> { // Build the request body if (!pageSpec) { pageSpec = PageSpec.defaultPage(); } let body = { "policies": this.getState().fieldPolicies, "pageSpec": pageSpec, "doProfile": doProfile, "doValidate": doValidate }; let index = this.states_.length - 1; if (index > -1) { // Find last cached state let last = index - 1; while (last >= 0 && (this.states_[last].table === null)) { --last; } // Add script to body if (!this.hasStateChanged()) { body["script"] = "import org.apache.spark.sql._\nvar df = parent\ndf"; last = index; } else { body["script"] = this.getScript(last + 1, index); } if (last >= 0) { body["parent"] = { table: this.states_[last].table, script: this.getScript(0, last) }; } } else { body["script"] = this.getScript() } if (this.datasources_ !== null) { body["datasources"] = this.datasources_.filter(datasource => datasource.id !== SparkConstants.HIVE_DATASOURCE); } //add in the datasets if (this.datasets !== null) { body["catalogDatasets"] = this.datasets; } if(this.catalogDataSources_ != null) { body['catalogDataSources'] = this.catalogDataSources_; } // Create the response handlers let self = this; let deferred = new Subject(); let successCallback = function (response: TransformResponse) { let state = self.states_[index]; self.resetStateChange(); // Check status if (response.status === "PENDING") { deferred.next(response.progress); setTimeout(function () { self.$http.get<TransformResponse>(self.apiUrl + "/transform/" + response.table, { headers: {"Content-Type": "application/json"}, responseType: "json" }).toPromise().then(successCallback, errorCallback); }, 250, false); return; } if (response.status !== "SUCCESS") { deferred.error("Unexpected server status."); return; } // Verify column names let invalid = _.find(response.results.columns, function (column: any) { return (column.hiveColumnLabel.match(/[.`]/) !== null); // Escaping backticks not supported until Spark 2.0 }); let reserved = _.find(response.results.columns, function (column: any) { return SparkConstants.RESERVED_COLUMN_NAMES.indexOf(column.hiveColumnLabel) >=0; }); if (typeof invalid != "undefined") { state.rows = []; state.columns = []; deferred.error("Column name '" + invalid.hiveColumnLabel + "' is not supported. Please choose a different name."); } else if (typeof reserved != "undefined") { state.rows = []; state.columns = []; deferred.error("Column name '" + reserved.hiveColumnLabel + "' is reserved. Please choose a different name."); } else { // Update state state.profile = response.profile; state.rows = response.results.rows; state.table = response.table; state.validationResults = response.results.validationResults; state.actualCols = response.actualCols; state.actualRows = response.actualRows; state.columns = response.results.columns; self.updateFieldPolicies(state); // Indicate observable is complete deferred.complete(); } }; let errorCallback = function (response: HttpErrorResponse) { // Update state let state = self.states_[index]; state.columns = []; state.rows = []; self.resetStateChange(); // Respond with error message let message; if (response.error !== undefined && response.error.message != null) { message = self.decodeError(response.error.message.toString()); message = (message.length <= 1024) ? message : message.substr(0, 1021) + "..."; } else { message = "An unknown error occurred."; } deferred.error(message); }; // Send the request self.httpBackendClient.post<TransformResponse>(this.apiUrl + "/transform", JSON.stringify(body), { headers: {"Content-Type": "application/json"}, responseType: "json" }).toPromise().then(successCallback, errorCallback); return deferred; } /** * Parses the specified tree into a script for the current state. */ protected parseAcornTree(tree: any): string { return new SparkScriptBuilder(this.defs_, this).toScript(tree as Program); } /** * Parses the specified source into a script for the initial state. */ protected parseQuery(source: any): string { return new SparkQueryParser(this.VisualQueryService).toScript(source, this.datasources_, this.catalogDataSources_); } /** * Updates the field policies of the specified state to match the column order. * @param {ScriptState<string>} state */ private updateFieldPolicies(state: ScriptState<string>) { const self = this; if (state.fieldPolicies != null && state.fieldPolicies.length > 0) { const policyMap = {}; state.fieldPolicies.forEach(policy => { policyMap[policy.name] = policy; }); state.fieldPolicies = state.columns.map(column => { const name = (typeof column.displayName != "undefined") ? self.getValidHiveColumnName(column.displayName) : column.hiveColumnLabel; if (policyMap[name]) { return policyMap[name]; } else { return { name: name, fieldName: name, feedFieldName: name, domainTypeId: null, partition: null, profile: true, standardization: null, validation: null }; } }); } } }
the_stack
import { dirname, relative } from "path"; import { ArrayType, assert, ASTNode, ContractDefinition, ContractKind, DataLocation, EnumDefinition, EventDefinition, Expression, FunctionDefinition, ImportDirective, ModifierDefinition, SourceUnit, SrcRangeMap, Statement, StructDefinition, TypeNode, VariableDeclaration } from "solc-typed-ast"; import { print } from "../ast_to_source_printer"; import { SUserFunctionDefinition } from "../spec-lang/ast"; import { SemMap, TypeEnv } from "../spec-lang/tc"; import { dedup } from "../util/misc"; import { NameGenerator } from "../util/name_generator"; import { SourceMap } from "../util/sources"; import { AnnotationFilterOptions, AnnotationMetaData } from "./annotations"; import { CallGraph } from "./callgraph"; import { CHA } from "./cha"; import { AbsDatastructurePath } from "./custom_maps"; import { generateMapLibrary, getSetterName, makeDeleteFun, makeGetFun, makeIncDecFun, makeSetFun } from "./custom_maps_templates"; import { makeArraySumFun, UnsupportedConstruct } from "./instrument"; import { findAliasedStateVars } from "./state_vars"; import { DbgIdsMap, InstrumentationSiteType, TranspilingContext } from "./transpiling_context"; import { FactoryMap, ScribbleFactory, StructMap } from "./utils"; /** * Gather all named nodes in the provided source units. * @param units list of source units */ function getAllNames(units: SourceUnit[]): Set<string> { const nameSet = new Set<string>(); for (const unit of units) { for (const child of unit.getChildren()) { // Add all named declarations if ( child instanceof ContractDefinition || child instanceof FunctionDefinition || child instanceof ModifierDefinition || child instanceof EventDefinition || child instanceof StructDefinition || child instanceof EnumDefinition || child instanceof VariableDeclaration ) { nameSet.add(child.name); } if (child instanceof ImportDirective) { // Add unit aliases (import "foo" as foo;) if (child.unitAlias !== "") { nameSet.add(child.unitAlias); } // Add all symbol aliases for (const [originalDef, alias] of child.vSymbolAliases) { if (alias !== undefined) { nameSet.add(alias); } else { if (!(originalDef instanceof ImportDirective)) { nameSet.add(originalDef.name); } } } } } } return nameSet; } // Helper classes for various caches used in InstrumentationContext class WrapperCache extends StructMap<[ContractDefinition, string], string, FunctionDefinition> { protected getName(contract: ContractDefinition, name: string): string { return `${contract.id}_${name}`; } } abstract class ContextFactoryMap<A extends any[], B extends string | number, C> extends FactoryMap< A, B, C > { constructor(protected ctx: InstrumentationContext) { super(); } } class TranspilingContextCache extends ContextFactoryMap< [FunctionDefinition, InstrumentationSiteType], number, TranspilingContext > { protected getName(fun: FunctionDefinition): number { return fun.id; } protected makeNew(fun: FunctionDefinition, type: InstrumentationSiteType): TranspilingContext { return new TranspilingContext(this.ctx.typeEnv, this.ctx.semMap, fun, this.ctx, type); } } class VarToLibraryMap extends StructMap< [VariableDeclaration, AbsDatastructurePath], string, ContractDefinition > { protected getName(v: VariableDeclaration, path: AbsDatastructurePath): string { return `${v.id}_${path.map((x) => (x === null ? `[]` : x)).join("_")}`; } } class TypesToLibraryMap extends ContextFactoryMap< [TypeNode, TypeNode], string, ContractDefinition > { private _inverseMap = new Map<ContractDefinition, [TypeNode, TypeNode]>(); protected getName(keyT: TypeNode, valueT: TypeNode): string { return `${keyT.pp()}_to_${valueT.pp()}`; } protected makeNew(keyT: TypeNode, valueT: TypeNode): ContractDefinition { const res = generateMapLibrary(this.ctx, keyT, valueT, this.ctx.utilsUnit); this._inverseMap.set(res, [keyT, valueT]); return res; } public isLib(contract: ContractDefinition): boolean { return this._inverseMap.has(contract); } public getKVTypes(lib: ContractDefinition): [TypeNode, TypeNode] { const res = this._inverseMap.get(lib); assert(res !== undefined, `Missing key/value types for library ${lib.name}`); return res; } public isCustomMapLibrary(node: ContractDefinition): boolean { return this._inverseMap.has(node); } } class MapGetterMap extends ContextFactoryMap< [ContractDefinition, boolean], string, FunctionDefinition > { protected getName(lib: ContractDefinition, lhs: boolean): string { return `${lib.id}_${lhs}`; } protected makeNew(lib: ContractDefinition, lhs: boolean): FunctionDefinition { const [keyT, valueT] = this.ctx.typesToLibraryMap.getKVTypes(lib); return makeGetFun(this.ctx, keyT, valueT, lib, lhs); } } class MapSetterMap extends ContextFactoryMap< [ContractDefinition, TypeNode], string, FunctionDefinition > { protected getName(lib: ContractDefinition, newValT: TypeNode): string { const [, valueT] = this.ctx.typesToLibraryMap.getKVTypes(lib); return `${lib.id}_${getSetterName(valueT, newValT)}`; } protected makeNew(lib: ContractDefinition, newValT: TypeNode): FunctionDefinition { const [keyT, valueT] = this.ctx.typesToLibraryMap.getKVTypes(lib); return makeSetFun(this.ctx, keyT, valueT, lib, newValT); } } class MapIncDecMap extends ContextFactoryMap< [ContractDefinition, "++" | "--", boolean, boolean], string, FunctionDefinition > { protected getName( lib: ContractDefinition, operator: "++" | "--", prefix: boolean, unchecked: boolean ): string { return `${lib.id}_${operator}_${prefix}_${unchecked}`; } protected makeNew( lib: ContractDefinition, operator: "++" | "--", prefix: boolean, unchecked: boolean ): FunctionDefinition { const [keyT, valueT] = this.ctx.typesToLibraryMap.getKVTypes(lib); return makeIncDecFun(this.ctx, keyT, valueT, lib, operator, prefix, unchecked); } } class MapDeleteFunMap extends ContextFactoryMap<[ContractDefinition], number, FunctionDefinition> { protected getName(lib: ContractDefinition): number { return lib.id; } protected makeNew(lib: ContractDefinition): FunctionDefinition { const [keyT, valueT] = this.ctx.typesToLibraryMap.getKVTypes(lib); return makeDeleteFun(this.ctx, keyT, valueT, lib); } } class ArraySumFunMap extends ContextFactoryMap< [ArrayType, DataLocation], string, FunctionDefinition > { protected getName(arrT: ArrayType, loc: DataLocation): string { return `${arrT.pp()}_${loc}`; } protected makeNew(arrT: ArrayType, loc: DataLocation): FunctionDefinition { return makeArraySumFun(this.ctx, this.ctx.arrSumLibrary, arrT, loc); } } export class InstrumentationContext { public readonly nameGenerator: NameGenerator; public readonly structVar: string; public readonly checkStateInvsFuncName: string; public readonly outOfContractFlagName: string; public readonly scratchField: string; public readonly checkInvsFlag: string; public readonly utilsContractName: string; private internalInvariantCheckers: Map<ContractDefinition, string> = new Map(); public readonly userFunctions: Map<SUserFunctionDefinition, FunctionDefinition> = new Map(); /** * Map from Annotations to the list of statements involved in their evaluation. */ public readonly evaluationStatements: Map<AnnotationMetaData, ASTNode[]> = new Map(); /** * Map from Annotations to the actual `Expression` that corresponds to the * annotation being fully checked. */ public readonly instrumentedCheck: Map<AnnotationMetaData, Expression[]> = new Map(); /** * Map from Annotations to the actual asserts and event emissions * that are hit if the annotation fails. */ public readonly failureStatements: Map<AnnotationMetaData, Statement[]> = new Map(); /** * List of statements added for general instrumentation, not tied to any * particular annotation. */ private _generalInstrumentationNodes: ASTNode[] = []; public get generalInstrumentationNodes(): ASTNode[] { return this._generalInstrumentationNodes; } /** * Map containing debug event associated with a given annotation. */ public readonly debugEventsMap: Map<AnnotationMetaData, EventDefinition> = new Map(); /** * Bit of a hack - this is set by `generateUtilsContract`. We need an * InstrumentationContext already present for `generateUtilsContract` to be able * to use `ctx.nameGenerator`. */ public utilsContract!: ContractDefinition; public get utilsUnit(): SourceUnit { return this.utilsContract.parent as SourceUnit; } public readonly varInterposingQueue: Array<[VariableDeclaration, AbsDatastructurePath]>; private unitsNeedingUtils = new Set<SourceUnit>(); private _originalContents: Map<SourceUnit, string>; private _aliasedStateVars: Map<VariableDeclaration, ASTNode>; /** * ContractDefinition for a library containing helper functions for * computing sums over arrays. If there are no annotations with sums over * arrays, then this is undefined. */ private _arrSumLibrary?: ContractDefinition; /** * Map keeping track of the `TranspilingContext`s for each `FunctionDefinition`. */ public readonly transCtxMap = new TranspilingContextCache(this); /** * Cache keeping track of wrappers functions generated for each contract. */ public readonly wrapperCache = new WrapperCache(); /** * Map keeping track of the custom map library generated for a specific state var (or part thereof) */ public readonly sVarToLibraryMap = new VarToLibraryMap(); /** * Map factory keeping track of the custom map library generated for a specific state var (or part thereof) */ public readonly typesToLibraryMap = new TypesToLibraryMap(this); /** * Map factory keeping track of getter functions generated for a given custom map library */ public readonly libToMapGetterMap = new MapGetterMap(this); /** * Map factory keeping track of getter functions generated for a given custom map library */ public readonly libToMapSetterMap = new MapSetterMap(this); /** * Map factory keeping track of increment/decrement functions generated for a given custom map library */ public readonly libToMapIncDecMap = new MapIncDecMap(this); /** * Map factory keeping track of delete key functions generated for a given custom map library */ public readonly libToDeleteFunMap = new MapDeleteFunMap(this); /** * Map factory keeping track of array sum functions generated for a given array type and location */ public readonly arraySumFunMap = new ArraySumFunMap(this); constructor( public readonly factory: ScribbleFactory, public readonly units: SourceUnit[], public readonly assertionMode: "log" | "mstore", public readonly covAssertions: boolean, public readonly addAssert: boolean, public readonly callgraph: CallGraph, public readonly cha: CHA<ContractDefinition>, public readonly filterOptions: AnnotationFilterOptions, public readonly annotations: AnnotationMetaData[], public readonly wrapperMap: Map<FunctionDefinition, FunctionDefinition>, public readonly files: SourceMap, public readonly compilerVersion: string, public readonly debugEvents: boolean, public readonly debugEventsEncoding: Map<number, DbgIdsMap>, public readonly outputMode: "files" | "flat" | "json", public readonly typeEnv: TypeEnv, public readonly semMap: SemMap, _varInterposingQueue: Array<[VariableDeclaration, AbsDatastructurePath]> ) { this.nameGenerator = new NameGenerator(getAllNames(units)); this.structVar = this.nameGenerator.getFresh("_v", true); this.checkStateInvsFuncName = this.nameGenerator.getFresh( "__scribble_check_state_invariants", true ); this.outOfContractFlagName = this.nameGenerator.getFresh( "__scribble_out_of_contract", true ); this.scratchField = this.nameGenerator.getFresh("__mstore_scratch__", true); this.checkInvsFlag = this.nameGenerator.getFresh("__scribble_check_invs_at_end", true); this.utilsContractName = this.nameGenerator.getFresh("__scribble_ReentrancyUtils", true); this.varInterposingQueue = dedup( _varInterposingQueue, (x: [VariableDeclaration, AbsDatastructurePath]) => `${x[0].name}_${x[1].map((y) => (y === null ? "[]" : y)).join("_")}` ); this._originalContents = this.printUnits(units, new Map()); this._aliasedStateVars = findAliasedStateVars(units); } getInternalInvariantCheckerName(contract: ContractDefinition): string { if (!this.internalInvariantCheckers.has(contract)) { this.internalInvariantCheckers.set( contract, this.nameGenerator.getFresh( `__scribble_${contract.name}_check_state_invariants_internal`, true ) ); } return this.internalInvariantCheckers.get(contract) as string; } addGeneralInstrumentation(...nodes: ASTNode[]): void { this.generalInstrumentationNodes.push(...nodes); } addAnnotationInstrumentation(annotation: AnnotationMetaData, ...nodes: ASTNode[]): void { const targets = this.evaluationStatements.get(annotation); if (targets === undefined) { this.evaluationStatements.set(annotation, nodes); } else { targets.push(...nodes); } } addAnnotationCheck(annotation: AnnotationMetaData, pred: Expression): void { const targets = this.instrumentedCheck.get(annotation); if (targets === undefined) { this.instrumentedCheck.set(annotation, [pred]); } else { targets.push(pred); } } addAnnotationFailureCheck(annotation: AnnotationMetaData, ...nodes: Statement[]): void { const targets = this.failureStatements.get(annotation); if (targets === undefined) { this.failureStatements.set(annotation, nodes); } else { targets.push(...nodes); } } finalize(): void { // Finalize all TranspilingContexts for (const transCtx of this.transCtxMap.values()) { transCtx.finalize(); } // Add imports in all units that need the ReentrancyUtils contract for (const unit of this.unitsNeedingUtils) { const path = relative(dirname(unit.absolutePath), this.utilsUnit.absolutePath); unit.appendChild( this.factory.makeImportDirective( `./${path}`, this.utilsUnit.absolutePath, "", [], unit.id, this.utilsUnit.id ) ); } // Finally scan all nodes in generalInsturmentation for any potential orphans, and remove them // Orphans can happen during insturmentation, when we replace some node with a re-written copy const orphans = new Set<ASTNode>(); for (const nd of this._generalInstrumentationNodes) { if (nd.getClosestParentByType(SourceUnit) === undefined) { orphans.add(nd); } } this._generalInstrumentationNodes = this._generalInstrumentationNodes.filter( (nd) => !orphans.has(nd) ); } /** * Mark the given SourceUnit `unit` as needing an import from the utils module in files * instrumentation mode. */ needsUtils(unit: SourceUnit): void { this.unitsNeedingUtils.add(unit); } /** * Return the list of SourceUnits that were changed by instrumentation. * @todo We currently compute this by printing the files before and after * and comparing the contents. This is simple, but inefficient. It would be better * to either diff the ASTs themselves, or to keep a generation counter somewhere inside * the AST. */ get changedUnits(): SourceUnit[] { const newContents = this.printUnits(this.units, new Map()); const res: SourceUnit[] = []; for (const [unit, newUnitCont] of newContents.entries()) { const oldUnitCont = this._originalContents.get(unit); if (oldUnitCont !== newUnitCont) { res.push(unit); } } return res; } getAliasingNode(v: VariableDeclaration): ASTNode | undefined { return this._aliasedStateVars.get(v); } crashIfAliased(varDef: VariableDeclaration): void { const potentialAliasing = this.getAliasingNode(varDef); if (potentialAliasing !== undefined) { throw new UnsupportedConstruct( `Cannot instrument state var ${(varDef.parent as ContractDefinition).name}.${ varDef.name } as it may be aliased by a storage pointer`, potentialAliasing, this.files ); } } printUnits( units: SourceUnit[], srcMap: SrcRangeMap, instrumentationMarker?: string ): Map<SourceUnit, string> { return print(units, this.compilerVersion, srcMap, instrumentationMarker); } get arrSumLibrary(): ContractDefinition { if (this._arrSumLibrary === undefined) { const utilsUnit = this.utilsUnit; this._arrSumLibrary = this.factory.makeContractDefinition( "arr_sum_funs", utilsUnit.id, ContractKind.Library, false, true, [], [] ); this.utilsUnit.appendChild(this._arrSumLibrary); } return this._arrSumLibrary; } }
the_stack
import { BlockchainTestsEnvironment, constants, expect, getRandomInteger, randomAddress, } from '@0x/contracts-test-utils'; import { LimitOrder, LimitOrderFields, OrderBase, OrderInfo, OtcOrder, RfqOrder, RfqOrderFields, SignatureType, } from '@0x/protocol-utils'; import { BigNumber, hexUtils } from '@0x/utils'; import { TransactionReceiptWithDecodedLogs } from 'ethereum-types'; import { IZeroExContract, IZeroExLimitOrderFilledEventArgs, IZeroExOtcOrderFilledEventArgs, IZeroExRfqOrderFilledEventArgs, } from '../../src/wrappers'; import { artifacts } from '../artifacts'; import { fullMigrateAsync } from '../utils/migration'; import { TestMintableERC20TokenContract } from '../wrappers'; const { ZERO_AMOUNT: ZERO, NULL_ADDRESS } = constants; interface RfqOrderFilledAmounts { makerTokenFilledAmount: BigNumber; takerTokenFilledAmount: BigNumber; } interface OtcOrderFilledAmounts extends RfqOrderFilledAmounts {} interface LimitOrderFilledAmounts { makerTokenFilledAmount: BigNumber; takerTokenFilledAmount: BigNumber; takerTokenFeeFilledAmount: BigNumber; } export enum OtcOrderWethOptions { LeaveAsWeth, WrapEth, UnwrapWeth, } export class NativeOrdersTestEnvironment { public static async createAsync( env: BlockchainTestsEnvironment, gasPrice: BigNumber = new BigNumber('123e9'), protocolFeeMultiplier: number = 70e3, ): Promise<NativeOrdersTestEnvironment> { const [owner, maker, taker] = await env.getAccountAddressesAsync(); const [makerToken, takerToken] = await Promise.all( [...new Array(2)].map(async () => TestMintableERC20TokenContract.deployFrom0xArtifactAsync( artifacts.TestMintableERC20Token, env.provider, { ...env.txDefaults, gasPrice }, artifacts, ), ), ); const zeroEx = await fullMigrateAsync(owner, env.provider, env.txDefaults, {}, { protocolFeeMultiplier }); await makerToken.approve(zeroEx.address, constants.MAX_UINT256).awaitTransactionSuccessAsync({ from: maker }); await takerToken.approve(zeroEx.address, constants.MAX_UINT256).awaitTransactionSuccessAsync({ from: taker }); return new NativeOrdersTestEnvironment( maker, taker, makerToken, takerToken, zeroEx, gasPrice, gasPrice.times(protocolFeeMultiplier), env, ); } constructor( public readonly maker: string, public readonly taker: string, public readonly makerToken: TestMintableERC20TokenContract, public readonly takerToken: TestMintableERC20TokenContract, public readonly zeroEx: IZeroExContract, public readonly gasPrice: BigNumber, public readonly protocolFee: BigNumber, private readonly _env: BlockchainTestsEnvironment, ) {} public async prepareBalancesForOrdersAsync( orders: LimitOrder[] | RfqOrder[] | OtcOrder[], taker: string = this.taker, ): Promise<void> { await this.makerToken .mint(this.maker, BigNumber.sum(...(orders as OrderBase[]).map(order => order.makerAmount))) .awaitTransactionSuccessAsync(); await this.takerToken .mint( taker, BigNumber.sum( ...(orders as OrderBase[]).map(order => order.takerAmount.plus(order instanceof LimitOrder ? order.takerTokenFeeAmount : 0), ), ), ) .awaitTransactionSuccessAsync(); } public async fillLimitOrderAsync( order: LimitOrder, opts: Partial<{ fillAmount: BigNumber | number; taker: string; protocolFee: BigNumber | number; }> = {}, ): Promise<TransactionReceiptWithDecodedLogs> { const { fillAmount, taker, protocolFee } = { taker: this.taker, fillAmount: order.takerAmount, ...opts, }; await this.prepareBalancesForOrdersAsync([order], taker); const value = protocolFee === undefined ? this.protocolFee : protocolFee; return this.zeroEx .fillLimitOrder( order, await order.getSignatureWithProviderAsync(this._env.provider), new BigNumber(fillAmount), ) .awaitTransactionSuccessAsync({ from: taker, value }); } public async fillRfqOrderAsync( order: RfqOrder, fillAmount: BigNumber | number = order.takerAmount, taker: string = this.taker, ): Promise<TransactionReceiptWithDecodedLogs> { await this.prepareBalancesForOrdersAsync([order], taker); return this.zeroEx .fillRfqOrder( order, await order.getSignatureWithProviderAsync(this._env.provider), new BigNumber(fillAmount), ) .awaitTransactionSuccessAsync({ from: taker }); } public async fillOtcOrderAsync( order: OtcOrder, fillAmount: BigNumber | number = order.takerAmount, taker: string = this.taker, unwrapWeth: boolean = false, ): Promise<TransactionReceiptWithDecodedLogs> { await this.prepareBalancesForOrdersAsync([order], taker); if (unwrapWeth) { return this.zeroEx .fillOtcOrderForEth( order, await order.getSignatureWithProviderAsync(this._env.provider), new BigNumber(fillAmount), ) .awaitTransactionSuccessAsync({ from: taker }); } else { return this.zeroEx .fillOtcOrder( order, await order.getSignatureWithProviderAsync(this._env.provider), new BigNumber(fillAmount), ) .awaitTransactionSuccessAsync({ from: taker }); } } public async fillTakerSignedOtcOrderAsync( order: OtcOrder, origin: string = order.txOrigin, taker: string = order.taker, unwrapWeth: boolean = false, ): Promise<TransactionReceiptWithDecodedLogs> { await this.prepareBalancesForOrdersAsync([order], taker); if (unwrapWeth) { return this.zeroEx .fillTakerSignedOtcOrderForEth( order, await order.getSignatureWithProviderAsync(this._env.provider), await order.getSignatureWithProviderAsync(this._env.provider, SignatureType.EthSign, taker), ) .awaitTransactionSuccessAsync({ from: origin }); } else { return this.zeroEx .fillTakerSignedOtcOrder( order, await order.getSignatureWithProviderAsync(this._env.provider), await order.getSignatureWithProviderAsync(this._env.provider, SignatureType.EthSign, taker), ) .awaitTransactionSuccessAsync({ from: origin }); } } public async fillOtcOrderWithEthAsync( order: OtcOrder, fillAmount: BigNumber | number = order.takerAmount, taker: string = this.taker, ): Promise<TransactionReceiptWithDecodedLogs> { await this.prepareBalancesForOrdersAsync([order], taker); return this.zeroEx .fillOtcOrderWithEth(order, await order.getSignatureWithProviderAsync(this._env.provider)) .awaitTransactionSuccessAsync({ from: taker, value: fillAmount }); } public createLimitOrderFilledEventArgs( order: LimitOrder, takerTokenFillAmount: BigNumber = order.takerAmount, takerTokenAlreadyFilledAmount: BigNumber = ZERO, ): IZeroExLimitOrderFilledEventArgs { const { makerTokenFilledAmount, takerTokenFilledAmount, takerTokenFeeFilledAmount, } = computeLimitOrderFilledAmounts(order, takerTokenFillAmount, takerTokenAlreadyFilledAmount); const protocolFee = order.taker !== NULL_ADDRESS ? ZERO : this.protocolFee; return { takerTokenFilledAmount, makerTokenFilledAmount, takerTokenFeeFilledAmount, orderHash: order.getHash(), maker: order.maker, taker: this.taker, feeRecipient: order.feeRecipient, makerToken: order.makerToken, takerToken: order.takerToken, protocolFeePaid: protocolFee, pool: order.pool, }; } public createRfqOrderFilledEventArgs( order: RfqOrder, takerTokenFillAmount: BigNumber = order.takerAmount, takerTokenAlreadyFilledAmount: BigNumber = ZERO, ): IZeroExRfqOrderFilledEventArgs { const { makerTokenFilledAmount, takerTokenFilledAmount } = computeRfqOrderFilledAmounts( order, takerTokenFillAmount, takerTokenAlreadyFilledAmount, ); return { takerTokenFilledAmount, makerTokenFilledAmount, orderHash: order.getHash(), maker: order.maker, taker: this.taker, makerToken: order.makerToken, takerToken: order.takerToken, pool: order.pool, }; } public createOtcOrderFilledEventArgs( order: OtcOrder, takerTokenFillAmount: BigNumber = order.takerAmount, ): IZeroExOtcOrderFilledEventArgs { const { makerTokenFilledAmount, takerTokenFilledAmount } = computeOtcOrderFilledAmounts( order, takerTokenFillAmount, ); return { takerTokenFilledAmount, makerTokenFilledAmount, orderHash: order.getHash(), maker: order.maker, taker: order.taker !== NULL_ADDRESS ? order.taker : this.taker, makerToken: order.makerToken, takerToken: order.takerToken, }; } } /** * Generate a random limit order. */ export function getRandomLimitOrder(fields: Partial<LimitOrderFields> = {}): LimitOrder { return new LimitOrder({ makerToken: randomAddress(), takerToken: randomAddress(), makerAmount: getRandomInteger('1e18', '100e18'), takerAmount: getRandomInteger('1e6', '100e6'), takerTokenFeeAmount: getRandomInteger('0.01e18', '1e18'), maker: randomAddress(), taker: randomAddress(), sender: randomAddress(), feeRecipient: randomAddress(), pool: hexUtils.random(), expiry: new BigNumber(Math.floor(Date.now() / 1000 + 60)), salt: new BigNumber(hexUtils.random()), ...fields, }); } /** * Generate a random RFQ order. */ export function getRandomRfqOrder(fields: Partial<RfqOrderFields> = {}): RfqOrder { return new RfqOrder({ makerToken: randomAddress(), takerToken: randomAddress(), makerAmount: getRandomInteger('1e18', '100e18'), takerAmount: getRandomInteger('1e6', '100e6'), maker: randomAddress(), txOrigin: randomAddress(), pool: hexUtils.random(), expiry: new BigNumber(Math.floor(Date.now() / 1000 + 60)), salt: new BigNumber(hexUtils.random()), ...fields, }); } /** * Generate a random OTC Order */ export function getRandomOtcOrder(fields: Partial<OtcOrder> = {}): OtcOrder { return new OtcOrder({ makerToken: randomAddress(), takerToken: randomAddress(), makerAmount: getRandomInteger('1e18', '100e18'), takerAmount: getRandomInteger('1e6', '100e6'), maker: randomAddress(), taker: randomAddress(), txOrigin: randomAddress(), expiryAndNonce: OtcOrder.encodeExpiryAndNonce( fields.expiry ?? new BigNumber(Math.floor(Date.now() / 1000 + 60)), // expiry fields.nonceBucket ?? getRandomInteger(0, OtcOrder.MAX_NONCE_BUCKET), // nonceBucket fields.nonce ?? getRandomInteger(0, OtcOrder.MAX_NONCE_VALUE), // nonce ), ...fields, }); } /** * Asserts the fields of an OrderInfo object. */ export function assertOrderInfoEquals(actual: OrderInfo, expected: OrderInfo): void { expect(actual.status, 'Order status').to.eq(expected.status); expect(actual.orderHash, 'Order hash').to.eq(expected.orderHash); expect(actual.takerTokenFilledAmount, 'Order takerTokenFilledAmount').to.bignumber.eq( expected.takerTokenFilledAmount, ); } /** * Creates an order expiry field. */ export function createExpiry(deltaSeconds: number = 60): BigNumber { return new BigNumber(Math.floor(Date.now() / 1000) + deltaSeconds); } /** * Computes the maker, taker, and taker token fee amounts filled for * the given limit order. */ export function computeLimitOrderFilledAmounts( order: LimitOrder, takerTokenFillAmount: BigNumber = order.takerAmount, takerTokenAlreadyFilledAmount: BigNumber = ZERO, ): LimitOrderFilledAmounts { const fillAmount = BigNumber.min( order.takerAmount, takerTokenFillAmount, order.takerAmount.minus(takerTokenAlreadyFilledAmount), ); const makerTokenFilledAmount = fillAmount .times(order.makerAmount) .div(order.takerAmount) .integerValue(BigNumber.ROUND_DOWN); const takerTokenFeeFilledAmount = fillAmount .times(order.takerTokenFeeAmount) .div(order.takerAmount) .integerValue(BigNumber.ROUND_DOWN); return { makerTokenFilledAmount, takerTokenFilledAmount: fillAmount, takerTokenFeeFilledAmount, }; } /** * Computes the maker and taker amounts filled for the given RFQ order. */ export function computeRfqOrderFilledAmounts( order: RfqOrder, takerTokenFillAmount: BigNumber = order.takerAmount, takerTokenAlreadyFilledAmount: BigNumber = ZERO, ): RfqOrderFilledAmounts { const fillAmount = BigNumber.min( order.takerAmount, takerTokenFillAmount, order.takerAmount.minus(takerTokenAlreadyFilledAmount), ); const makerTokenFilledAmount = fillAmount .times(order.makerAmount) .div(order.takerAmount) .integerValue(BigNumber.ROUND_DOWN); return { makerTokenFilledAmount, takerTokenFilledAmount: fillAmount, }; } /** * Computes the maker and taker amounts filled for the given OTC order. */ export function computeOtcOrderFilledAmounts( order: OtcOrder, takerTokenFillAmount: BigNumber = order.takerAmount, ): OtcOrderFilledAmounts { const fillAmount = BigNumber.min(order.takerAmount, takerTokenFillAmount, order.takerAmount); const makerTokenFilledAmount = fillAmount .times(order.makerAmount) .div(order.takerAmount) .integerValue(BigNumber.ROUND_DOWN); return { makerTokenFilledAmount, takerTokenFilledAmount: fillAmount, }; } /** * Computes the remaining fillable amount in maker token for * the given order. */ export function getFillableMakerTokenAmount( order: LimitOrder | RfqOrder, takerTokenFilledAmount: BigNumber = ZERO, ): BigNumber { return order.takerAmount .minus(takerTokenFilledAmount) .times(order.makerAmount) .div(order.takerAmount) .integerValue(BigNumber.ROUND_DOWN); } /** * Computes the remaining fillable amnount in taker token, based on * the amount already filled and the maker's balance/allowance. */ export function getActualFillableTakerTokenAmount( order: LimitOrder | RfqOrder, makerBalance: BigNumber = order.makerAmount, makerAllowance: BigNumber = order.makerAmount, takerTokenFilledAmount: BigNumber = ZERO, ): BigNumber { const fillableMakerTokenAmount = getFillableMakerTokenAmount(order, takerTokenFilledAmount); return BigNumber.min(fillableMakerTokenAmount, makerBalance, makerAllowance) .times(order.takerAmount) .div(order.makerAmount) .integerValue(BigNumber.ROUND_UP); }
the_stack
import { ContractTransaction, ethers, BigNumber, utils, providers } from 'ethers'; import { Timestamp } from '@energyweb/utils-general'; import { getEventsFromContract } from '../utils/events'; import { encodeClaimData, decodeClaimData, IShareInCertificate, calculateOwnership, calculateClaims, decodeData, encodeData } from './CertificateUtils'; import { IBlockchainProperties } from './BlockchainProperties'; import { MAX_ENERGY_PER_CERTIFICATE } from './CertificationRequest'; import { IOwnershipCommitment, IOwnershipCommitmentProof, PreciseProofUtils } from '../utils/PreciseProofUtils'; export interface IClaimData { beneficiary: string; location: string; countryCode: string; periodStartDate: string; periodEndDate: string; purpose: string; } export interface IData { deviceId: string; generationStartTime: Timestamp; generationEndTime: Timestamp; metadata: string; } export interface IClaim { id: number; from: string; to: string; topic: string; // BigNumber string value: string; // BigNumber string claimData: IClaimData; } export interface ICertificate extends IData { id: number; issuer: string; creationTime: Timestamp; creationTransactionHash: string; owners: IShareInCertificate; claimers: IShareInCertificate; } export class Certificate implements ICertificate { public deviceId: string; public generationStartTime: Timestamp; public generationEndTime: Timestamp; public issuer: string; public creationTime: Timestamp; public creationTransactionHash: string; public initialized = false; public metadata: string; public owners: IShareInCertificate; public claimers: IShareInCertificate; constructor(public id: number, public blockchainProperties: IBlockchainProperties) {} /** * * * @description Uses the Issuer contract to allow direct issuance of a certificate * */ public static async create( to: string, value: BigNumber, generationStartTime: Timestamp, generationEndTime: Timestamp, deviceId: string, blockchainProperties: IBlockchainProperties, metadata?: string ): Promise<ContractTransaction> { if (value.gt(MAX_ENERGY_PER_CERTIFICATE)) { throw new Error( `Too much energy requested. Requested: ${value}, Max: ${MAX_ENERGY_PER_CERTIFICATE}` ); } const { issuer } = blockchainProperties; const issuerWithSigner = issuer.connect(blockchainProperties.activeUser); const data = encodeData({ generationStartTime, generationEndTime, deviceId, metadata: metadata ?? '' }); const properChecksumToAddress = ethers.utils.getAddress(to); return await issuerWithSigner.issue(properChecksumToAddress, value, data); } /** * * * @description Returns the Certificate that was created in a given transaction * */ public static async fromTxHash( txHash: string, blockchainProperties: IBlockchainProperties ): Promise<Certificate> { const tx = await blockchainProperties.web3.getTransactionReceipt(txHash); if (!tx || !tx.blockNumber) { throw new Error(`No certificate was issued in transaction ${txHash}`); } let result: ethers.utils.Result; for (const log of tx.logs) { try { result = blockchainProperties.issuer.interface.decodeEventLog( 'CertificationRequestApproved', log.data, log.topics ); } catch (e) { continue; } try { result = blockchainProperties.issuer.interface.decodeEventLog( 'PrivateCertificationRequestApproved', log.data, log.topics ); } catch (e) { continue; } } const newCertificate = new Certificate(result._id.toNumber(), blockchainProperties); newCertificate.creationTransactionHash = txHash; return newCertificate.sync(); } /** * * * @description Uses Private Issuer contract to allow issuance of a private Certificate * */ public static async createPrivate( to: string, value: BigNumber, generationStartTime: Timestamp, generationEndTime: Timestamp, deviceId: string, blockchainProperties: IBlockchainProperties, metadata?: string ): Promise<{ proof: IOwnershipCommitmentProof; tx: ContractTransaction }> { if (value.gt(MAX_ENERGY_PER_CERTIFICATE)) { throw new Error( `Too much energy requested. Requested: ${value}, Max: ${MAX_ENERGY_PER_CERTIFICATE}` ); } const { privateIssuer } = blockchainProperties; const privateIssuerWithSigner = privateIssuer.connect(blockchainProperties.activeUser); const data = encodeData({ generationStartTime, generationEndTime, deviceId, metadata: metadata ?? '' }); const properChecksumToAddress = ethers.utils.getAddress(to); const ownershipCommitment: IOwnershipCommitment = { [properChecksumToAddress]: value.toString() }; const commitmentProof = PreciseProofUtils.generateProofs(ownershipCommitment); const tx = await privateIssuerWithSigner.issuePrivate( properChecksumToAddress, commitmentProof.rootHash, data ); return { proof: commitmentProof, tx }; } /** * * * @description Retrieves current data for a Certificate * */ async sync(): Promise<Certificate> { if (this.id === null) { return this; } const { registry } = this.blockchainProperties; const issuanceTransaction = await this.getIssuanceTransaction(); const certOnChain = await registry.getCertificate(this.id); const decodedData = decodeData(certOnChain.data); this.generationStartTime = decodedData.generationStartTime; this.generationEndTime = decodedData.generationEndTime; this.deviceId = decodedData.deviceId; this.metadata = decodedData.metadata; this.issuer = certOnChain.issuer; const creationBlock = await registry.provider.getBlock(issuanceTransaction.blockNumber); this.creationTime = Number(creationBlock.timestamp); this.creationTransactionHash = issuanceTransaction.transactionHash; this.owners = await calculateOwnership( this.id, this.blockchainProperties, issuanceTransaction.blockNumber ); this.claimers = await calculateClaims( this.id, this.blockchainProperties, issuanceTransaction.blockNumber ); this.initialized = true; return this; } /** * * * @description Uses Registry contract to allow user to claim all or part of a Certificate's volume units * */ async claim( claimData: IClaimData, amount?: BigNumber, to?: string, from?: string ): Promise<ContractTransaction> { const { activeUser, registry } = this.blockchainProperties; const registryWithSigner = registry.connect(activeUser); const activeUserAddress = await activeUser.getAddress(); const claimAddress = to ?? activeUserAddress; const ownedVolume = BigNumber.from(this.owners[claimAddress] ?? 0); if (ownedVolume.eq(0) && !amount) { throw new Error(`claim(): ${claimAddress} does not own a share in the certificate.`); } const fromAddress = from ?? activeUserAddress; const encodedClaimData = encodeClaimData(claimData); return registryWithSigner.safeTransferAndClaimFrom( fromAddress, claimAddress, this.id, amount ?? ownedVolume, encodedClaimData, // TO-DO: Check the difference between data and claimData encodedClaimData ); } /** * * * @description Uses Registry contract to allow user to transfer part or all of a Certificate's volume units to another address * */ async transfer(to: string, amount?: BigNumber, from?: string): Promise<ContractTransaction> { if (await this.isRevoked()) { throw new Error(`Unable to transfer Certificate #${this.id}. It has been revoked.`); } const { activeUser, registry } = this.blockchainProperties; const fromAddress = from ?? (await activeUser.getAddress()); const toAddress = ethers.utils.getAddress(to); const ownedVolume = BigNumber.from(this.owners[toAddress] ?? 0); const registryWithSigner = registry.connect(activeUser); return registryWithSigner.safeTransferFrom( fromAddress, toAddress, this.id, amount ?? ownedVolume, utils.defaultAbiCoder.encode([], []) // TO-DO: Store more meaningful transfer data? ); } /** * * * @description Uses Issuer contract to allow issuer to mint more volumes of energy units for an existing Certificate * */ async mint(to: string, volume: BigNumber): Promise<ContractTransaction> { const toAddress = ethers.utils.getAddress(to); const { issuer } = this.blockchainProperties; const issuerWithSigner = issuer.connect(this.blockchainProperties.activeUser); return issuerWithSigner.mint(toAddress, this.id, volume); } /** * * * @description Uses Issuer contract to allow issuer to revoke a Certificate * */ async revoke(): Promise<ContractTransaction> { const { issuer } = this.blockchainProperties; const issuerWithSigner = issuer.connect(this.blockchainProperties.activeUser); return issuerWithSigner.revokeCertificate(this.id); } /** * * * @description Allows issuer to see if Certificate has been revoked * @returns boolean */ async isRevoked(): Promise<boolean> { const { issuer } = this.blockchainProperties; const issuanceTransaction = await this.getIssuanceTransaction(); const revokedEvents = await getEventsFromContract( issuer, issuer.filters.CertificateRevoked(this.id), issuanceTransaction.blockNumber ); return revokedEvents.length > 0; } /** * * * @description Returns all claim data for a Certificate * */ async getClaimedData(): Promise<IClaim[]> { const { registry } = this.blockchainProperties; const issuanceTransaction = await this.getIssuanceTransaction(); const claims: IClaim[] = []; const claimSingleEvents = await getEventsFromContract( registry, registry.filters.ClaimSingle(null, null, null, null, null, null), issuanceTransaction.blockNumber ); for (const claimEvent of claimSingleEvents) { if (claimEvent._id.toNumber() === this.id) { const { _claimData, _id, _claimIssuer, _claimSubject, _topic, _value } = claimEvent; const claimData = decodeClaimData(_claimData); claims.push({ id: _id.toNumber(), from: _claimIssuer, to: _claimSubject, topic: _topic.toString(), value: _value.toString(), claimData }); } } const claimBatchEvents = await getEventsFromContract( registry, registry.filters.ClaimBatch(null, null, null, null, null, null), issuanceTransaction.blockNumber ); for (const claimBatchEvent of claimBatchEvents) { if ( claimBatchEvent._ids.map((idAsBN: BigNumber) => idAsBN.toNumber()).includes(this.id) ) { const { _ids, _claimData, _claimIssuer, _claimSubject, _topics, _values } = claimBatchEvent; const claimIds = _ids.map((idAsBN: BigNumber) => idAsBN.toNumber()); const index = claimIds.indexOf(this.id); const claimData = decodeClaimData(_claimData[index]); claims.push({ id: _ids[index].toNumber(), from: _claimIssuer, to: _claimSubject, topic: _topics[index]?.toString(), value: _values[index].toString(), claimData }); } } const claimBatchMultipleEvents = await getEventsFromContract( registry, registry.filters.ClaimBatchMultiple(null, null, null, null, null, null), issuanceTransaction.blockNumber ); for (const claimBatchMultipleEvent of claimBatchMultipleEvents) { if ( claimBatchMultipleEvent._ids .map((idAsBN: BigNumber) => idAsBN.toNumber()) .includes(this.id) ) { const { _ids, _claimData, _claimIssuer, _claimSubject, _topics, _values } = claimBatchMultipleEvent; const claimIds = _ids.map((idAsBN: BigNumber) => idAsBN.toNumber()); const index = claimIds.indexOf(this.id); claims.push({ id: _ids[index].toNumber(), from: _claimIssuer[index], to: _claimSubject[index], topic: _topics[index]?.toString(), value: _values[index].toString(), claimData: decodeClaimData(_claimData[index]) }); } } return claims; } /** * * * @description Returns the Issuance transaction for a Certificate * */ private async getIssuanceTransaction(): Promise<providers.TransactionReceipt> { const { registry } = this.blockchainProperties; if (this.creationTransactionHash) { return await registry.provider.getTransactionReceipt(this.creationTransactionHash); } const allIssuanceLogs = await getEventsFromContract( registry, registry.filters.IssuanceSingle(null, null, null) ); let issuanceLog = allIssuanceLogs.find( (event) => event._id.toString() === this.id.toString() ); if (!issuanceLog) { const allBatchIssuanceLogs = await getEventsFromContract( registry, registry.filters.IssuanceBatch(null, null, null, null) ); issuanceLog = allBatchIssuanceLogs.find((event) => event._ids.map((id: BigNumber) => id.toString()).includes(this.id.toString()) ); if (!issuanceLog) { throw new Error(`Unable to find the issuance event for Certificate ${this.id}`); } } return registry.provider.getTransactionReceipt(issuanceLog.transactionHash); } }
the_stack
import * as React from 'react'; // import {createRef} from 'react'; For react v16.3 import * as ReactDom from 'react-dom'; import * as d3 from 'd3'; import ReactTable from 'react-table'; import 'react-table/react-table.css'; import { OverViewProps, PathRegion, Helpable, Utils } from './Utils'; import AutoComplete from './AutoComplete'; import styled from 'styled-components'; // tslint:disable-next-line:variable-name const FeatureTableContainer = styled.div` font-size: 12px; `; export interface SVListState { fusions: any; // DSVParsedArray<DSVRowString>; loading: boolean; filter: string; } class SVList extends React.Component<OverViewProps, SVListState> implements Helpable { private selectTable; // = createRef<ReactTable>(); constructor(props: OverViewProps) { super(props); this.onChange = this.onChange.bind(this); this.filterExec = this.filterExec.bind(this); this.filterByPosition = this.filterByPosition.bind(this); this.filterCancel = this.filterCancel.bind(this); this.state = { fusions: props.features, loading: false, filter: '' }; this.selectTable = null; this.addAllCandidate = this.addAllCandidate.bind(this); } componentWillReceiveProps(props: OverViewProps) { if ( this.props.features === undefined || props.features.length !== this.props.features.length ) { this.setState({ fusions: props.features, loading: false }); } } help() { return ( <div> <h3>Feature-Table</h3> <p>The Table shows the list of features between genomic coordinates.</p> <p>Structural variations are listed here.</p> <p>Click on the row to select the feature.</p> <p>Input genomic coordinates or gene name to filter variations.</p> </div> ); } link() { return 'feature-table'; } filterExec() { const pos = Utils.strToRegion(this.state.filter); const _this = this; if (pos[0] !== null) { this.filterByPosition(pos[0]); } else { fetch( '/api/v2/feature?ref=' + this.props.reference + '&equals=' + this.state.filter.toUpperCase() ) .then(function(response: Response) { return response.json(); }) .then(function(json2: any) { // FIXME() if (Object.prototype.toString.call(json2) === '[object Array]') json2 = json2[1]; // For Compatible var pos2; if (json2.start <= json2.stop) { pos2 = new PathRegion(json2.path, json2.start, json2.stop); } else { pos2 = new PathRegion(json2.path, json2.stop, json2.start); } _this.filterByPosition(pos2); }) .catch(function(err: any) { // handle error // console.error(err); }); } } filterByPosition(pos: PathRegion) { if (pos && pos.path) { const filteredFeatures = this.props.features.filter(a => { return ( (a.source_id === pos.path && pos.start <= a.source_breakpoint && a.source_breakpoint <= pos.stop) || (a.target_id === pos.path && pos.start <= a.target_breakpoint && a.target_breakpoint <= pos.stop) ); }); this.setState({ fusions: filteredFeatures }); } } filterCancel() { this.setState({ fusions: this.props.features, filter: '' }); } onChange = (event, { newValue }) => { this.setState({ filter: newValue }); if (newValue === '') { this.filterCancel(); } } posUpdate = (row, annotations) => { if (row.source_id === row.target_id) { this.props.posUpdate( [ new PathRegion( row.source_id, row.source_breakpoint, row.target_breakpoint, true, annotations ), /*new PathRegion( rowInfo.row._original.id, null, null, false, annotations )*/ ], row._index ); } else { this.props.posUpdate( [ new PathRegion( row.source_id, row.source_breakpoint, row.source_breakpoint, true, annotations ), new PathRegion( row.target_id, row.target_breakpoint, row.target_breakpoint, true, annotations ), /* new PathRegion( rowInfo.row._original.id, null, null, false, annotations )*/ ], row._index ); } } filter = ({ filter, onChange }) => ( <select onChange={event => onChange(event.target.value)} style={{ width: '100%', display: 'inline-block' }} className="form-control" value={filter ? filter.value : ''}> <option value="">Show All</option> {this.props.chroms.map(a => ( <option key={a.id} value={a.id}> {a.label} </option> ))} </select> ); addAllCandidate() { const tableState = this.selectTable.getResolvedState(); let props = tableState.sortedData.slice(tableState.page * tableState.pageSize, tableState.pageSize).map(row => { let annotations = [row.svtype, row.priority]; // this.posUpdate(row, annotations); return new PathRegion( row.source_id, row.source_breakpoint, row.target_breakpoint, true, annotations ); }); this.props.posUpdate(props, 0); } render() { const columns = [ { Header: () => <div onClick={this.addAllCandidate}><strong>GO</strong></div>, id: 'jump', width: 35, Filter: ({ filter, onChange }) => {return <div />; }, accessor: d => ( <a title="Go to this region" style={{ cursor: 'pointer' }}> <strong>&#x2295;</strong> </a> ) }, { Header: 'Source', columns: [ { Header: 'chrom', accessor: 'source_id', Filter: this.filter, filterMethod: (filter, row) => String(row[filter.id]) === filter.value, Cell: item => { return ( <span> <span style={{ color: Utils.strToColor(item.value, this.props.chroms), transition: 'all .3s ease' }}> &#x25cf; </span>{' '} {item.value} </span> ); } }, { Header: 'breakpoint', id: 'source_breakpoint', accessor: d => Number(d.source_breakpoint), Cell: item => { const item2 = Utils.formatPrettier(item.value); return <span>{item2}</span>; } }, { Header: '+/-', width: 40, accessor: 'source_strand' } ] }, { Header: 'Target', columns: [ { Header: 'chrom', accessor: 'target_id', Filter: this.filter, filterMethod: (filter, row) => String(row[filter.id]) === filter.value, Cell: item => { return ( <span> <span style={{ color: Utils.strToColor(item.value, this.props.chroms), transition: 'all .3s ease' }}> &#x25cf; </span>{' '} {item.value} </span> ); } }, { Header: 'breakpoint', id: 'target_breakpoint', accessor: d => Number(d.target_breakpoint), Cell: item => { const item2 = Utils.formatPrettier(item.value); return <span>{item2}</span>; } }, { Header: '+/-', width: 40, accessor: 'target_strand' } ] }, { Header: 'Stats', columns: [ { Header: 'priority', width: 80, id: 'priority', accessor: d => Number(d.priority) }, { Header: 'svtype', width: 80, filterMethod: (filter, row) => row[filter.id].startsWith(filter.value.toUpperCase()), accessor: 'svtype', Cell: item => { return ( <span> <span style={{ color: Utils.svTypeToColor(item.value), transition: 'all .3s ease' }}> &#x25cf; </span>{' '} {item.value} </span> ); } } ] } ]; return ( <FeatureTableContainer> <ReactTable defaultSorted={[ { id: 'priority', desc: true } ]} ref={(r) => this.selectTable = r} loading={this.state.loading} data={this.state.fusions} columns={columns} className="-striped -highlight" filterable={true} showPageSizeOptions={true} freezeWhenExpanded={true} defaultPageSize={10} /*filters={[ { // the current filters model id: 'source_id', value: this.props.pos[0].path } ]}*/ getTdProps={(state, rowInfo, column, instance) => { return { onClick: e => { if (column.id === 'jump' && rowInfo) { const _false = false; let annotations = [rowInfo.row.svtype, rowInfo.row.priority]; // Add annotations as filter if (this.state.filter !== '') { annotations.push(this.state.filter); } // If each variants has own id -- but currently it disabled. if (_false && rowInfo.row._original.hasOwnProperty('id')) { this.props.posUpdate( [ new PathRegion( rowInfo.row._original.id, null, null, false, annotations ) ], rowInfo.row._index ); } else { this.posUpdate(rowInfo.row, annotations); } } // console.log('It was in this table instance:', instance); } }; }} /> <div id="SelectByRegion"> <div className="form-group" style={{ display: 'flex' }}> <label>Filter: </label> <AutoComplete value={this.state.filter} onChange={this.onChange} reference={this.props.reference} width={300} title="Type a genomic region(path:start-stop) or gene name to filter items." placeholder="genomic region or gene name" /> </div> <div className="form-group" style={{ display: 'flex' }}> <input type="submit" className="btn btn-primary" value="filter" title="Filter all items by a genomic region(path:start-stop) or gene name." onClick={this.filterExec} /> <input type="submit" className="btn btn-secondary" value="cancel" title="Cancel filtering" onClick={this.filterCancel} /> </div> </div> </FeatureTableContainer> ); } } export default SVList;
the_stack
import localVarRequest from 'request'; import http from 'http'; let defaultBasePath = 'http://localhost/kfam'; // =============================================== // This file is autogenerated - Please do not edit // =============================================== /* tslint:disable:no-unused-variable */ let primitives = [ "string", "boolean", "double", "integer", "long", "float", "number", "any" ]; class ObjectSerializer { public static findCorrectType(data: any, expectedType: string) { if (data == undefined) { return expectedType; } else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) { return expectedType; } else if (expectedType === "Date") { return expectedType; } else { if (enumsMap[expectedType]) { return expectedType; } if (!typeMap[expectedType]) { return expectedType; // w/e we don't know the type } // Check the discriminator let discriminatorProperty = typeMap[expectedType].discriminator; if (discriminatorProperty == null) { return expectedType; // the type does not have a discriminator. use it. } else { if (data[discriminatorProperty]) { return data[discriminatorProperty]; // use the type given in the discriminator } else { return expectedType; // discriminator was not present (or an empty string) } } } } public static serialize(data: any, type: string) { if (data == undefined) { return data; } else if (primitives.indexOf(type.toLowerCase()) !== -1) { return data; } else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6 let subType: string = type.replace("Array<", ""); // Array<Type> => Type> subType = subType.substring(0, subType.length - 1); // Type> => Type let transformedData: any[] = []; for (let index in data) { let date = data[index]; transformedData.push(ObjectSerializer.serialize(date, subType)); } return transformedData; } else if (type === "Date") { return data.toString(); } else { if (enumsMap[type]) { return data; } if (!typeMap[type]) { // in case we dont know the type return data; } // get the map for the correct type. let attributeTypes = typeMap[type].getAttributeTypeMap(); let instance: {[index: string]: any} = {}; for (let index in attributeTypes) { let attributeType = attributeTypes[index]; instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type); } return instance; } } public static deserialize(data: any, type: string) { // polymorphism may change the actual type. type = ObjectSerializer.findCorrectType(data, type); if (data == undefined) { return data; } else if (primitives.indexOf(type.toLowerCase()) !== -1) { return data; } else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6 let subType: string = type.replace("Array<", ""); // Array<Type> => Type> subType = subType.substring(0, subType.length - 1); // Type> => Type let transformedData: any[] = []; for (let index in data) { let date = data[index]; transformedData.push(ObjectSerializer.deserialize(date, subType)); } return transformedData; } else if (type === "Date") { return new Date(data); } else { if (enumsMap[type]) {// is Enum return data; } if (!typeMap[type]) { // dont know the type return data; } let instance = new typeMap[type](); let attributeTypes = typeMap[type].getAttributeTypeMap(); for (let index in attributeTypes) { let attributeType = attributeTypes[index]; instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type); } return instance; } } } /** * Binding will give user edit access to referredNamespace */ export class Binding { 'user'?: Subject; 'referredNamespace'?: string; 'roleRef'?: RoleRef; /** * Status of the profile, one of Succeeded, Failed, Unknown. */ 'status'?: string; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "user", "baseName": "user", "type": "Subject" }, { "name": "referredNamespace", "baseName": "referredNamespace", "type": "string" }, { "name": "roleRef", "baseName": "RoleRef", "type": "RoleRef" }, { "name": "status", "baseName": "status", "type": "string" } ]; static getAttributeTypeMap() { return Binding.attributeTypeMap; } } export class BindingEntries { 'bindings'?: Array<Binding>; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "bindings", "baseName": "bindings", "type": "Array<Binding>" } ]; static getAttributeTypeMap() { return BindingEntries.attributeTypeMap; } } export class ErrorMessage { 'errorMessage'?: string; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "errorMessage", "baseName": "errorMessage", "type": "string" } ]; static getAttributeTypeMap() { return ErrorMessage.attributeTypeMap; } } export class Metadata { 'name'?: string; 'namespace'?: string; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "name", "baseName": "name", "type": "string" }, { "name": "namespace", "baseName": "namespace", "type": "string" } ]; static getAttributeTypeMap() { return Metadata.attributeTypeMap; } } export class Profile { 'metadata'?: Metadata; 'spec'?: ProfileSpec; 'status'?: ProfileStatus; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "metadata", "baseName": "metadata", "type": "Metadata" }, { "name": "spec", "baseName": "spec", "type": "ProfileSpec" }, { "name": "status", "baseName": "status", "type": "ProfileStatus" } ]; static getAttributeTypeMap() { return Profile.attributeTypeMap; } } export class ProfileSpec { /** * Only accept kind: user */ 'owner'?: Subject; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "owner", "baseName": "owner", "type": "Subject" } ]; static getAttributeTypeMap() { return ProfileSpec.attributeTypeMap; } } export class ProfileStatus { /** * Status of the profile, one of Succeeded, Failed, Unknown. */ 'status'?: string; /** * Non empty when at Failed status, containing detailed error messages */ 'message'?: string; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "status", "baseName": "status", "type": "string" }, { "name": "message", "baseName": "message", "type": "string" } ]; static getAttributeTypeMap() { return ProfileStatus.attributeTypeMap; } } /** * in consistent with io.k8s.api.rbac.v1.RoleRef */ export class RoleRef { 'apiGroup'?: string; 'kind'?: string; 'name'?: string; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "apiGroup", "baseName": "apiGroup", "type": "string" }, { "name": "kind", "baseName": "kind", "type": "string" }, { "name": "name", "baseName": "name", "type": "string" } ]; static getAttributeTypeMap() { return RoleRef.attributeTypeMap; } } /** * in consistent with io.k8s.api.rbac.v1.Subject */ export class Subject { 'kind'?: string; 'name'?: string; 'namespace'?: string; static discriminator: string | undefined = undefined; static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ { "name": "kind", "baseName": "kind", "type": "string" }, { "name": "name", "baseName": "name", "type": "string" }, { "name": "namespace", "baseName": "namespace", "type": "string" } ]; static getAttributeTypeMap() { return Subject.attributeTypeMap; } } let enumsMap: {[index: string]: any} = { } let typeMap: {[index: string]: any} = { "Binding": Binding, "BindingEntries": BindingEntries, "ErrorMessage": ErrorMessage, "Metadata": Metadata, "Profile": Profile, "ProfileSpec": ProfileSpec, "ProfileStatus": ProfileStatus, "RoleRef": RoleRef, "Subject": Subject, } export interface Authentication { /** * Apply authentication settings to header and query params. */ applyToRequest(requestOptions: localVarRequest.Options): void; } export class HttpBasicAuth implements Authentication { public username: string = ''; public password: string = ''; applyToRequest(requestOptions: localVarRequest.Options): void { requestOptions.auth = { username: this.username, password: this.password } } } export class ApiKeyAuth implements Authentication { public apiKey: string = ''; constructor(private location: string, private paramName: string) { } applyToRequest(requestOptions: localVarRequest.Options): void { if (this.location == "query") { (<any>requestOptions.qs)[this.paramName] = this.apiKey; } else if (this.location == "header" && requestOptions && requestOptions.headers) { requestOptions.headers[this.paramName] = this.apiKey; } } } export class OAuth implements Authentication { public accessToken: string = ''; applyToRequest(requestOptions: localVarRequest.Options): void { if (requestOptions && requestOptions.headers) { requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; } } } export class VoidAuth implements Authentication { public username: string = ''; public password: string = ''; applyToRequest(_: localVarRequest.Options): void { // Do nothing } } export enum DefaultApiApiKeys { } export class DefaultApi { protected _basePath = defaultBasePath; protected defaultHeaders : any = {}; protected _useQuerystring : boolean = false; protected authentications = { 'default': <Authentication>new VoidAuth(), } constructor(basePath?: string); constructor(basePathOrUsername: string, password?: string, basePath?: string) { if (password) { if (basePath) { this.basePath = basePath; } } else { if (basePathOrUsername) { this.basePath = basePathOrUsername } } } set useQuerystring(value: boolean) { this._useQuerystring = value; } set basePath(basePath: string) { this._basePath = basePath; } get basePath() { return this._basePath; } public setDefaultAuthentication(auth: Authentication) { this.authentications.default = auth; } public setApiKey(key: DefaultApiApiKeys, value: string) { (this.authentications as any)[DefaultApiApiKeys[key]].apiKey = value; } /** * Only admin or referred namespace owner can create binding * @summary Create a binding specifying a user and an namespace, the binding will grant user edit-access to referred namespace * @param body Binding spec * @param {*} [options] Override http request options. */ public createBinding (body: Binding, options: any = {}) : Promise<{ response: http.IncomingMessage; body?: any; }> { const localVarPath = this.basePath + '/v1/bindings'; let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createBinding.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'POST', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Binding") }; this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * * @summary Create a instance, which own a namespace of same name * @param body Profile spec * @param {*} [options] Override http request options. */ public createProfile (body: Profile, options: any = {}) : Promise<{ response: http.IncomingMessage; body?: any; }> { const localVarPath = this.basePath + '/v1/profiles'; let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling createProfile.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'POST', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Profile") }; this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * Only admin or referred namespace owner can delete binding * @summary Delete binding specified in request body * @param body Binding spec * @param {*} [options] Override http request options. */ public deleteBinding (body: Binding, options: any = {}) : Promise<{ response: http.IncomingMessage; body?: any; }> { const localVarPath = this.basePath + '/v1/bindings'; let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'body' is not null or undefined if (body === null || body === undefined) { throw new Error('Required parameter body was null or undefined when calling deleteBinding.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'DELETE', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, body: ObjectSerializer.serialize(body, "Binding") }; this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * Only admin or profile owner can delete profile * @summary Delete profile * @param profile Profile name * @param {*} [options] Override http request options. */ public deleteProfile (profile: string, options: any = {}) : Promise<{ response: http.IncomingMessage; body?: any; }> { const localVarPath = this.basePath + '/v1/profiles/{profile}' .replace('{' + 'profile' + '}', encodeURIComponent(String(profile))); let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'profile' is not null or undefined if (profile === null || profile === undefined) { throw new Error('Required parameter profile was null or undefined when calling deleteProfile.'); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'DELETE', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body?: any; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * Bindings will contain its current status * @summary Get bindings created via kubeflow; filtered by query param * @param user User name, when not empty, only return bindings of this user * @param namespace Namespace name, when not empty, only return bindings of this namespace * @param role Owner or editor or viewer, when not empty, only return bindings of this role * @param {*} [options] Override http request options. */ public readBindings (user?: string, namespace?: string, role?: string, options: any = {}) : Promise<{ response: http.IncomingMessage; body: BindingEntries; }> { const localVarPath = this.basePath + '/v1/bindings'; let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; if (user !== undefined) { localVarQueryParameters['user'] = ObjectSerializer.serialize(user, "string"); } if (namespace !== undefined) { localVarQueryParameters['namespace'] = ObjectSerializer.serialize(namespace, "string"); } if (role !== undefined) { localVarQueryParameters['role'] = ObjectSerializer.serialize(role, "string"); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body: BindingEntries; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "BindingEntries"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } /** * * @summary Query whether the user specified by query param is cluster admin * @param user username / email * @param {*} [options] Override http request options. */ public v1RoleClusteradminGet (user: string, options: any = {}) : Promise<{ response: http.IncomingMessage; body: boolean; }> { const localVarPath = this.basePath + '/v1/role/clusteradmin'; let localVarQueryParameters: any = {}; let localVarHeaderParams: any = (<any>Object).assign({}, this.defaultHeaders); let localVarFormParams: any = {}; // verify required parameter 'user' is not null or undefined if (user === null || user === undefined) { throw new Error('Required parameter user was null or undefined when calling v1RoleClusteradminGet.'); } if (user !== undefined) { localVarQueryParameters['user'] = ObjectSerializer.serialize(user, "string"); } (<any>Object).assign(localVarHeaderParams, options.headers); let localVarUseFormData = false; let localVarRequestOptions: localVarRequest.Options = { method: 'GET', qs: localVarQueryParameters, headers: localVarHeaderParams, uri: localVarPath, useQuerystring: this._useQuerystring, json: true, }; this.authentications.default.applyToRequest(localVarRequestOptions); if (Object.keys(localVarFormParams).length) { if (localVarUseFormData) { (<any>localVarRequestOptions).formData = localVarFormParams; } else { localVarRequestOptions.form = localVarFormParams; } } return new Promise<{ response: http.IncomingMessage; body: boolean; }>((resolve, reject) => { localVarRequest(localVarRequestOptions, (error, response, body) => { if (error) { reject(error); } else { body = ObjectSerializer.deserialize(body, "boolean"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { resolve({ response: response, body: body }); } else { reject({ response: response, body: body }); } } }); }); } }
the_stack
* Mock implementation of BlockchainApiConnection to specifically mock Substrate api calls that * require a connection to a Substrate blockchain. * * Transaction (tx) calls will return a mocked SubmittableExtrinsic containing a SubmittableResult * which will be returned when calling the `.send()` method. * This result defaults to `Finalized`, a default which can be changed by means of the `__setDefaultResult()` function: * ``` * require('../blockchainApiConnection/BlockchainApiConnection').__setDefaultResult( * false * ) * const transfer = blockchain.api.tx.balances.transfer(alice.address, amount) // returns a mock SubmittableExtrinsic that has a send() method * const result = await BlockchainUtils.signAndSubmitTx(alice, transfer) // calls transfer.send() internally * ``` * You can also queue results with * ``` * require('../blockchainApiConnection/BlockchainApiConnection').__queueResults( * [true, false] * ) * ``` * After queue results have been consumed via tx calls, the mock implementation will resume returning the default result. * * Mocked query methods return representations of 'not present' by default, such as Option(..., null) or Vec(..., []). * You can set different return values during test execution by importing __mocked_api, then calling jest's return * value setters `.mockReturnValue` or `.mockReturnValueOnce` on the method you want to modify: * ``` * const mocked_api = require('../blockchainApiConnection/BlockchainApiConnection').__mocked_api * mocked_api.query.delegation.hierarchies.mockReturnValue( * new Option( * 'Hash' * ) * ) * ``` * `.mockReturnValue` changes the default return value for the scope of the current test file. * `.mockReturnValueOnce()` can be called multiple times to build a queue of return values. After the queue has * been emptied by calling the query in question repeatedly, jest will return the default value again. * */ import { Blockchain } from '../../blockchain/Blockchain' import { ApiPromise, SubmittableResult } from '@polkadot/api' import type { AccountInfoWithProviders, ExtrinsicStatus, Index, } from '@polkadot/types/interfaces' import { GenericEventData, U64 } from '@polkadot/types' import type { IIdentity, ISubmittableResult, SubmittableExtrinsic, } from '@kiltprotocol/types' import { mockChainQueryReturn } from './BlockchainQuery' import { TYPE_REGISTRY } from '../TypeRegistry' const BlockchainApiConnection = jest.requireActual('../BlockchainApiConnection') const accumulator = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] async function getConnectionOrConnect(): Promise<Blockchain> { if (!BlockchainApiConnection.instance) { BlockchainApiConnection.instance = Promise.resolve( new Blockchain(__mocked_api as ApiPromise) ) } return BlockchainApiConnection.instance } const TxResultsQueue: ISubmittableResult[] = [] let defaultTxResult: ISubmittableResult = __makeSubmittableResult({}) class MockSubmittableExtrinsic { result: ISubmittableResult method = { toHex: () => '0x00' } signature = { signed: false, toHuman: (): number | undefined => undefined, } nonce = { toHuman: (): number | undefined => undefined } constructor(result: ISubmittableResult) { this.result = result } public addSignature() { const signature = this.signature.toHuman() ? this.signature.toHuman()! + 1 : 0 this.signature = { signed: true, toHuman: () => signature, } const nonce = this.nonce.toHuman() ? this.nonce.toHuman()! + 1 : 0 this.nonce = { toHuman: () => nonce } return this } public signAsync() { const signature = this.signature.toHuman() ? this.signature.toHuman()! : 0 this.signature = { signed: true, toHuman: () => signature, } const nonce = this.nonce.toHuman() ? this.nonce.toHuman()! : 0 this.nonce = { toHuman: () => nonce } return this } public async send(callable: Function) { if (callable) { callable(this.result) return () => {} } return '0x123' } public async signAndSend(a: any, callable: Function) { const signature = this.signature.toHuman() ? this.signature.toHuman()! : 0 this.signature = { signed: true, toHuman: () => signature, } const nonce = this.nonce.toHuman() ? this.nonce.toHuman()! : 0 this.nonce = { toHuman: () => nonce } if (callable) { callable(this.result) return () => {} } return '0x123' } } function __getMockSubmittableExtrinsic(): SubmittableExtrinsic { const result: ISubmittableResult = TxResultsQueue.shift() || defaultTxResult return new MockSubmittableExtrinsic(result) as any as SubmittableExtrinsic } function __makeSubmittableResult( opts: Partial<ExtrinsicStatus> ): ISubmittableResult { const finalized = opts ? !Object.keys(opts)[0] : true const status: ExtrinsicStatus = { isFinalized: finalized, isDropped: false, isInvalid: false, isUsurped: false, isFuture: false, isReady: true, } as any for (const key in opts) { status[key] = opts[key] } const eventData = new GenericEventData( TYPE_REGISTRY, new Uint8Array([0]), {} as any, 'system', 'ExtrinsicSuccess' ) return new SubmittableResult({ status, events: [ { phase: { asApplyExtrinsic: { isEmpty: false, }, }, event: { section: 'system', data: eventData, index: { toHex: jest.fn(() => { return '0x0000' }), }, // portablegabi checks if a transaction was successful method: 'ExtrinsicSuccess', }, } as any, ], }) } function __queueResults(results: Partial<ExtrinsicStatus>[]) { results.forEach((status) => { TxResultsQueue.push(__makeSubmittableResult(status)) }) } function __setDefaultResult(status: Partial<ExtrinsicStatus>) { defaultTxResult = __makeSubmittableResult(status) } const __mocked_api: any = { rpc: { system: { chain: jest.fn(), name: jest.fn(), version: jest.fn(), accountNextIndex: jest.fn( async (): Promise<Index> => TYPE_REGISTRY.createType('Index', 0) ), }, chain: { subscribeNewHeads: jest.fn() }, }, tx: { attestation: { add: jest.fn((claimHash, _cTypeHash) => { return __getMockSubmittableExtrinsic() }), revoke: jest.fn((claimHash: string) => { return __getMockSubmittableExtrinsic() }), remove: jest.fn((claimHash: string) => { return __getMockSubmittableExtrinsic() }), reclaimDeposit: jest.fn((claimHash: string) => { return __getMockSubmittableExtrinsic() }), }, balances: { transfer: jest.fn(() => __getMockSubmittableExtrinsic()), }, ctype: { add: jest.fn((hash, signature) => { return __getMockSubmittableExtrinsic() }), }, delegation: { createHierarchy: jest.fn((rootId, _ctypeHash) => { return __getMockSubmittableExtrinsic() }), addDelegation: jest.fn( (delegationId, parent_id, owner, permissions, signature) => { return __getMockSubmittableExtrinsic() } ), revokeDelegation: jest.fn((delegationId) => { return __getMockSubmittableExtrinsic() }), }, did: { add: jest.fn((sign_key, box_key, doc_ref) => { return __getMockSubmittableExtrinsic() }), remove: jest.fn(() => { return __getMockSubmittableExtrinsic() }), }, portablegabi: { updateAccumulator: jest.fn((acc) => { // change the accumulator for each update accumulator.push(accumulator.length) return __getMockSubmittableExtrinsic() }), }, }, query: { system: { // default return value decodes to BN(0) // default return value decodes to AccountInfo with all entries holding BN(0) account: jest.fn( async ( address: IIdentity['address'], cb ): Promise<AccountInfoWithProviders> => TYPE_REGISTRY.createType('AccountInfoWithProviders') ), }, attestation: { // default return value decodes to [], represents no delegated attestations delegatedAttestations: jest.fn(async (id: string) => mockChainQueryReturn('attestation', 'delegatedAttestations') ), /* example return value: new Vec( TYPE_REGISTRY 'Hash', ['0x123', '0x456', '0x789'] ) */ // default return value decodes to null, represents attestation not found attestations: jest.fn(async (claim_hash: string) => mockChainQueryReturn('attestation', 'attestations') ), /* example return value: new Option( TYPE_REGISTRY, Tuple.with(['Hash', AccountId, 'Option<Hash>', Bool]), [ '0x1234', // ctype hash '4r1WkS3t8rbCb11H8t3tJvGVCynwDXSUBiuGB6sLRHzCLCjs', // Account null, // delegation-id? true, // revoked flag '{ '4r1WkS3t8rbCb11H8t3tJvGVCynwDXSUBiuGB6sLRHzCLCjs, 10 }', // deposit details ] ) */ }, ctype: { // default return value decodes to null, represents CTYPE not found ctypes: jest.fn(async (hash: string) => mockChainQueryReturn('ctype', 'cTYPEs') ), }, delegation: { // default return value decodes to null, represents delegation not found hierarchies: jest.fn(async (rootId: string) => mockChainQueryReturn('delegation', 'hierarchies') ), /* example return value: new Option( TYPE_REGISTRY, Hash, '0x1234', // ctype hash ) */ // default return value decodes to null, represents delegation not found delegations: jest.fn(async (delegationId: string) => mockChainQueryReturn('delegation', 'delegations') ), /* example return value: new Option( TYPE_REGISTRY, Tuple.with(['DelegationNodeId','Option<DelegationNodeId>','Vec<DelegationNodeId>',DelegationDetails]), [ '0x1234', // root-id '0x1234', // parent-id? '[0x2345,0x3456] // children ids '{4r1WkS3t8rbCb11H8t3tJvGVCynwDXSUBiuGB6sLRHzCLCjs,false,0}', // {owner, revocation status, permissions} '{ '4r1WkS3t8rbCb11H8t3tJvGVCynwDXSUBiuGB6sLRHzCLCjs, 10 }', // deposit details ] ) */ }, did: { // default return value decodes to null, represents dID not found dIDs: jest.fn(async (address: string) => mockChainQueryReturn('did', 'dIDs') ), /* example return value: new Option( TYPE_REGISTRY, Tuple.with(['Hash','Hash','Option<Bytes>']), [ 'publicSigningKey', // publicSigningKey 'publicBoxKey', // publicBoxKey stringToHex('http://myDID.kilt.io'), // document store ] ) */ }, portablegabi: { accumulatorList: jest.fn((address: string, index: number) => mockChainQueryReturn('portablegabi', 'accumulatorList', accumulator) ), accumulatorCount: jest.fn((address: string) => mockChainQueryReturn( 'portablegabi', 'accumulatorCount', new U64(TYPE_REGISTRY, 1) ) ), }, }, runtimeMetadata: { asV11: { modules: [], }, }, registry: TYPE_REGISTRY, } BlockchainApiConnection.getConnectionOrConnect = getConnectionOrConnect BlockchainApiConnection.__queueResults = __queueResults BlockchainApiConnection.__setDefaultResult = __setDefaultResult BlockchainApiConnection.__mocked_api = __mocked_api BlockchainApiConnection.mockChainQueryReturn = mockChainQueryReturn module.exports = BlockchainApiConnection
the_stack
export as namespace h337; /** * Create a heatmap instance. A Heatmap can be customized with the configObject. * * @example <caption>Simple configuration with standard gradient</caption> * * // create configuration object * var config = { * container: document.getElementById('heatmapContainer'), * radius: 10, * maxOpacity: .5, * minOpacity: 0, * blur: .75 * }; * // create heatmap with configuration * var heatmapInstance = h337.create(config); * * @example <caption>Custom gradient configuration</caption> * * // create configuration object * var config = { * container: document.getElementById('heatmapContainer'), * radius: 10, * maxOpacity: .5, * minOpacity: 0, * blur: .75, * gradient: { * // enter n keys between 0 and 1 here * // for gradient color customization * '.5': 'blue', * '.8': 'red', * '.95': 'white' * } * }; * var heatmapInstance = h337.create(config); */ export function create< V extends string = 'value', X extends string = 'x', Y extends string = 'y' >( configObject: HeatmapConfiguration<V, X, Y> ): Heatmap<V, X, Y>; export function register(pluginKey: string, plugin: any): void; /** * Heatmap instances are returned by h337.create. A heatmap instance has its own * internal datastore and renderer where you can manipulate data. As a result * the heatmap gets updated (either partially or completely, depending on * whether it's necessary). */ export class Heatmap<V extends string, X extends string, Y extends string> { /** * Use this functionality only for adding datapoints on the fly, not for data * initialization! heatmapInstance.addData adds a single or multiple * datapoints to the heatmap's datastore. * * @example <caption>A single datapoint</caption> * * var dataPoint = { * x: 5, // x coordinate of the datapoint, a number * y: 5, // y coordinate of the datapoint, a number * value: 100 // the value at datapoint(x, y) * }; * heatmapInstance.addData(dataPoint); * * @example <caption>multiple datapoints</caption> * * // for data initialization use setData!! * var dataPoints = [dataPoint, dataPoint, dataPoint, dataPoint]; * heatmapInstance.addData(dataPoints); */ addData(dataPoint: DataPoint<V, X, Y> | ReadonlyArray<DataPoint<V, X, Y>>): this; /** * Initialize a heatmap instance with the given dataset. Removes all * previously existing points from the heatmap instance and re-initializes * the datastore. * * @example * * var data = { * max: 100, * min: 0, * data: [ * dataPoint, dataPoint, dataPoint, dataPoint * ] * }; * heatmapInstance.setData(data); */ setData(data: HeatmapData<DataPoint<V, X, Y>>): this; /** * Changes the upper bound of your dataset and triggers a complete * rerendering. * * @example * * heatmapInstance.setDataMax(200); * // setting the maximum value triggers a complete rerendering of the heatmap * heatmapInstance.setDataMax(100); */ setDataMax(number: number): this; /** * Changes the lower bound of your dataset and triggers a complete * rerendering. * * @example * * heatmapInstance.setDataMin(10); * // setting the minimum value triggers a complete rerendering of the heatmap * heatmapInstance.setDataMin(0); */ setDataMin(number: number): this; /** * Reconfigures a heatmap instance after it has been initialized. Triggers a * complete rerendering. * * NOTE: This returns a reference to itself, but also offers an opportunity * to change the `xField`, `yField` and `valueField` options, which can * change the type of the `Heatmap` instance. * * @example * * var nuConfig = { * radius: 10, * maxOpacity: .5, * minOpacity: 0, * blur: .75 * }; * heatmapInstance.configure(nuConfig); */ configure< Vn extends string = V, Xn extends string = X, Yn extends string = Y >(configObject: HeatmapConfiguration<Vn, Xn, Yn>): Heatmap<Vn, Xn, Yn>; /** * Returns value at datapoint position. * * The returned value is an interpolated value based on the gradient blending * if point is not in store. * * @example * * heatmapInstance.addData({ x: 10, y: 10, value: 100}); * // get the value at x=10, y=10 * heatmapInstance.getValueAt({ x: 10, y: 10 }); // returns 100 */ getValueAt(point: { x: number, y: number }): number; /** * Returns a persistable and reimportable (with setData) JSON object. * * @example * * var currentData = heatmapInstance.getData(); * // now let's create a new instance and set the data * var heatmap2 = h337.create(config); * heatmap2.setData(currentData); // now both heatmap instances have the same content */ getData(): HeatmapData<DataCircle>; /** * Returns dataURL string. * * The returned value is the base64 encoded dataURL of the heatmap instance. * * @example * * heatmapInstance.getDataURL(); // data:image/png;base64... * // ready for saving locally or on the server */ getDataURL(): string; /** * Repaints the whole heatmap canvas. */ repaint(): this; } export interface BaseHeatmapConfiguration<V extends string = 'value'> { /** * A background color string in form of hexcode, color name, or rgb(a) */ backgroundColor?: string; /** * The blur factor that will be applied to all datapoints. The higher the * blur factor is, the smoother the gradients will be * Default value: 0.85 */ blur?: number; /** * An object that represents the gradient. * Syntax: {[key: number in range [0,1]]: color} */ gradient?: { [key: string]: string }; /** * The maximal opacity the highest value in the heatmap will have. (will be * overridden if opacity set) * Default value: 0.6 */ maxOpacity?: number; /** * The minimum opacity the lowest value in the heatmap will have (will be * overridden if opacity set) */ minOpacity?: number; /** * A global opacity for the whole heatmap. This overrides maxOpacity and * minOpacity if set * Default value: 0.6 */ opacity?: number; /** * The radius each datapoint will have (if not specified on the datapoint * itself) */ radius?: number; /** * Scales the radius based on map zoom. */ scaleRadius?: boolean; /** * The property name of the value/weight in a datapoint * Default value: 'value' */ valueField?: V; /** * Pass a callback to receive extrema change updates. Useful for DOM * legends. */ onExtremaChange?: () => void; /** * Indicate whether the heatmap should use a global extrema or a local * extrema (the maximum and minimum of the currently displayed viewport) */ useLocalExtrema?: boolean; } /** * Configuration object of a heatmap */ export interface HeatmapConfiguration< V extends string = 'value', X extends string = 'x', Y extends string = 'y', > extends BaseHeatmapConfiguration<V> { /** * A DOM node where the heatmap canvas should be appended (heatmap will adapt to * the node's size) */ container: HTMLElement; /** * The property name of your x coordinate in a datapoint * Default value: 'x' */ xField?: X; /** * The property name of your y coordinate in a datapoint * Default value: 'y' */ yField?: Y; } export interface HeatmapOverlayConfiguration< V extends string = 'value', TLat extends string = 'lat', TLong extends string = 'lng', > extends BaseHeatmapConfiguration<V> { /** * The property name of your latitude coordinate in a datapoint * Default value: 'x' */ latField?: TLat; /** * The property name of your longitude coordinate in a datapoint * Default value: 'y' */ lngField?: TLong; } /** * A single data point on a heatmap. The interface of the data point can be * overridden by providing alternative values for `xKey` and `yKey` in the * config object. */ export type DataPoint< V extends string = 'value', X extends string = 'x', Y extends string = 'y', > = Record<V | X | Y, number>; /** * Type of data returned by `Heatmap#hello`, which ignores custom `xField`, * `yField` and `valueField`. */ export interface DataCircle { x: number; y: number; value: number; radius: number; } /** * An object representing the set of data points on a heatmap */ export interface HeatmapData<T> { /** * An array of data points */ data: ReadonlyArray<T>; /** * Max value of the valueField */ max: number; /** * Min value of the valueField */ min: number; } // -- Leaflet plugin -- import * as Leaflet from "leaflet"; declare global { /** * The overlay layer to be added onto leaflet map */ class HeatmapOverlay< V extends string, TLat extends string, TLng extends string > implements Leaflet.ILayer { /** * Initialization function */ constructor(configuration: HeatmapOverlayConfiguration<V, TLat, TLng>); /** * Initialize a heatmap instance with the given dataset */ setData(data: HeatmapData<DataPoint<V, TLat, TLng>>): void; /** * Experimential... not ready. */ addData(data: DataPoint<V, TLat, TLng> | ReadonlyArray<DataPoint<V, TLat, TLng>>): void; /** * Create DOM elements for an overlay, adding them to map panes and puts * listeners on relevant map events */ onAdd(map: Leaflet.Map): void; /** * Remove the overlay's elements from the DOM and remove listeners * previously added by onAdd() */ onRemove(map: Leaflet.Map): void; } }
the_stack
import { SubAppRenderPipeline } from "./subapp-render-pipeline"; /** * CDN mapping data type * * @remark * Internal use */ export type CDNData = { /** mapping data */ md: Record<string, any>; }; /** * xarcV2 client runtime type. * * @remark * Internal use */ export type _xarcV2RunTimeInfo = { instId: number; subApps: Record<string, any>; onLoadStart: Record<string, any>; started: boolean; /** CDN mapping data */ md: Record<string, any>; }; /** * xarc subapp version client interface */ export interface XarcSubAppClientV2 { IS_BROWSER: boolean; HAS_WINDOW: boolean; version: number; rt: _xarcV2RunTimeInfo; // run time info /** * Initialize CDN mapping * * @param data - data to initialize with */ cdnInit(data: CDNData): void; /** * Add CDN mapping data from data into the CDN mapping for looking up assets * * @param data - CDN data * @param replace - replace existing entry? */ cdnUpdate(data: CDNData, replace: boolean): void; /** * Map an asset name to its CDN version * * @param name - asset name to map */ cdnMap(name: string): string; getOnLoadStart(name: string): any[]; addOnLoadStart(name: string, load: any): void; startSubAppOnLoad(options: any, data: any): void; start(): Promise<any>; _start(ignore: string[], callDepth: number): Promise<any>; /** * Need this for node.js. While chrome dev tools allow setting console level, node.js' * console.debug is just an alias for console.log. */ debug(...args: any[]): void; /** * Extract JSON data from a script tag * * @param id - script element id * @returns the data extracted */ dyn(id: string): unknown; } /** * Options for calling the `declareSubApp` API. * * To see example of implement and declare a subapp, see a framework specific * SubApp implementation type, such as `ReactSubApp`. */ export type SubAppOptions = { /** * Name of the subapp * * - This will be used to name the JS bundle * - It must follow valid filename format, avoid space and special characters * */ name: string; /** * The dynamic import promise for the subapp's module, or a function that returns it */ getModule: Promise<any> | (() => Promise<any>); /** * The name of the export for the subapp from the module. * * - default to `subapp` * - then `default` * - If it's `false`, then this subapp is treated as having no UI logic. * */ resolveName?: string | false; /** * _optional_ webpack bundle name for the subapp * * - By default, xarc will create one like `"subapp-<name>"` * - Use this if you want to override it, such as to combine multiple subapps * a single bundle. */ bundleName?: string; /** * Extra features that the subapp wants. Should be initialized with the feature provider function * * - The intent is to allow a module to provide one or more features for a subapp. * * - Typically the feature needs to have implementation for server and client side, and exposed * through the main/browser fields in package.json. * * - The feature is access through an API function. The API should return another * function to be called by the subapp system later, and the subapp's info will be * passed. */ wantFeatures?: SubAppFeatureFactory[]; /** * File name of the module that declares the subapp. * * - Only required for server side rendering (SSR). * - Typically just set it to `__filename`, which webpack set to `"/<file>"` for client side bundle. * - If not set, then xarc will figure it out through webpack compiling. * - But webpack compiling is not 100%, so setting it yourself guarantees it. * */ __filename?: string; }; /** * SubApp client side rendering data * * @remark * Internal use */ export type SubAppCSRData = LoadSubAppOptions & { element?: Element; elementId?: string; getInitialState?(): any; }; /** * Parameters for starting a subapp * * @remark * Internal use */ export type SubAppStartParams = { /** server side render data */ ssrData?: SubAppSSRData; /** client side render data */ csrData?: SubAppCSRData; }; /** * Subapp rendering pipeline factory parameters * * @remark * Internal use * * */ export type PipelineFactoryParams = SubAppStartParams; /** * definition of a subapp from `declareSubApp` * * To see example of implement and declare a subapp, see a framework specific * SubApp implementation type, such as `ReactSubApp`. * * */ export type SubAppDef = SubAppOptions & { /** * Unique definition ID, if a subapp with same name is re-declared then it will have a diff _id */ _id: number; /** * handle loading the subapp's module */ _getModule: () => Promise<any>; /** * The module that implements the subapp */ _module: any; /** * Indicate if this subapp involves being used in any server side rendering * TODO: this is not the right place for this? Since different routes could be using the * same subapp def but not for SSR. */ _ssr: boolean; /** * SubApp's start method that declareSubApp will create, with versions * for browser or node.js. * * - Browser: the browser subapp shell will call this from start. * - Node.js: load-v2.ts in node dir will call this during SSR. * * @param options */ _start?(params: SubAppStartParams, reload?: boolean): Promise<any>; /** * Handles HMR on client side * * @param subAppName * @param modName */ _reload?(subAppName: string, modName?: string): Promise<any>; /** * Features this subapp wants */ _features?: Record<string, SubAppFeature>; /** * Create a render pipeline * * The respective env/framework specific implementation should set this accordingly */ _pipelineFactory?: (params: PipelineFactoryParams) => SubAppRenderPipeline; /** * factory to return a framework object for the running env. it's unknown because we don't know * what the env or the framework could be. */ _frameworkFactory?: () => unknown; /** For UI component instance to let the subapp know it's mounting to the subapp */ _mount?(info: SubAppMountInfo): void; /** For UI component instance to let the subapp know it's unmounting from the subapp */ _unmount?(info: SubAppMountInfo): void; /** * Holds rendering pipeline instances for this subapp. * * This is only used on client side. On server side, there are multiple page rendering for * multiple requests. We need to maintain and manage the pipelines for each request. So * they are stored in their owning request object. */ _renderPipelines?: SubAppRenderPipeline[]; /** * Get the export subapp object from the module */ _getExport?: <T>() => SubApp<T>; }; /** * Declare what info a subapp feature should have * * @remark * Internal use * * */ export type SubAppFeatureInfo = { /** * Unique ID to identify the feature. There could be multiple implementations of a feature */ id: string; /** * sub id to identify a particular implementation of a feature. * */ subId?: string; }; /** * Declare a subapp feature factory * * @remark * Internal use * * */ export interface ISubAppFeatureFactory { /** * Function to add the feature to a subapp definition */ add: (subappDef: SubAppDef) => SubAppDef; } /** * The factory type for a subapp feature. * * A subapp feature should export a factory for creating the feature. * * @remark * Internal use * * */ export type SubAppFeatureFactory = ISubAppFeatureFactory & SubAppFeatureInfo; /** * The result type a subapp feature execution should return. */ export type SubAppFeatureResult = { Component?: any; props?: any; }; /** * Parameters for a subapp feature execution */ export type SubAppFeatureExecuteParams = { input: SubAppFeatureResult; ssrData?: SubAppSSRData; csrData?: SubAppCSRData; reload?: boolean; }; /** * subapp feature interface. All subapp features need to implement this interface. */ export interface ISubAppFeature { /** * execute the feature for the subapp */ execute(param: SubAppFeatureExecuteParams): SubAppFeatureResult | Promise<SubAppFeatureResult>; } /** * The type for a subapp feature implementation. */ export type SubAppFeature = ISubAppFeature & SubAppFeatureInfo; /** * Options for loading a subapp into a page * * The subapp should've been declared. */ export type LoadSubAppOptions = { /** * Name of the subapp to load */ name: string; /** * Enable server side rendering for the subapp */ ssr?: boolean; /** * If SSR, set this to `true` to prepare subapp's data only but don't actually do render to string. */ prepareOnly?: boolean; /** * ID for the subapp inlined as a component. * * For now, any non-empty string ID will do. */ inlineId?: string; /** namespace to load subapp into. **Default** `"ns0"` */ namespace?: string; /** * group the subapp belongs to */ group?: string; }; /** * Type of Component that's mounting a subapp * * - `dynamic` - using subapp as a plain dynamic import component * - `inline` - inline nesting a subapp within another as a component * - `start` - as a start component for the subapp to handle hot reload * */ export type MountType = "dynamic" | "inline" | "start"; /** * For a UI component to let the subapp know it has mount itself for the subapp */ export type SubAppMountInfo = { /** The UI component instance that's mount to the subapp */ component: any; /** The subapp that the UI component instance mount to */ subapp: SubAppDef; /** type of component trying to mount to the subapp */ type?: MountType; }; /** * Base type for a generic implementation of a SubApp. * * An actual subapp implementation should use a type derived from this for a specific * framework. For example, `ReactSubApp` for React. */ export type SubApp<ComponentType> = { /** * The component for this subapp. * * If it's undefined, then this subapp is treated to have no UI component * */ Component?: ComponentType; /** * Extra features that the subapp wants. Should be initialized with the feature provider function * * - The intent is to allow a module to provide one or more features for a subapp. * * - Typically the feature needs to have implementation for server and client side, and exposed * through the main/browser fields in package.json. * * - The feature is access through an API function. The API should return another * function to be called by the subapp system later, and the subapp's info will be * passed. */ wantFeatures?: SubAppFeatureFactory[]; }; /** * container of declared subapps * * @remark * Internal use */ export class SubAppContainer { readyCount: number; declareCount: number; $: Record<string, SubAppDef>; constructor(store: Record<string, SubAppDef>) { this.readyCount = this.declareCount = 0; this.$ = store; } get(name: string): SubAppDef { return this.$[name]; } declare(name: string, subapp: SubAppDef): SubAppDef { this.$[name] = subapp; this.declareCount = this.getNames().length; this.updateReady(); return subapp; } isReady(): boolean { return this.readyCount === this.declareCount; } updateReady(): void { this.readyCount = 0; for (const name in this.$) { if (this.$[name]._module) { this.readyCount++; } } } getNames(): string[] { return Object.keys(this.$); } } /** * potential data for doing server side rendering */ export type SubAppSSRData = { /** * RenderContext from `@xarc/render-context` * * TODO: need to type this */ context: any; subapp: SubAppDef; options: LoadSubAppOptions; request?: any; path?: string; params?: Record<string, string>; query?: Record<string, string>; }; /** * Implement a subapp feature decorator * * The behavior of the decorator will be very specific to the internals of the feature * it decorated. */ export interface FeatureDecorator<TF = unknown, TP = unknown, TR = void> { decorate(feature: TF, params: TP): TR; }
the_stack
import * as dom from 'vs/base/browser/dom'; import { createFastDomNode, FastDomNode } from 'vs/base/browser/fastDomNode'; import { GlobalPointerMoveMonitor, IPointerMoveEventData, standardPointerMoveMerger } from 'vs/base/browser/globalPointerMoveMonitor'; import { StandardWheelEvent } from 'vs/base/browser/mouseEvent'; import { ScrollbarArrow, ScrollbarArrowOptions } from 'vs/base/browser/ui/scrollbar/scrollbarArrow'; import { ScrollbarState } from 'vs/base/browser/ui/scrollbar/scrollbarState'; import { ScrollbarVisibilityController } from 'vs/base/browser/ui/scrollbar/scrollbarVisibilityController'; import { Widget } from 'vs/base/browser/ui/widget'; import * as platform from 'vs/base/common/platform'; import { INewScrollPosition, Scrollable, ScrollbarVisibility } from 'vs/base/common/scrollable'; /** * The orthogonal distance to the slider at which dragging "resets". This implements "snapping" */ const POINTER_DRAG_RESET_DISTANCE = 140; export interface ISimplifiedPointerEvent { buttons: number; pageX: number; pageY: number; } export interface ScrollbarHost { onMouseWheel(mouseWheelEvent: StandardWheelEvent): void; onDragStart(): void; onDragEnd(): void; } export interface AbstractScrollbarOptions { lazyRender: boolean; host: ScrollbarHost; scrollbarState: ScrollbarState; visibility: ScrollbarVisibility; extraScrollbarClassName: string; scrollable: Scrollable; scrollByPage: boolean; } export abstract class AbstractScrollbar extends Widget { protected _host: ScrollbarHost; protected _scrollable: Scrollable; protected _scrollByPage: boolean; private _lazyRender: boolean; protected _scrollbarState: ScrollbarState; protected _visibilityController: ScrollbarVisibilityController; private _pointerMoveMonitor: GlobalPointerMoveMonitor; public domNode: FastDomNode<HTMLElement>; public slider!: FastDomNode<HTMLElement>; protected _shouldRender: boolean; constructor(opts: AbstractScrollbarOptions) { super(); this._lazyRender = opts.lazyRender; this._host = opts.host; this._scrollable = opts.scrollable; this._scrollByPage = opts.scrollByPage; this._scrollbarState = opts.scrollbarState; this._visibilityController = this._register(new ScrollbarVisibilityController(opts.visibility, 'visible scrollbar ' + opts.extraScrollbarClassName, 'invisible scrollbar ' + opts.extraScrollbarClassName)); this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()); this._pointerMoveMonitor = this._register(new GlobalPointerMoveMonitor()); this._shouldRender = true; this.domNode = createFastDomNode(document.createElement('div')); this.domNode.setAttribute('role', 'presentation'); this.domNode.setAttribute('aria-hidden', 'true'); this._visibilityController.setDomNode(this.domNode); this.domNode.setPosition('absolute'); this._register(dom.addDisposableListener(this.domNode.domNode, dom.EventType.POINTER_DOWN, (e: PointerEvent) => this._domNodePointerDown(e))); } // ----------------- creation /** * Creates the dom node for an arrow & adds it to the container */ protected _createArrow(opts: ScrollbarArrowOptions): void { const arrow = this._register(new ScrollbarArrow(opts)); this.domNode.domNode.appendChild(arrow.bgDomNode); this.domNode.domNode.appendChild(arrow.domNode); } /** * Creates the slider dom node, adds it to the container & hooks up the events */ protected _createSlider(top: number, left: number, width: number | undefined, height: number | undefined): void { this.slider = createFastDomNode(document.createElement('div')); this.slider.setClassName('slider'); this.slider.setPosition('absolute'); this.slider.setTop(top); this.slider.setLeft(left); if (typeof width === 'number') { this.slider.setWidth(width); } if (typeof height === 'number') { this.slider.setHeight(height); } this.slider.setLayerHinting(true); this.slider.setContain('strict'); this.domNode.domNode.appendChild(this.slider.domNode); this._register(dom.addDisposableListener( this.slider.domNode, dom.EventType.POINTER_DOWN, (e: PointerEvent) => { if (e.button === 0) { e.preventDefault(); this._sliderPointerDown(e); } } )); this.onclick(this.slider.domNode, e => { if (e.leftButton) { e.stopPropagation(); } }); } // ----------------- Update state protected _onElementSize(visibleSize: number): boolean { if (this._scrollbarState.setVisibleSize(visibleSize)) { this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()); this._shouldRender = true; if (!this._lazyRender) { this.render(); } } return this._shouldRender; } protected _onElementScrollSize(elementScrollSize: number): boolean { if (this._scrollbarState.setScrollSize(elementScrollSize)) { this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()); this._shouldRender = true; if (!this._lazyRender) { this.render(); } } return this._shouldRender; } protected _onElementScrollPosition(elementScrollPosition: number): boolean { if (this._scrollbarState.setScrollPosition(elementScrollPosition)) { this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()); this._shouldRender = true; if (!this._lazyRender) { this.render(); } } return this._shouldRender; } // ----------------- rendering public beginReveal(): void { this._visibilityController.setShouldBeVisible(true); } public beginHide(): void { this._visibilityController.setShouldBeVisible(false); } public render(): void { if (!this._shouldRender) { return; } this._shouldRender = false; this._renderDomNode(this._scrollbarState.getRectangleLargeSize(), this._scrollbarState.getRectangleSmallSize()); this._updateSlider(this._scrollbarState.getSliderSize(), this._scrollbarState.getArrowSize() + this._scrollbarState.getSliderPosition()); } // ----------------- DOM events private _domNodePointerDown(e: PointerEvent): void { if (e.target !== this.domNode.domNode) { return; } this._onPointerDown(e); } public delegatePointerDown(e: PointerEvent): void { const domTop = this.domNode.domNode.getClientRects()[0].top; const sliderStart = domTop + this._scrollbarState.getSliderPosition(); const sliderStop = domTop + this._scrollbarState.getSliderPosition() + this._scrollbarState.getSliderSize(); const pointerPos = this._sliderPointerPosition(e); if (sliderStart <= pointerPos && pointerPos <= sliderStop) { // Act as if it was a pointer down on the slider if (e.button === 0) { e.preventDefault(); this._sliderPointerDown(e); } } else { // Act as if it was a pointer down on the scrollbar this._onPointerDown(e); } } private _onPointerDown(e: PointerEvent): void { let offsetX: number; let offsetY: number; if (e.target === this.domNode.domNode && typeof e.offsetX === 'number' && typeof e.offsetY === 'number') { offsetX = e.offsetX; offsetY = e.offsetY; } else { const domNodePosition = dom.getDomNodePagePosition(this.domNode.domNode); offsetX = e.pageX - domNodePosition.left; offsetY = e.pageY - domNodePosition.top; } const offset = this._pointerDownRelativePosition(offsetX, offsetY); this._setDesiredScrollPositionNow( this._scrollByPage ? this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(offset) : this._scrollbarState.getDesiredScrollPositionFromOffset(offset) ); if (e.button === 0) { // left button e.preventDefault(); this._sliderPointerDown(e); } } private _sliderPointerDown(e: PointerEvent): void { if (!e.target || !(e.target instanceof Element)) { return; } const initialPointerPosition = this._sliderPointerPosition(e); const initialPointerOrthogonalPosition = this._sliderOrthogonalPointerPosition(e); const initialScrollbarState = this._scrollbarState.clone(); this.slider.toggleClassName('active', true); this._pointerMoveMonitor.startMonitoring( e.target, e.pointerId, e.buttons, standardPointerMoveMerger, (pointerMoveData: IPointerMoveEventData) => { const pointerOrthogonalPosition = this._sliderOrthogonalPointerPosition(pointerMoveData); const pointerOrthogonalDelta = Math.abs(pointerOrthogonalPosition - initialPointerOrthogonalPosition); if (platform.isWindows && pointerOrthogonalDelta > POINTER_DRAG_RESET_DISTANCE) { // The pointer has wondered away from the scrollbar => reset dragging this._setDesiredScrollPositionNow(initialScrollbarState.getScrollPosition()); return; } const pointerPosition = this._sliderPointerPosition(pointerMoveData); const pointerDelta = pointerPosition - initialPointerPosition; this._setDesiredScrollPositionNow(initialScrollbarState.getDesiredScrollPositionFromDelta(pointerDelta)); }, () => { this.slider.toggleClassName('active', false); this._host.onDragEnd(); } ); this._host.onDragStart(); } private _setDesiredScrollPositionNow(_desiredScrollPosition: number): void { const desiredScrollPosition: INewScrollPosition = {}; this.writeScrollPosition(desiredScrollPosition, _desiredScrollPosition); this._scrollable.setScrollPositionNow(desiredScrollPosition); } public updateScrollbarSize(scrollbarSize: number): void { this._updateScrollbarSize(scrollbarSize); this._scrollbarState.setScrollbarSize(scrollbarSize); this._shouldRender = true; if (!this._lazyRender) { this.render(); } } public isNeeded(): boolean { return this._scrollbarState.isNeeded(); } // ----------------- Overwrite these protected abstract _renderDomNode(largeSize: number, smallSize: number): void; protected abstract _updateSlider(sliderSize: number, sliderPosition: number): void; protected abstract _pointerDownRelativePosition(offsetX: number, offsetY: number): number; protected abstract _sliderPointerPosition(e: ISimplifiedPointerEvent): number; protected abstract _sliderOrthogonalPointerPosition(e: ISimplifiedPointerEvent): number; protected abstract _updateScrollbarSize(size: number): void; public abstract writeScrollPosition(target: INewScrollPosition, scrollPosition: number): void; }
the_stack
import type { DeviceOverallStatus } from './device-overall-status'; export type { DeviceOverallStatus } from './device-overall-status'; import { Contract } from './contract'; import { JWTUser } from './jwt'; import type { PineDeferred, NavigationResource, OptionalNavigationResource, ReverseNavigationResource, } from '../../typings/pinejs-client-core'; // TODO: Drop in the next major export { SocialServiceAccount } from './jwt'; export interface ResourceTypeMap { api_key: ApiKey; application: Application; application__can_use__application_as_host: ApplicationHostedOnApplication; application_config_variable: ApplicationVariable; application_environment_variable: ApplicationVariable; application_membership_role: ApplicationMembershipRole; application_tag: ApplicationTag; application_type: ApplicationType; build_environment_variable: BuildVariable; cpu_architecture: CpuArchitecture; device: Device; device_config_variable: DeviceVariable; device_environment_variable: DeviceVariable; device_service_environment_variable: DeviceServiceEnvironmentVariable; device_tag: DeviceTag; device_type: DeviceType; feature: Feature; gateway_download: GatewayDownload; image: Image; image_install: ImageInstall; invitee: Invitee; invitee__is_invited_to__application: ApplicationInvite; invitee__is_invited_to__organization: OrganizationInvite; /** @deprecated */ my_application: Application; organization: Organization; organization__has_private_access_to__device_type: OrganizationPrivateDeviceTypeAccess; organization_membership: OrganizationMembership; organization_membership_role: OrganizationMembershipRole; organization_membership_tag: OrganizationMembershipTag; plan: Plan; plan__has__discount_code: PlanDiscountCode; plan_addon: PlanAddon; plan_feature: PlanFeature; public_organization: PublicOrganization; public_device: PublicDevice; recovery_two_factor: RecoveryTwoFactor; release: Release; release_tag: ReleaseTag; service: Service; service_environment_variable: ServiceEnvironmentVariable; service_install: ServiceInstall; service_instance: ServiceInstance; subscription: Subscription; subscription_addon_discount: SubscriptionAddonDiscount; subscription_prepaid_addon: SubscriptionPrepaidAddon; supervisor_release: SupervisorRelease; support_feature: SupportFeature; support_tier: SupportTier; team: Team; team_application_access: TeamApplicationAccess; team_membership: TeamMembership; user: User; user__has__public_key: SSHKey; user__has_direct_access_to__application: UserHasDirectAccessToApplication; /** @deprecated in favor of user_application_membership */ user__is_member_of__application: ApplicationMembership; user_application_membership: ApplicationMembership; } export interface Organization { id: number; created_at: string; name: string; handle: string; has_past_due_invoice_since__date: string | null; application: ReverseNavigationResource<Application>; /** includes__organization_membership */ organization_membership: ReverseNavigationResource<OrganizationMembership>; owns__team: ReverseNavigationResource<Team>; organization__has_private_access_to__device_type: ReverseNavigationResource<OrganizationPrivateDeviceTypeAccess>; } export interface Team { id: number; created_at: string; name: string; belongs_to__organization: NavigationResource<Organization>; /** includes__user */ team_membership: ReverseNavigationResource<TeamMembership>; /** grants_access_to__application */ team_application_access: ReverseNavigationResource<TeamApplicationAccess>; } export interface RecoveryTwoFactor { id: number; used_timestamp: string | null; belongs_to__user: NavigationResource<User>; } // TODO: Stop (confusingly) extending the UserJWT in the next major version export interface User extends JWTUser { id: number; actor: number; created_at: string; username: string; organization_membership: ReverseNavigationResource<OrganizationMembership>; /** @deprecated in favor of user_application_membership */ user__is_member_of__application: ReverseNavigationResource<ApplicationMembership>; user_application_membership: ReverseNavigationResource<ApplicationMembership>; team_membership: ReverseNavigationResource<TeamMembership>; has_direct_access_to__application: ReverseNavigationResource<Application>; } export type OrganizationMembershipRoles = 'administrator' | 'member'; export interface OrganizationMembershipRole { id: number; name: OrganizationMembershipRoles; } export interface OrganizationMembership { id: number; created_at: string; user: NavigationResource<User>; /** organization */ is_member_of__organization: NavigationResource<Organization>; organization_membership_role: NavigationResource<OrganizationMembershipRole>; effective_seat_role: string; organization_membership_tag: ReverseNavigationResource<OrganizationMembershipTag>; } export interface TeamMembership { id: number; created_at: string; user: NavigationResource<User>; /** team */ is_member_of__team: NavigationResource<Team>; } export interface ApiKey { id: number; created_at: string; name: string; description: string | null; is_of__actor: PineDeferred; } export interface Application { id: number; created_at: string; app_name: string; actor: number; slug: string; uuid: string; is_accessible_by_support_until__date: string; is_host: boolean; should_track_latest_release: boolean; is_public: boolean; is_of__class: 'fleet' | 'block' | 'app'; is_archived: boolean; is_discoverable: boolean; is_stored_at__repository_url: string | null; public_organization: OptionalNavigationResource<PublicOrganization>; application_type: NavigationResource<ApplicationType>; is_for__device_type: NavigationResource<DeviceType>; depends_on__application: OptionalNavigationResource<Application>; organization: NavigationResource<Organization>; should_be_running__release: OptionalNavigationResource<Release>; application_config_variable: ReverseNavigationResource<ApplicationVariable>; application_environment_variable: ReverseNavigationResource<ApplicationVariable>; build_environment_variable: ReverseNavigationResource<BuildVariable>; application_tag: ReverseNavigationResource<ApplicationTag>; owns__device: ReverseNavigationResource<Device>; owns__public_device: ReverseNavigationResource<PublicDevice>; owns__release: ReverseNavigationResource<Release>; is_depended_on_by__application: ReverseNavigationResource<Application>; is_directly_accessible_by__user: ReverseNavigationResource<User>; /** includes__user */ /** @deprecated in favor of user_application_membership */ user__is_member_of__application: ReverseNavigationResource<ApplicationMembership>; user_application_membership: ReverseNavigationResource<ApplicationMembership>; /** is_accessible_by__team */ team_application_access: ReverseNavigationResource<TeamApplicationAccess>; } export interface UserHasDirectAccessToApplication { id: number; user: NavigationResource<User>; has_direct_access_to__application: NavigationResource<Application>; } export interface PublicOrganization { id: number; name: string; handle: string; } export interface PublicDevice { // TODO: improve the custom pine client rypings to support resources w/o an id field id: undefined; latitude: string; longitude: string; belongs_to__application: NavigationResource<Application>; is_of__device_type: NavigationResource<DeviceType>; was_recently_online: boolean; } export interface Invitee { id: number; created_at: string; email: string; } export interface ApplicationInvite { id: number; message?: string; created_at: string; invitationToken: string; application_membership_role: NavigationResource<ApplicationMembershipRole>; invitee: NavigationResource<Invitee>; is_invited_to__application: NavigationResource<Application>; } export interface OrganizationInvite { id: number; message?: string; created_at: string; invitationToken: string; organization_membership_role: NavigationResource<OrganizationMembershipRole>; invitee: NavigationResource<Invitee>; is_invited_to__organization: NavigationResource<Organization>; } export interface ApplicationType { id: number; name: string; slug: string; description: string | null; supports_gateway_mode: boolean; supports_multicontainer: boolean; supports_web_url: boolean; is_legacy: boolean; requires_payment: boolean; needs__os_version_range: string | null; maximum_device_count: number | null; } export interface ApplicationHostedOnApplication { id: null; application: NavigationResource<Application>; can_use__application_as_host: NavigationResource<Application>; } export type ApplicationMembershipRoles = 'developer' | 'operator' | 'observer'; export interface ApplicationMembershipRole { id: number; name: ApplicationMembershipRoles; } export interface ApplicationMembership { id: number; user: NavigationResource<User>; /** application */ is_member_of__application: NavigationResource<Application>; application_membership_role: NavigationResource<ApplicationMembershipRole>; } export interface TeamApplicationAccess { id: number; team: NavigationResource<Team>; /** application */ grants_access_to__application: NavigationResource<Application>; application_membership_role: NavigationResource<ApplicationMembershipRole>; } export type ReleaseStatus = | 'cancelled' | 'error' | 'failed' | 'interrupted' | 'local' | 'running' | 'success' | 'timeout' | null; export interface ReleaseVersion { raw: string; major: number; minor: number; patch: number; version: string; build: ReadonlyArray<string>; prerelease: ReadonlyArray<string | number>; } export interface Release { id: number; created_at: string; commit: string; composition: string | null; contract: string | null; status: ReleaseStatus; source: string; build_log: string | null; is_invalidated: boolean; start_timestamp: string; update_timestamp: string | null; end_timestamp: string; /** @deprecated */ release_version: string | null; semver: string; semver_major: number; semver_minor: number; semver_patch: number; revision: number | null; known_issue_list: string | null; /** This is a computed term */ version: ReleaseVersion; is_final: boolean; is_finalized_at__date: string | null; is_created_by__user: OptionalNavigationResource<User>; belongs_to__application: NavigationResource<Application>; contains__image: ReverseNavigationResource<{ id: number; image: NavigationResource<Image>; }>; should_be_running_on__application: ReverseNavigationResource<Application>; is_running_on__device: ReverseNavigationResource<Device>; should_be_running_on__device: ReverseNavigationResource<Device>; release_tag: ReverseNavigationResource<ReleaseTag>; } export interface Device { id: number; created_at: string; modified_at: string; custom_latitude?: string; custom_longitude?: string; device_name: string; download_progress?: number; ip_address: string | null; public_address: string | null; mac_address: string | null; is_accessible_by_support_until__date: string | null; is_connected_to_vpn: boolean; /** @deprecate */ is_in_local_mode?: boolean; is_locked_until__date: string; is_web_accessible: boolean; is_active: boolean; is_online: boolean; last_connectivity_event: string | null; last_vpn_event: string; latitude?: string; local_id?: string; location: string; longitude?: string; note: string; os_variant?: string; os_version: string | null; provisioning_progress?: number; provisioning_state: string; state?: { key: string; name: string }; status: string; status_sort_index?: number; supervisor_version: string; uuid: string; vpn_address: string | null; api_heartbeat_state: 'online' | 'offline' | 'timeout' | 'unknown'; memory_usage: number | null; memory_total: number | null; storage_block_device: string | null; storage_usage: number | null; storage_total: number | null; cpu_usage: number | null; cpu_temp: number | null; cpu_id: string | null; is_undervolted: boolean; /** This is a computed term */ overall_status: DeviceOverallStatus; /** This is a computed term */ overall_progress: number | null; is_of__device_type: NavigationResource<DeviceType>; // the schema has this as a nullable, but for simplicity we have it as non-optional belongs_to__application: NavigationResource<Application>; belongs_to__user: OptionalNavigationResource<User>; is_running__release: OptionalNavigationResource<Release>; should_be_running__release: OptionalNavigationResource<Release>; is_managed_by__service_instance: OptionalNavigationResource<ServiceInstance>; is_managed_by__device: OptionalNavigationResource<Device>; should_be_managed_by__supervisor_release: OptionalNavigationResource<SupervisorRelease>; device_config_variable: ReverseNavigationResource<DeviceVariable>; device_environment_variable: ReverseNavigationResource<DeviceVariable>; device_tag: ReverseNavigationResource<DeviceTag>; manages__device: ReverseNavigationResource<Device>; service_install: ReverseNavigationResource<ServiceInstall>; image_install?: ReverseNavigationResource<ImageInstall>; gateway_download?: ReverseNavigationResource<GatewayDownload>; } export interface CpuArchitecture { id: number; slug: string; is_supported_by__device_type: ReverseNavigationResource<CpuArchitecture>; } export interface DeviceType { id: number; slug: string; name: string; is_private: boolean; logo: string | null; contract: Contract | null; belongs_to__device_family: OptionalNavigationResource<DeviceFamily>; is_default_for__application: ReverseNavigationResource<Application>; is_of__cpu_architecture: NavigationResource<CpuArchitecture>; is_accessible_privately_by__organization: ReverseNavigationResource<Organization>; describes_device: ReverseNavigationResource<Device>; } export interface DeviceFamily { created_at: string; modified_at: string; id: number; slug: string; name: string; is_manufactured_by__device_manufacturer: OptionalNavigationResource<DeviceManufacturer>; } export interface DeviceManufacturer { created_at: string; modified_at: string; id: number; slug: string; name: string; } export interface OrganizationPrivateDeviceTypeAccess { id: number; organization: NavigationResource<Organization>; has_private_access_to__device_type: NavigationResource<DeviceType>; } export type DeviceWithImageInstalls = Device & Required<Pick<Device, 'image_install' | 'gateway_download'>>; export interface SupervisorRelease { created_at: string; id: number; supervisor_version: string; image_name: string; is_public: boolean; note?: string; is_for__device_type: NavigationResource<DeviceType>; } export interface ServiceInstance { id: number; created_at: string; service_type: string; ip_address: string; last_heartbeat: string; } export interface Service { id: number; created_at: string; service_name: string; application: NavigationResource<Application>; is_built_by__image: ReverseNavigationResource<Image>; service_environment_variable: ReverseNavigationResource<ServiceEnvironmentVariable>; device_service_environment_variable: ReverseNavigationResource<DeviceServiceEnvironmentVariable>; } export interface Image { id: number; created_at: string; build_log: string; contract: string | null; content_hash?: string | null; project_type?: string | null; status: string; is_stored_at__image_location: string; start_timestamp?: string | null; end_timestamp?: string | null; push_timestamp?: string | null; image_size?: number | null; dockerfile: string; error_message?: string | null; is_a_build_of__service: NavigationResource<Service>; release_image: ReverseNavigationResource<ReleaseImage>; } export interface ReleaseImage { id: number; created_at: string; image: NavigationResource<Image>; is_part_of__release: NavigationResource<Release>; } export interface SSHKey { title: string; public_key: string; id: number; created_at: string; user: NavigationResource<User>; } export interface ImageInstall { id: number; download_progress: number | null; status: string; install_date: string; /** @deprecated Use `installs__image` instead. */ image: NavigationResource<Image>; installs__image: NavigationResource<Image>; device: NavigationResource<Device>; is_provided_by__release: NavigationResource<Release>; } export interface GatewayDownload { id: number; download_progress: number; status: string; image: NavigationResource<Image>; is_downloaded_by__device: NavigationResource<Device>; } export interface ServiceInstall { id: number; should_be_running: boolean; device: NavigationResource<Device>; /** service */ installs__service: NavigationResource<Service>; application: NavigationResource<Application>; device_service_environment_variable: ReverseNavigationResource<DeviceServiceEnvironmentVariable>; } export interface EnvironmentVariableBase { id: number; name: string; value: string; } export interface DeviceServiceEnvironmentVariable extends EnvironmentVariableBase { service_install: NavigationResource<ServiceInstall>; } export interface ServiceEnvironmentVariable extends EnvironmentVariableBase { service: NavigationResource<Service>; } export interface DeviceVariable extends EnvironmentVariableBase { device: NavigationResource<Device>; } export interface ApplicationVariable extends EnvironmentVariableBase { application: NavigationResource<Application>; } export interface BuildVariable extends EnvironmentVariableBase { application: NavigationResource<Application>; } export interface ResourceTagBase { id: number; tag_key: string; value: string; } export interface ApplicationTag extends ResourceTagBase { application: NavigationResource<Application>; } export interface DeviceTag extends ResourceTagBase { device: NavigationResource<Device>; } export interface OrganizationMembershipTag extends ResourceTagBase { organization_membership: NavigationResource<OrganizationMembership>; } export interface ReleaseTag extends ResourceTagBase { release: NavigationResource<Release>; } // Billing model export interface Feature { id: number; title: string; slug: string; billing_code: string | null; } export interface SupportFeature { id: number; feature: number; support_tier: NavigationResource<SupportTier>; } export interface SupportTier { id: number; title: string; slug: string; includes_private_support: boolean; includes__SLA?: string; } export interface Plan { id: number; title: string; billing_code: string | null; monthly_price: number; annual_price: number; can_self_serve: boolean; is_legacy: boolean; plan_feature: ReverseNavigationResource<PlanFeature>; offers__plan_addon: ReverseNavigationResource<PlanAddon>; plan__has__discount_code: ReverseNavigationResource<PlanDiscountCode>; } export interface PlanAddon { id: number; base_price: number; can_self_serve: boolean; bills_dynamically: boolean; offers__feature: NavigationResource<Feature>; } export interface PlanDiscountCode { id: number; discount_code: string; plan: NavigationResource<Plan>; } export interface PlanFeature { id: number; quantity: number; provides__feature: NavigationResource<Feature>; } export type SubscriptionBillingCycle = | 'monthly' | 'quarterly' | 'biannual' | 'annual' | 'biennial' | 'triennial' | 'quadrennial' | 'quinquennial'; export interface Subscription { id: number; starts_on__date: string; ends_on__date: string | null; discount_percentage: number; billing_cycle: SubscriptionBillingCycle; origin: string; is_active: boolean; is_for__organization: NavigationResource<Organization>; is_for__plan: NavigationResource<Plan>; subscription_addon_discount: ReverseNavigationResource<SubscriptionAddonDiscount>; /** @deprecated */ discounts__plan_addon: ReverseNavigationResource<SubscriptionAddonDiscount>; subscription_prepaid_addon: ReverseNavigationResource<SubscriptionPrepaidAddon>; } export interface SubscriptionPrepaidAddon { id: number; discount_percentage: number; quantity: number; starts_on__date: string; expires_on__date: string | null; is_for__plan_addon: NavigationResource<PlanAddon>; is_for__subscription: NavigationResource<Subscription>; } export interface SubscriptionAddonDiscount { id: number; discount_percentage: number; discounts__plan_addon: NavigationResource<PlanAddon>; }
the_stack
import { keyValue } from '../../storage'; import * as CONSTANTS from '../../constants'; export class Data { private readonly store: typeof keyValue; constructor(store: typeof keyValue = keyValue) { this.store = store; } public async clearAll(): Promise<void> { await this.store.set('params.applicationCode', undefined); await this.store.set('params.hwid', undefined); await this.store.set('params.deviceType', undefined); await this.store.set('params.deviceModel', undefined); await this.store.set('params.language', undefined); await this.store.set('params.apiEntrypoint', undefined); await this.store.set('params.tokens', undefined); await this.store.set('params.applicationServerKey', undefined); await this.store.set('params.senderId', undefined); await this.store.set('params.webSitePushId', undefined); await this.store.set('params.defaultNotificationImage', undefined); await this.store.set('params.defaultNotificationTitle', undefined); await this.store.set('params.userId', undefined); await this.store.set('params.userIdWasChanged', undefined); await this.store.set('params.isLastPermissionStatus', undefined); await this.store.set('params.isManualUnsubscribed', undefined); await this.store.set('params.isCommunicationDisabled', undefined); await this.store.set('params.isDropAllData', undefined); await this.store.set('params.sdkVersion', undefined); await this.store.set('params.serviceWorkerVersion', undefined); await this.store.set('params.serviceWorkerUrl', undefined); await this.store.set('params.serviceWorkerScope', undefined); await this.store.set('params.lastOpenMessage', undefined); await this.store.set('params.lastOpenApplicationTime', undefined); await this.store.set('params.features', undefined); await this.store.set('params.init', undefined); await this.store.set('API_PARAMS', undefined); await this.store.set('SENDER_ID', undefined); await this.store.set('COMMUNICATION_ENABLED', undefined); await this.store.set('DEVICE_DATA_REMOVED', undefined); await this.store.set('LAST_OPEN_MESSAGE', undefined); await this.store.set('DELAYED_EVENT', undefined); } public async setApplicationCode(application: string): Promise<void> { await this.store.set('params.applicationCode', application); } public async getApplicationCode(): Promise<string> { return await this.store.get('params.applicationCode'); } public async setHwid(hwid: string): Promise<void> { await this.store.set('params.hwid', hwid); } public async getHwid(): Promise<string> { return await this.store.get('params.hwid'); } public async setDeviceType(type: number): Promise<void> { await this.store.set('params.deviceType', type); } public async getDeviceType(): Promise<number> { return await this.store.get('params.deviceType'); } public async setDeviceModel(model: string): Promise<void> { await this.store.set('params.deviceModel', model); } public async getDeviceModel(): Promise<string> { return await this.store.get('params.deviceModel'); } public async setLanguage(language: string): Promise<void> { await this.store.set('params.language', language); } public async getLanguage(): Promise<string> { return await this.store.get('params.language', 'en'); } public async setApiEntrypoint(url: string): Promise<void> { await this.store.set('params.apiEntrypoint', url); } public async getApiEntrypoint(): Promise<string> { return await this.store.get('params.apiEntrypoint', CONSTANTS.DEFAULT_API_URL); } public async setTokens(tokens: any): Promise<void> { // old key in indexed db // if old service worker or old sdk const hwid = await this.getHwid(); await this.store.set('API_PARAMS', { hwid, ...tokens}); // new key await this.store.set('params.tokens', tokens); } public async getTokens(): Promise<any> { // old key in indexed db // if old service worker or old sdk const oldValue = await this.store.get('API_PARAMS'); // new key const newValue = await this.store.get('params.tokens'); return typeof newValue !== 'undefined' ? newValue : oldValue; } public async setApplicationServerKey(key: string): Promise<void> { await this.store.set('params.applicationServerKey', key); } public async getApplicationServerKey(): Promise<string | undefined> { return await this.store.get('params.applicationServerKey'); } public async setSenderId(senderId: string): Promise<void> { // old key in indexed db // if old service worker or old sdk await this.store.set('GCM_SENDER_ID', senderId); // new key await this.store.set('params.senderId', senderId); } public async getSenderId(): Promise<string> { // old key in indexed db // if old service worker or old sdk const oldValue = await this.store.get('GCM_SENDER_ID'); // new key const newValue = await this.store.get('params.senderId'); return typeof newValue !== 'undefined' ? newValue : oldValue; } public async setWebSitePushId(senderId: string): Promise<void> { await this.store.set('params.webSitePushId', senderId); } public async getWebSitePushId(): Promise<string> { return await this.store.get('params.webSitePushId'); } public async setDefaultNotificationImage(url?: string): Promise<void> { await this.store.set('params.defaultNotificationImage', url); } public async getDefaultNotificationImage(): Promise<string> { return await this.store.get('params.defaultNotificationImage', CONSTANTS.DEFAULT_NOTIFICATION_IMAGE); } public async setDefaultNotificationTitle(text?: string): Promise<void> { await this.store.set('params.defaultNotificationTitle', text); } public async getDefaultNotificationTitle(): Promise<string> { return await this.store.get('params.defaultNotificationTitle', CONSTANTS.DEFAULT_NOTIFICATION_TITLE); } public async setUserId(userId?: string | number): Promise<void> { if (!userId) { await this.store.set('params.userId', undefined); return; } await this.store.set('params.userId', userId.toString()); } public async getUserId(): Promise<string | undefined> { return await this.store.get('params.userId'); } public async setStatusUserIdWasChanged(status: boolean): Promise<void> { await this.store.set('params.userIdWasChanged', status); } public async getStatusUserIdWasChanged(): Promise<boolean> { return await this.store.get('params.userIdWasChanged', false); } public async setLastPermissionStatus(status: NotificationPermission): Promise<void> { await this.store.set('params.isLastPermissionStatus', status); } public async getLastPermissionStatus(): Promise<NotificationPermission | undefined> { return await this.store.get('params.isLastPermissionStatus'); } public async setStatusManualUnsubscribed(status: boolean): Promise<void> { // old key in indexed db // if old service worker or old sdk await this.store.set('MANUAL_UNSUBSCRIBE', status); // new value await this.store.set('params.isManualUnsubscribed', status); } public async getStatusManualUnsubscribed(): Promise<boolean> { // old key in indexed db // if old service worker or old sdk const oldValue = await this.store.get('MANUAL_UNSUBSCRIBE', false); // new value const newValue = await this.store.get('params.isManualUnsubscribed', false); return typeof newValue !== 'undefined' ? newValue : oldValue; } public async setStatusCommunicationDisabled(status: boolean): Promise<void> { // old key in indexed db // if old service worker or old sdk await this.store.set('COMMUNICATION_ENABLED', status ? 0 : 1); // new key await this.store.set('params.isCommunicationDisabled', status); } public async getStatusCommunicationDisabled(): Promise<boolean> { // old key in indexed db // if old service worker or old sdk const oldValue = await this.store.get('COMMUNICATION_ENABLED'); // new key const newValue = await this.store.get('params.isCommunicationDisabled', false); return typeof newValue !== 'undefined' ? newValue : oldValue ! == 0; } public async setStatusDropAllData(status: boolean): Promise<void> { // old key in indexed db // if old service worker or old sdk await this.store.set('DEVICE_DATA_REMOVED', status); // new key await this.store.set('params.isDropAllData', status); } public async getStatusDropAllData(): Promise<boolean> { // old key in indexed db // if old service worker or old sdk const oldValue = await this.store.get('DEVICE_DATA_REMOVED', false); // new key const newValue = await this.store.get('params.isDropAllData', false); return typeof newValue !== 'undefined' ? newValue : oldValue; } public async setSdkVersion(version: string): Promise<void> { await this.store.set('params.sdkVersion', version); } public async getSdkVersion(): Promise<string> { return await this.store.get('params.sdkVersion'); } public async setServiceWorkerVersion(version: string): Promise<void> { // old key in indexed db // if old service worker or old sdk await this.store.set('WORKER_VERSION', version); // new key await this.store.set('params.serviceWorkerVersion', version); } public async getServiceWorkerVersion(): Promise<string> { // old key in indexed db // if old service worker or old sdk const oldValue = await this.store.get('WORKER_VERSION'); // new key const newValue = await this.store.get('params.serviceWorkerVersion'); return typeof newValue !== 'undefined' ? newValue : oldValue; } public async setServiceWorkerUrl(url?: string | null): Promise<void> { if (!url) { return; } await this.store.set('params.serviceWorkerUrl', url); } public async getServiceWorkerUrl(): Promise<string> { return await this.store.get('params.serviceWorkerUrl', CONSTANTS.DEFAULT_SERVICE_WORKER_URL); } public async setServiceWorkerScope(scope?: string): Promise<void> { if (!scope) { return; } await this.store.set('params.serviceWorkerScope', scope); } public async getServiceWorkerScope(): Promise<string> { return await this.store.get('params.serviceWorkerScope'); } public async setLastOpenMessage(message: any): Promise<void> { // old key in indexed db // if old service worker or old sdk await this.store.set('LAST_OPEN_MESSAGE', message); // new key await this.store.set('params.lastOpenMessage', message); } public async getLastOpenMessage(): Promise<any> { // old key in indexed db // if old service worker or old sdk const oldValue = await this.store.get('LAST_OPEN_MESSAGE'); // new key const newValue = await this.store.get('params.lastOpenMessage'); return typeof newValue !== 'undefined' ? newValue : oldValue; } public async setLastOpenApplicationTime(time: number): Promise<void> { await this.store.set('params.lastOpenApplicationTime', time); } public async getLastOpenApplicationTime(): Promise<number> { return await this.store.get('params.lastOpenApplicationTime'); } public async setFeatures(features: any): Promise<void> { await this.store.set('params.features', features); } public async getFeatures(): Promise<any> { return await this.store.get('params.features'); } public async setInitParams(params: any): Promise<any> { await this.store.set('params.init', params); } public async getInitParams(): Promise<any> { return await this.store.get('params.init'); } public async setInboxLastRequestCode(lastCode: string): Promise<void> { await this.store.set('params.inbox.lastRequestCode', lastCode); } public async getInboxLastRequestCode(): Promise<string> { return await this.store.get('params.inbox.lastRequestCode', ''); } public async setInboxLastRequestTime(lastRequestTime: number): Promise<void> { await this.store.set('params.inbox.lastRequestTime', lastRequestTime); } public async getInboxLastRequestTime(): Promise<number> { return this.store.get('params.inbox.lastRequestTime', 0); } public async setInboxNewMessagesCount(count: number): Promise<void> { await this.store.set('params.inbox.newMessagesCount', count); } public async getInboxNewMessagesCount(): Promise<number> { return this.store.get('params.inbox.newMessagesCount', 0); } public async setDelayedEvent(event: any): Promise<void> { // old key in indexed db // if old service worker or old sdk await this.store.set('DELAYED_EVENT', event); // new key await this.store.set('params.delayedEvent', event); } public async getDelayedEvent(): Promise<any> { // old key in indexed db // if old service worker or old sdk const oldValue = await this.store.get('DELAYED_EVENT'); // new key const newValue = await this.store.get('params.delayedEvent'); return typeof newValue !== 'undefined' ? newValue : oldValue; } public async setInApps(inApps: any): Promise<void> { await this.store.set('params.inApps', inApps); } public async getInApps(): Promise<any> { return this.store.get('params.inApps'); } public async setPromptDisplayCount(count: number): Promise<void> { await this.store.set('params.promptDisplayCount', count); } public async getPromptDisplayCount(): Promise<number> { return this.store.get('params.promptDisplayCount', 0); } public async setPromptLastSeenTime(time: number): Promise<void> { await this.store.set('params.promptLastSeenTime', time); } public async getPromptLastSeenTime(): Promise<number> { return this.store.get('params.promptLastSeenTime', 0); } }
the_stack
import * as angular from 'angular'; /** * @ngdoc enum * @name MenuItemTypes * @module officeuifabric.components.contextualmenu * * @description * Determines which menu template to use, default is `link` */ enum MenuItemTypes { link = 0, divider = 1, header = 2, subMenu = 3 } /** * @ngdoc interface * @name IContextualMenuItemAttributes * @module officeuifabric.components.contextualmenu * * @description * Attributs for the `<uif-contextual-menu-item>` directive. * * @property {string} uifType - The type of the menu item, based on `MenuItemTypes` enum */ interface IContextualMenuItemAttributes extends angular.IAttributes { uifType: string; } /** * @ngdoc directive * @name uifContextualMenuItem * @module officeuifabric.components.contextualmenu * * @restrict E * * @description * `<uif-contextual-menu-item>` is a contextual menu item directive. * * @see {link http://dev.office.com/fabric/components/contextualmenu} * * @usage * * <uif-contextual-menu-item uif-text="'Item1'" uif-on-click="menuOnClick()"></uif-contextual-menu-item> */ export class ContextualMenuItemDirective implements angular.IDirective { public static directiveName: string = 'uifContextualMenuItem'; public restrict: string = 'E'; public require: string = '^uifContextualMenu'; public transclude: boolean = true; public controller: any = ContextualMenuItemController; public replace: boolean = true; public scope: {} = { isSelected: '=?uifIsSelected', onClick: '&ngClick', text: '=?uifText', type: '@uifType' }; private templateTypes: { [menuType: number]: string } = {}; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = ($log: angular.ILogService) => new ContextualMenuItemDirective($log); directive.$inject = ['$log']; return directive; } constructor(private $log: angular.ILogService) { this.templateTypes[MenuItemTypes.subMenu] = `<li class="ms-ContextualMenu-item"> <a class="ms-ContextualMenu-link ms-ContextualMenu-link--hasMenu" ng-class="{\'is-selected\': isSelected, \'is-disabled\': isDisabled}" ng-click="selectItem($event)" href> <span class='uif-item-content'></span></a> <i class="ms-ContextualMenu-subMenuIcon ms-Icon ms-Icon--chevronRight"></i> <div class="uif-context-submenu"></div> </li>`; this.templateTypes[MenuItemTypes.link] = `<li class="ms-ContextualMenu-item"> <a class="ms-ContextualMenu-link" ng-class="{\'is-selected\': isSelected, \'is-disabled\': isDisabled}" ng-click="selectItem($event)" href><span class='uif-item-content'></span></a> </li>`; this.templateTypes[MenuItemTypes.header] = ` <li class="ms-ContextualMenu-item ms-ContextualMenu-item--header"> <span class='uif-item-content'></span> </li>`; this.templateTypes[MenuItemTypes.divider] = `<li class="ms-ContextualMenu-item ms-ContextualMenu-item--divider"></li>`; } public template: any = ($element: angular.IAugmentedJQuery, $attrs: IContextualMenuItemAttributes) => { let type: string = $attrs.uifType; if (angular.isUndefined(type)) { return this.templateTypes[MenuItemTypes.link]; } if (MenuItemTypes[type] === undefined) { this.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.contextualmenu - unsupported menu type:\n' + 'the type \'' + type + '\' is not supported by ng-Office UI Fabric as valid type for context menu.' + 'Supported types can be found under MenuItemTypes enum here:\n' + 'https://github.com/ngOfficeUIFabric/ng-officeuifabric/blob/master/src/components/contextualmenu/contextualMenu.ts'); } return this.templateTypes[MenuItemTypes[type]]; } public link: angular.IDirectiveLinkFn = ( $scope: IContextualMenuItemScope, $element: angular.IAugmentedJQuery, $attrs: angular.IAttributes, contextualMenuController: ContextualMenuController, $transclude: angular.ITranscludeFunction): void => { if (typeof $scope.isSelected !== 'boolean' && $scope.isSelected !== undefined) { contextualMenuController.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.contextualmenu - ' + 'invalid attribute type: \'uif-is-selected\'.\n' + 'The type \'' + typeof $scope.isSelected + '\' is not supported as valid type for \'uif-is-selected\' attribute for ' + '<uif-contextual-menu-item />. The valid type is boolean.'); } $attrs.$observe('disabled', (disabled) => { $scope.isDisabled = !!disabled; }); this.transcludeChilds($scope, $element, $transclude); $scope.selectItem = ($event: MouseEvent) => { if (!contextualMenuController.isMultiSelectionMenu()) { contextualMenuController.deselectItems(); } if (angular.isUndefined($scope.isSelected) && !$scope.isDisabled) { $scope.isSelected = true; } else { $scope.isSelected = !$scope.isSelected; } /*close all menus if link is clicked, do not close if submenu clicked */ if (!$scope.hasChildMenu) { contextualMenuController.closeSubMenus(null, true); if (!contextualMenuController.isRootMenu()) { contextualMenuController.deselectItems(true); } } else { contextualMenuController.closeSubMenus($scope.$id); } if ($scope.hasChildMenu) { $scope.childMenuCtrl.openMenu(); } if (!angular.isUndefined($scope.onClick)) { $scope.onClick(); } $event.stopPropagation(); }; $scope.$on('uif-menu-deselect', () => { $scope.isSelected = false; }); $scope.$on('uif-menu-close', (event: angular.IAngularEvent, menuItemId: number) => { if ($scope.hasChildMenu && $scope.$id !== menuItemId) { $scope.childMenuCtrl.closeMenu(); } }); } private transcludeChilds( $scope: IContextualMenuItemScope, $element: angular.IAugmentedJQuery, $transclude: angular.ITranscludeFunction): void { $transclude((clone: angular.IAugmentedJQuery) => { let hasContent: boolean = this.hasItemContent(clone); if (!hasContent && !$scope.text && !$scope.hasChildMenu && $scope.type !== 'divider') { this.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.contextualmenu - ' + 'you need to provide a text for a contextual menu item.\n' + 'For <uif-contextual-menu-item> you need to specify either \'uif-text\' as attribute or <uif-content> as a child directive'); } this.insertItemContent(clone, $scope, $element); this.insertSubMenu(clone, $scope, $element); }); } private insertItemContent(clone: angular.IAugmentedJQuery, $scope: IContextualMenuItemScope, $element: angular.IAugmentedJQuery): void { let elementToReplace: JQuery = angular.element($element[0].querySelector('.uif-item-content')); if (this.hasItemContent(clone)) { /* element provided */ for (let i: number = 0; i < clone.length; i++) { let element: angular.IAugmentedJQuery = angular.element(clone[i]); if (element.hasClass('uif-content')) { elementToReplace.replaceWith(element); break; } } } else { /* text attribute provided */ elementToReplace.replaceWith(angular.element('<span>' + $scope.text + '</span>')); } } private insertSubMenu(clone: angular.IAugmentedJQuery, $scope: IContextualMenuItemScope, $element: angular.IAugmentedJQuery): void { for (let i: number = 0; i < clone.length; i++) { let element: angular.IAugmentedJQuery = angular.element(clone[i]); if (element.hasClass('ms-ContextualMenu')) { angular.element($element[0].querySelector('.uif-context-submenu')).replaceWith(element); } } } private hasItemContent(clone: angular.IAugmentedJQuery): boolean { for (let i: number = 0; i < clone.length; i++) { let element: angular.IAugmentedJQuery = angular.element(clone[i]); if (element.hasClass('uif-content')) { return true; } } return false; } } /** * @ngdoc interface * @name IContextualMenuItemScope * @module officeuifabric.components.contextualmenu * * @description * This is the scope used by the `<uif-contextual-menu-item>` directive. * * @property {boolean} isSelected - Indicates if particular item is selected * @property {boolean} isDisabled - Indicates if particular item is disabled * @property {boolean} hasChildMenu - Indicates if current menu item has child sub-menu * @property {function} selectItem - Function which is called by clicking on menu item * @property {function} onClick - On click callback for parent scope * @property {object} childMenuCtrl - Reference to child controller (will be initialized only if `hasChildMenu` is true) * @property {string} text - Represents text used by menu item * @property {string} type - Menu type */ export interface IContextualMenuItemScope extends angular.IScope { isSelected?: boolean; isDisabled?: boolean; hasChildMenu: boolean; text: string; type: string; selectItem: ($event: MouseEvent) => void; onClick: () => void; childMenuCtrl: ContextualMenuController; } /** * @ngdoc controller * @name ContextualMenuItemController * @module officeuifabric.components.contextualmenu * * @description * Controller used for the `<uif-contextual-menu-item>` directive. */ export class ContextualMenuItemController { public static $inject: string[] = ['$scope', '$element']; constructor(private $scope: IContextualMenuItemScope, private $element: angular.IAugmentedJQuery) { } public setChildMenu(childMenuCtrl: ContextualMenuController): void { this.$scope.hasChildMenu = true; this.$scope.childMenuCtrl = childMenuCtrl; } } /** * @ngdoc directive * @name uifContextualMenu * @module officeuifabric.components.contextualmenu * * @restrict E * * @description * `<uif-contextual-menu>` is a contextual menu directive. * * @see {link http://dev.office.com/fabric/components/contextualmenu} * * @usage * * <uif-contextual-menu uif-is-open="isOpen"> * <uif-contextual-menu-item uif-text="'Item1'" uif-on-click="menuOnClick()"></uif-contextual-menu-item> * <uif-contextual-menu-item uif-text="'Item2'"></uif-contextual-menu-item> * </uif-contextual-menu> */ export class ContextualMenuDirective implements angular.IDirective { public static directiveName: string = 'uifContextualMenu'; public restrict: string = 'E'; public require: string = ContextualMenuDirective.directiveName; public transclude: boolean = true; public template: string = `<ul class="ms-ContextualMenu" ng-transclude></ul>`; public replace: boolean = true; public controller: any = ContextualMenuController; public scope: {} = { closeOnClick: '@uifCloseOnClick', isOpen: '=?uifIsOpen', multiselect: '@uifMultiselect' }; public static factory(): angular.IDirectiveFactory { const directive: angular.IDirectiveFactory = () => new ContextualMenuDirective(); return directive; } public link( $scope: IContextualMenuScope, $element: angular.IAugmentedJQuery, $attrs: angular.IAttributes, contextualMenuController: ContextualMenuController): void { let setCloseOnClick: (value?: string | boolean) => void = (value: string | boolean) => { if (angular.isUndefined(value)) { $scope.closeOnClick = true; } else { $scope.closeOnClick = value.toString().toLowerCase() === 'true'; } }; setCloseOnClick($scope.closeOnClick); $attrs.$observe('uifCloseOnClick', setCloseOnClick); let parentMenuItemCtrl: ContextualMenuItemController = $element.controller(ContextualMenuItemDirective.directiveName); if (!angular.isUndefined(parentMenuItemCtrl)) { parentMenuItemCtrl.setChildMenu(contextualMenuController); } if (!angular.isUndefined($scope.multiselect) && $scope.multiselect.toLowerCase() === 'true') { $element.addClass('ms-ContextualMenu--multiselect'); } } } /** * @ngdoc interface * @name IContextualMenuItemScope * @module officeuifabric.components.contextualmenu * * @description * This is the scope used by the `<uif-contextual-menu-item>` directive. * * @property {boolean} isOpen - Indicates if menu is open * @property {boolean} isRootMenu - Indicates if this is root menu and not child * @property {string} multiselect - Indicates if current menu is multiselection menu * @property {boolean} closeOnClick - Indicates if root menu should be closed after clicking on menu item */ export interface IContextualMenuScope extends angular.IScope { isOpen: boolean; isRootMenu: boolean; multiselect: string; closeOnClick: boolean; } /** * @ngdoc controller * @name ContextualMenuController * @module officeuifabric.components.contextualmenu * * @description * Controller used for the `<uif-contextual-menu>` directive. */ export class ContextualMenuController { public static $inject: string[] = ['$scope', '$animate', '$element', '$log']; public onRootMenuClosed: (() => void)[] = []; private isOpenClassName: string = 'is-open'; constructor( private $scope: IContextualMenuScope, private $animate: angular.animate.IAnimateService, private $element: angular.IAugmentedJQuery, public $log: angular.ILogService) { if (angular.isUndefined($element.controller(ContextualMenuItemDirective.directiveName))) { $scope.isRootMenu = true; } $scope.$watch('isOpen', (newValue: boolean) => { if (typeof newValue !== 'boolean' && newValue !== undefined) { this.$log.error('Error [ngOfficeUiFabric] officeuifabric.components.contextualmenu - invalid attribute type: \'uif-is-open\'.\n' + 'The type \'' + typeof newValue + '\' is not supported as valid type for \'uif-is-open\' attribute for ' + '<uif-contextual-menu />. The valid type is boolean.'); } $animate[newValue ? 'addClass' : 'removeClass']($element, this.isOpenClassName); }); this.onRootMenuClosed.push(() => { this.closeMenu(); this.deselectItems(true); }); $scope.$on('uif-menu-close', () => { if ($scope.isRootMenu && $scope.closeOnClick) { this.onRootMenuClosed.forEach((callback: () => void) => { callback(); }); } }); } public deselectItems(deselectParentMenus?: boolean): void { this.$scope.$broadcast('uif-menu-deselect'); if (deselectParentMenus) { this.$scope.$emit('uif-menu-deselect'); } } public closeSubMenus(menuItemToSkip?: number, closeRootMenu?: boolean): void { this.$scope.$broadcast('uif-menu-close', menuItemToSkip); if (closeRootMenu) { this.$scope.$emit('uif-menu-close'); } } public openMenu(): void { this.$scope.isOpen = true; } public closeMenu(): void { this.$scope.isOpen = false; } public isRootMenu(): boolean { return this.$scope.isRootMenu; } public isMultiSelectionMenu(): boolean { if (angular.isUndefined(this.$scope.multiselect)) { return false; } return this.$scope.multiselect.toLowerCase() === 'true'; } public isMenuOpened(): boolean { return this.$element.hasClass('is-open'); } } /** * @ngdoc module * @name officeuifabric.components.contextualmenu * * @description * Contextual Menu Module * */ export let module: angular.IModule = angular.module('officeuifabric.components.contextualmenu', [ 'officeuifabric.components']) .directive(ContextualMenuDirective.directiveName, ContextualMenuDirective.factory()) .directive(ContextualMenuItemDirective.directiveName, ContextualMenuItemDirective.factory());
the_stack
// @Filename:privacyFunctionReturnTypeDeclFile_externalModule.ts class privateClass { } export class publicClass { } export interface publicInterfaceWithPrivateParmeterTypes { new (): privateClass; // Error (): privateClass; // Error [x: number]: privateClass; // Error myMethod(): privateClass; // Error } export interface publicInterfaceWithPublicParmeterTypes { new (): publicClass; (): publicClass; [x: number]: publicClass; myMethod(): publicClass; } interface privateInterfaceWithPrivateParmeterTypes { new (): privateClass; (): privateClass; [x: number]: privateClass; myMethod(): privateClass; } interface privateInterfaceWithPublicParmeterTypes { new (): publicClass; (): publicClass; [x: number]: publicClass; myMethod(): publicClass; } export class publicClassWithWithPrivateParmeterTypes { static myPublicStaticMethod(): privateClass { // Error return null; } private static myPrivateStaticMethod(): privateClass { return null; } myPublicMethod(): privateClass { // Error return null; } private myPrivateMethod(): privateClass { return null; } static myPublicStaticMethod1() { // Error return new privateClass(); } private static myPrivateStaticMethod1() { return new privateClass(); } myPublicMethod1() { // Error return new privateClass(); } private myPrivateMethod1() { return new privateClass(); } } export class publicClassWithWithPublicParmeterTypes { static myPublicStaticMethod(): publicClass { return null; } private static myPrivateStaticMethod(): publicClass { return null; } myPublicMethod(): publicClass { return null; } private myPrivateMethod(): publicClass { return null; } static myPublicStaticMethod1() { return new publicClass(); } private static myPrivateStaticMethod1() { return new publicClass(); } myPublicMethod1() { return new publicClass(); } private myPrivateMethod1() { return new publicClass(); } } class privateClassWithWithPrivateParmeterTypes { static myPublicStaticMethod(): privateClass { return null; } private static myPrivateStaticMethod(): privateClass { return null; } myPublicMethod(): privateClass { return null; } private myPrivateMethod(): privateClass { return null; } static myPublicStaticMethod1() { return new privateClass(); } private static myPrivateStaticMethod1() { return new privateClass(); } myPublicMethod1() { return new privateClass(); } private myPrivateMethod1() { return new privateClass(); } } class privateClassWithWithPublicParmeterTypes { static myPublicStaticMethod(): publicClass { return null; } private static myPrivateStaticMethod(): publicClass { return null; } myPublicMethod(): publicClass { return null; } private myPrivateMethod(): publicClass { return null; } static myPublicStaticMethod1() { return new publicClass(); } private static myPrivateStaticMethod1() { return new publicClass(); } myPublicMethod1() { return new publicClass(); } private myPrivateMethod1() { return new publicClass(); } } export function publicFunctionWithPrivateParmeterTypes(): privateClass { // Error return null; } export function publicFunctionWithPublicParmeterTypes(): publicClass { return null; } function privateFunctionWithPrivateParmeterTypes(): privateClass { return null; } function privateFunctionWithPublicParmeterTypes(): publicClass { return null; } export function publicFunctionWithPrivateParmeterTypes1() { // Error return new privateClass(); } export function publicFunctionWithPublicParmeterTypes1() { return new publicClass(); } function privateFunctionWithPrivateParmeterTypes1() { return new privateClass(); } function privateFunctionWithPublicParmeterTypes1() { return new publicClass(); } export declare function publicAmbientFunctionWithPrivateParmeterTypes(): privateClass; // Error export declare function publicAmbientFunctionWithPublicParmeterTypes(): publicClass; declare function privateAmbientFunctionWithPrivateParmeterTypes(): privateClass; declare function privateAmbientFunctionWithPublicParmeterTypes(): publicClass; export interface publicInterfaceWithPrivateModuleParameterTypes { new (): privateModule.publicClass; // Error (): privateModule.publicClass; // Error [x: number]: privateModule.publicClass // Error myMethod(): privateModule.publicClass; // Error } export class publicClassWithPrivateModuleParameterTypes { static myPublicStaticMethod(): privateModule.publicClass { // Error return null; } myPublicMethod(): privateModule.publicClass { // Error return null; } static myPublicStaticMethod1() { // Error return new privateModule.publicClass(); } myPublicMethod1() { // Error return new privateModule.publicClass(); } } export function publicFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass { // Error return null; } export function publicFunctionWithPrivateModuleParameterTypes1() { // Error return new privateModule.publicClass(); } export declare function publicAmbientFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass; // Error interface privateInterfaceWithPrivateModuleParameterTypes { new (): privateModule.publicClass; (): privateModule.publicClass; [x: number]: privateModule.publicClass myMethod(): privateModule.publicClass; } class privateClassWithPrivateModuleParameterTypes { static myPublicStaticMethod(): privateModule.publicClass { return null; } myPublicMethod(): privateModule.publicClass { return null; } static myPublicStaticMethod1() { return new privateModule.publicClass(); } myPublicMethod1() { return new privateModule.publicClass(); } } function privateFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass { return null; } function privateFunctionWithPrivateModuleParameterTypes1() { return new privateModule.publicClass(); } declare function privateAmbientFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass; export module publicModule { class privateClass { } export class publicClass { } export interface publicInterfaceWithPrivateParmeterTypes { new (): privateClass; // Error (): privateClass; // Error [x: number]: privateClass; // Error myMethod(): privateClass; // Error } export interface publicInterfaceWithPublicParmeterTypes { new (): publicClass; (): publicClass; [x: number]: publicClass; myMethod(): publicClass; } interface privateInterfaceWithPrivateParmeterTypes { new (): privateClass; (): privateClass; [x: number]: privateClass; myMethod(): privateClass; } interface privateInterfaceWithPublicParmeterTypes { new (): publicClass; (): publicClass; [x: number]: publicClass; myMethod(): publicClass; } export class publicClassWithWithPrivateParmeterTypes { static myPublicStaticMethod(): privateClass { // Error return null; } private static myPrivateStaticMethod(): privateClass { return null; } myPublicMethod(): privateClass { // Error return null; } private myPrivateMethod(): privateClass { return null; } static myPublicStaticMethod1() { // Error return new privateClass(); } private static myPrivateStaticMethod1() { return new privateClass(); } myPublicMethod1() { // Error return new privateClass(); } private myPrivateMethod1() { return new privateClass(); } } export class publicClassWithWithPublicParmeterTypes { static myPublicStaticMethod(): publicClass { return null; } private static myPrivateStaticMethod(): publicClass { return null; } myPublicMethod(): publicClass { return null; } private myPrivateMethod(): publicClass { return null; } static myPublicStaticMethod1() { return new publicClass(); } private static myPrivateStaticMethod1() { return new publicClass(); } myPublicMethod1() { return new publicClass(); } private myPrivateMethod1() { return new publicClass(); } } class privateClassWithWithPrivateParmeterTypes { static myPublicStaticMethod(): privateClass { return null; } private static myPrivateStaticMethod(): privateClass { return null; } myPublicMethod(): privateClass { return null; } private myPrivateMethod(): privateClass { return null; } static myPublicStaticMethod1() { return new privateClass(); } private static myPrivateStaticMethod1() { return new privateClass(); } myPublicMethod1() { return new privateClass(); } private myPrivateMethod1() { return new privateClass(); } } class privateClassWithWithPublicParmeterTypes { static myPublicStaticMethod(): publicClass { return null; } private static myPrivateStaticMethod(): publicClass { return null; } myPublicMethod(): publicClass { return null; } private myPrivateMethod(): publicClass { return null; } static myPublicStaticMethod1() { return new publicClass(); } private static myPrivateStaticMethod1() { return new publicClass(); } myPublicMethod1() { return new publicClass(); } private myPrivateMethod1() { return new publicClass(); } } export function publicFunctionWithPrivateParmeterTypes(): privateClass { // Error return null; } export function publicFunctionWithPublicParmeterTypes(): publicClass { return null; } function privateFunctionWithPrivateParmeterTypes(): privateClass { return null; } function privateFunctionWithPublicParmeterTypes(): publicClass { return null; } export function publicFunctionWithPrivateParmeterTypes1() { // Error return new privateClass(); } export function publicFunctionWithPublicParmeterTypes1() { return new publicClass(); } function privateFunctionWithPrivateParmeterTypes1() { return new privateClass(); } function privateFunctionWithPublicParmeterTypes1() { return new publicClass(); } export declare function publicAmbientFunctionWithPrivateParmeterTypes(): privateClass; // Error export declare function publicAmbientFunctionWithPublicParmeterTypes(): publicClass; declare function privateAmbientFunctionWithPrivateParmeterTypes(): privateClass; declare function privateAmbientFunctionWithPublicParmeterTypes(): publicClass; export interface publicInterfaceWithPrivateModuleParameterTypes { new (): privateModule.publicClass; // Error (): privateModule.publicClass; // Error [x: number]: privateModule.publicClass; // Error myMethod(): privateModule.publicClass; // Error } export class publicClassWithPrivateModuleParameterTypes { static myPublicStaticMethod(): privateModule.publicClass { // Error return null; } myPublicMethod(): privateModule.publicClass { // Error return null; } static myPublicStaticMethod1() { // Error return new privateModule.publicClass(); } myPublicMethod1() { // Error return new privateModule.publicClass(); } } export function publicFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass { // Error return null; } export function publicFunctionWithPrivateModuleParameterTypes1() { // Error return new privateModule.publicClass(); } export declare function publicAmbientFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass; // Error interface privateInterfaceWithPrivateModuleParameterTypes { new (): privateModule.publicClass; (): privateModule.publicClass; [x: number]: privateModule.publicClass; myMethod(): privateModule.publicClass; } class privateClassWithPrivateModuleParameterTypes { static myPublicStaticMethod(): privateModule.publicClass { return null; } myPublicMethod(): privateModule.publicClass { return null; } static myPublicStaticMethod1() { return new privateModule.publicClass(); } myPublicMethod1() { return new privateModule.publicClass(); } } function privateFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass { return null; } function privateFunctionWithPrivateModuleParameterTypes1() { return new privateModule.publicClass(); } declare function privateAmbientFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass; } module privateModule { class privateClass { } export class publicClass { } export interface publicInterfaceWithPrivateParmeterTypes { new (): privateClass; (): privateClass; [x: number]: privateClass; myMethod(): privateClass; } export interface publicInterfaceWithPublicParmeterTypes { new (): publicClass; (): publicClass; [x: number]: publicClass; myMethod(): publicClass; } interface privateInterfaceWithPrivateParmeterTypes { new (): privateClass; (): privateClass; [x: number]: privateClass; myMethod(): privateClass; } interface privateInterfaceWithPublicParmeterTypes { new (): publicClass; (): publicClass; [x: number]: publicClass; myMethod(): publicClass; } export class publicClassWithWithPrivateParmeterTypes { static myPublicStaticMethod(): privateClass { return null; } private static myPrivateStaticMethod(): privateClass { return null; } myPublicMethod(): privateClass { return null; } private myPrivateMethod(): privateClass { return null; } static myPublicStaticMethod1() { return new privateClass(); } private static myPrivateStaticMethod1() { return new privateClass(); } myPublicMethod1() { return new privateClass(); } private myPrivateMethod1() { return new privateClass(); } } export class publicClassWithWithPublicParmeterTypes { static myPublicStaticMethod(): publicClass { return null; } private static myPrivateStaticMethod(): publicClass { return null; } myPublicMethod(): publicClass { return null; } private myPrivateMethod(): publicClass { return null; } static myPublicStaticMethod1() { return new publicClass(); } private static myPrivateStaticMethod1() { return new publicClass(); } myPublicMethod1() { return new publicClass(); } private myPrivateMethod1() { return new publicClass(); } } class privateClassWithWithPrivateParmeterTypes { static myPublicStaticMethod(): privateClass { return null; } private static myPrivateStaticMethod(): privateClass { return null; } myPublicMethod(): privateClass { return null; } private myPrivateMethod(): privateClass { return null; } static myPublicStaticMethod1() { return new privateClass(); } private static myPrivateStaticMethod1() { return new privateClass(); } myPublicMethod1() { return new privateClass(); } private myPrivateMethod1() { return new privateClass(); } } class privateClassWithWithPublicParmeterTypes { static myPublicStaticMethod(): publicClass { return null; } private static myPrivateStaticMethod(): publicClass { return null; } myPublicMethod(): publicClass { return null; } private myPrivateMethod(): publicClass { return null; } static myPublicStaticMethod1() { return new publicClass(); } private static myPrivateStaticMethod1() { return new publicClass(); } myPublicMethod1() { return new publicClass(); } private myPrivateMethod1() { return new publicClass(); } } export function publicFunctionWithPrivateParmeterTypes(): privateClass { return null; } export function publicFunctionWithPublicParmeterTypes(): publicClass { return null; } function privateFunctionWithPrivateParmeterTypes(): privateClass { return null; } function privateFunctionWithPublicParmeterTypes(): publicClass { return null; } export function publicFunctionWithPrivateParmeterTypes1() { return new privateClass(); } export function publicFunctionWithPublicParmeterTypes1() { return new publicClass(); } function privateFunctionWithPrivateParmeterTypes1() { return new privateClass(); } function privateFunctionWithPublicParmeterTypes1() { return new publicClass(); } export declare function publicAmbientFunctionWithPrivateParmeterTypes(): privateClass; export declare function publicAmbientFunctionWithPublicParmeterTypes(): publicClass; declare function privateAmbientFunctionWithPrivateParmeterTypes(): privateClass; declare function privateAmbientFunctionWithPublicParmeterTypes(): publicClass; export interface publicInterfaceWithPrivateModuleParameterTypes { new (): privateModule.publicClass; (): privateModule.publicClass; [x: number]: privateModule.publicClass; myMethod(): privateModule.publicClass; } export class publicClassWithPrivateModuleParameterTypes { static myPublicStaticMethod(): privateModule.publicClass { return null; } myPublicMethod(): privateModule.publicClass { return null; } static myPublicStaticMethod1() { return new privateModule.publicClass(); } myPublicMethod1() { return new privateModule.publicClass(); } } export function publicFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass { return null; } export function publicFunctionWithPrivateModuleParameterTypes1() { return new privateModule.publicClass(); } export declare function publicAmbientFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass; interface privateInterfaceWithPrivateModuleParameterTypes { new (): privateModule.publicClass; (): privateModule.publicClass; [x: number]: privateModule.publicClass; myMethod(): privateModule.publicClass; } class privateClassWithPrivateModuleParameterTypes { static myPublicStaticMethod(): privateModule.publicClass { return null; } myPublicMethod(): privateModule.publicClass { return null; } static myPublicStaticMethod1() { return new privateModule.publicClass(); } myPublicMethod1() { return new privateModule.publicClass(); } } function privateFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass { return null; } function privateFunctionWithPrivateModuleParameterTypes1() { return new privateModule.publicClass(); } declare function privateAmbientFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass; } // @Filename: privacyFunctionReturnTypeDeclFile_GlobalFile.ts class publicClassInGlobal { } interface publicInterfaceWithPublicParmeterTypesInGlobal { new (): publicClassInGlobal; (): publicClassInGlobal; [x: number]: publicClassInGlobal; myMethod(): publicClassInGlobal; } class publicClassWithWithPublicParmeterTypesInGlobal { static myPublicStaticMethod(): publicClassInGlobal { return null; } private static myPrivateStaticMethod(): publicClassInGlobal { return null; } myPublicMethod(): publicClassInGlobal { return null; } private myPrivateMethod(): publicClassInGlobal { return null; } static myPublicStaticMethod1() { return new publicClassInGlobal(); } private static myPrivateStaticMethod1() { return new publicClassInGlobal(); } myPublicMethod1() { return new publicClassInGlobal(); } private myPrivateMethod1() { return new publicClassInGlobal(); } } function publicFunctionWithPublicParmeterTypesInGlobal(): publicClassInGlobal { return null; } function publicFunctionWithPublicParmeterTypesInGlobal1() { return new publicClassInGlobal(); } declare function publicAmbientFunctionWithPublicParmeterTypesInGlobal(): publicClassInGlobal; module publicModuleInGlobal { class privateClass { } export class publicClass { } module privateModule { class privateClass { } export class publicClass { } export interface publicInterfaceWithPrivateParmeterTypes { new (): privateClass; (): privateClass; [x: number]: privateClass; myMethod(): privateClass; } export interface publicInterfaceWithPublicParmeterTypes { new (): publicClass; (): publicClass; [x: number]: publicClass; myMethod(): publicClass; } interface privateInterfaceWithPrivateParmeterTypes { new (): privateClass; (): privateClass; [x: number]: privateClass; myMethod(): privateClass; } interface privateInterfaceWithPublicParmeterTypes { new (): publicClass; (): publicClass; [x: number]: publicClass; myMethod(): publicClass; } export class publicClassWithWithPrivateParmeterTypes { static myPublicStaticMethod(): privateClass { return null; } private static myPrivateStaticMethod(): privateClass { return null; } myPublicMethod(): privateClass { return null; } private myPrivateMethod(): privateClass { return null; } static myPublicStaticMethod1() { return new privateClass(); } private static myPrivateStaticMethod1() { return new privateClass(); } myPublicMethod1() { return new privateClass(); } private myPrivateMethod1() { return new privateClass(); } } export class publicClassWithWithPublicParmeterTypes { static myPublicStaticMethod(): publicClass { return null; } private static myPrivateStaticMethod(): publicClass { return null; } myPublicMethod(): publicClass { return null; } private myPrivateMethod(): publicClass { return null; } static myPublicStaticMethod1() { return new publicClass(); } private static myPrivateStaticMethod1() { return new publicClass(); } myPublicMethod1() { return new publicClass(); } private myPrivateMethod1() { return new publicClass(); } } class privateClassWithWithPrivateParmeterTypes { static myPublicStaticMethod(): privateClass { return null; } private static myPrivateStaticMethod(): privateClass { return null; } myPublicMethod(): privateClass { return null; } private myPrivateMethod(): privateClass { return null; } static myPublicStaticMethod1() { return new privateClass(); } private static myPrivateStaticMethod1() { return new privateClass(); } myPublicMethod1() { return new privateClass(); } private myPrivateMethod1() { return new privateClass(); } } class privateClassWithWithPublicParmeterTypes { static myPublicStaticMethod(): publicClass { return null; } private static myPrivateStaticMethod(): publicClass { return null; } myPublicMethod(): publicClass { return null; } private myPrivateMethod(): publicClass { return null; } static myPublicStaticMethod1() { return new publicClass(); } private static myPrivateStaticMethod1() { return new publicClass(); } myPublicMethod1() { return new publicClass(); } private myPrivateMethod1() { return new publicClass(); } } export function publicFunctionWithPrivateParmeterTypes(): privateClass { return null; } export function publicFunctionWithPublicParmeterTypes(): publicClass { return null; } function privateFunctionWithPrivateParmeterTypes(): privateClass { return null; } function privateFunctionWithPublicParmeterTypes(): publicClass { return null; } export function publicFunctionWithPrivateParmeterTypes1() { return new privateClass(); } export function publicFunctionWithPublicParmeterTypes1() { return new publicClass(); } function privateFunctionWithPrivateParmeterTypes1() { return new privateClass(); } function privateFunctionWithPublicParmeterTypes1() { return new publicClass(); } export declare function publicAmbientFunctionWithPrivateParmeterTypes(): privateClass; export declare function publicAmbientFunctionWithPublicParmeterTypes(): publicClass; declare function privateAmbientFunctionWithPrivateParmeterTypes(): privateClass; declare function privateAmbientFunctionWithPublicParmeterTypes(): publicClass; export interface publicInterfaceWithPrivateModuleParameterTypes { new (): privateModule.publicClass; (): privateModule.publicClass; [x: number]: privateModule.publicClass; myMethod(): privateModule.publicClass; } export class publicClassWithPrivateModuleParameterTypes { static myPublicStaticMethod(): privateModule.publicClass { return null; } myPublicMethod(): privateModule.publicClass { return null; } static myPublicStaticMethod1() { return new privateModule.publicClass(); } myPublicMethod1() { return new privateModule.publicClass(); } } export function publicFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass { return null; } export function publicFunctionWithPrivateModuleParameterTypes1() { return new privateModule.publicClass(); } export declare function publicAmbientFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass; interface privateInterfaceWithPrivateModuleParameterTypes { new (): privateModule.publicClass; (): privateModule.publicClass; [x: number]: privateModule.publicClass; myMethod(): privateModule.publicClass; } class privateClassWithPrivateModuleParameterTypes { static myPublicStaticMethod(): privateModule.publicClass { return null; } myPublicMethod(): privateModule.publicClass { return null; } static myPublicStaticMethod1() { return new privateModule.publicClass(); } myPublicMethod1() { return new privateModule.publicClass(); } } function privateFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass { return null; } function privateFunctionWithPrivateModuleParameterTypes1() { return new privateModule.publicClass(); } declare function privateAmbientFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass; } export interface publicInterfaceWithPrivateParmeterTypes { new (): privateClass; // Error (): privateClass; // Error [x: number]: privateClass; // Error myMethod(): privateClass; // Error } export interface publicInterfaceWithPublicParmeterTypes { new (): publicClass; (): publicClass; [x: number]: publicClass; myMethod(): publicClass; } interface privateInterfaceWithPrivateParmeterTypes { new (): privateClass; (): privateClass; [x: number]: privateClass; myMethod(): privateClass; } interface privateInterfaceWithPublicParmeterTypes { new (): publicClass; (): publicClass; [x: number]: publicClass; myMethod(): publicClass; } export class publicClassWithWithPrivateParmeterTypes { static myPublicStaticMethod(): privateClass { // Error return null; } private static myPrivateStaticMethod(): privateClass { return null; } myPublicMethod(): privateClass { // Error return null; } private myPrivateMethod(): privateClass { return null; } static myPublicStaticMethod1() { // Error return new privateClass(); } private static myPrivateStaticMethod1() { return new privateClass(); } myPublicMethod1() { // Error return new privateClass(); } private myPrivateMethod1() { return new privateClass(); } } export class publicClassWithWithPublicParmeterTypes { static myPublicStaticMethod(): publicClass { return null; } private static myPrivateStaticMethod(): publicClass { return null; } myPublicMethod(): publicClass { return null; } private myPrivateMethod(): publicClass { return null; } static myPublicStaticMethod1() { return new publicClass(); } private static myPrivateStaticMethod1() { return new publicClass(); } myPublicMethod1() { return new publicClass(); } private myPrivateMethod1() { return new publicClass(); } } class privateClassWithWithPrivateParmeterTypes { static myPublicStaticMethod(): privateClass { return null; } private static myPrivateStaticMethod(): privateClass { return null; } myPublicMethod(): privateClass { return null; } private myPrivateMethod(): privateClass { return null; } static myPublicStaticMethod1() { return new privateClass(); } private static myPrivateStaticMethod1() { return new privateClass(); } myPublicMethod1() { return new privateClass(); } private myPrivateMethod1() { return new privateClass(); } } class privateClassWithWithPublicParmeterTypes { static myPublicStaticMethod(): publicClass { return null; } private static myPrivateStaticMethod(): publicClass { return null; } myPublicMethod(): publicClass { return null; } private myPrivateMethod(): publicClass { return null; } static myPublicStaticMethod1() { return new publicClass(); } private static myPrivateStaticMethod1() { return new publicClass(); } myPublicMethod1() { return new publicClass(); } private myPrivateMethod1() { return new publicClass(); } } export function publicFunctionWithPrivateParmeterTypes(): privateClass { // Error return null; } export function publicFunctionWithPublicParmeterTypes(): publicClass { return null; } function privateFunctionWithPrivateParmeterTypes(): privateClass { return null; } function privateFunctionWithPublicParmeterTypes(): publicClass { return null; } export function publicFunctionWithPrivateParmeterTypes1() { // Error return new privateClass(); } export function publicFunctionWithPublicParmeterTypes1() { return new publicClass(); } function privateFunctionWithPrivateParmeterTypes1() { return new privateClass(); } function privateFunctionWithPublicParmeterTypes1() { return new publicClass(); } export declare function publicAmbientFunctionWithPrivateParmeterTypes(): privateClass; // Error export declare function publicAmbientFunctionWithPublicParmeterTypes(): publicClass; declare function privateAmbientFunctionWithPrivateParmeterTypes(): privateClass; declare function privateAmbientFunctionWithPublicParmeterTypes(): publicClass; export interface publicInterfaceWithPrivateModuleParameterTypes { new (): privateModule.publicClass; // Error (): privateModule.publicClass; // Error [x: number]: privateModule.publicClass; // Error myMethod(): privateModule.publicClass; // Error } export class publicClassWithPrivateModuleParameterTypes { static myPublicStaticMethod(): privateModule.publicClass { // Error return null; } myPublicMethod(): privateModule.publicClass { // Error return null; } static myPublicStaticMethod1() { // Error return new privateModule.publicClass(); } myPublicMethod1() { // Error return new privateModule.publicClass(); } } export function publicFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass { // Error return null; } export function publicFunctionWithPrivateModuleParameterTypes1() { // Error return new privateModule.publicClass(); } export declare function publicAmbientFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass; // Error interface privateInterfaceWithPrivateModuleParameterTypes { new (): privateModule.publicClass; (): privateModule.publicClass; [x: number]: privateModule.publicClass; myMethod(): privateModule.publicClass; } class privateClassWithPrivateModuleParameterTypes { static myPublicStaticMethod(): privateModule.publicClass { return null; } myPublicMethod(): privateModule.publicClass { return null; } static myPublicStaticMethod1() { return new privateModule.publicClass(); } myPublicMethod1() { return new privateModule.publicClass(); } } function privateFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass { return null; } function privateFunctionWithPrivateModuleParameterTypes1() { return new privateModule.publicClass(); } declare function privateAmbientFunctionWithPrivateModuleParameterTypes(): privateModule.publicClass; }
the_stack
import { STS } from '@aws-sdk/client-sts'; import { ServiceCatalog } from '@aws-sdk/client-service-catalog'; import { action, runInAction, set } from 'mobx'; import { observer } from 'mobx-react-lite'; import { useCallback, useState } from 'react'; import { Alert, Box, Button, Container, FormField, Header, Select, SelectProps, SpaceBetween, StatusIndicator, } from '@awsui/components-react'; import * as t from '@aws-accelerator/common-types'; import { AwsConfiguration, useAwsConfiguration } from '@/components/aws-credentials-context'; import { EnumField } from '@/components/fields/enum'; import { useEffectAsync } from '@/utils/hooks'; import { ImportModal, ImportModalProps } from '@/components/import-modal'; import { useStateInput } from '@/components/fields/input'; import { useI18n } from '@/components/i18n-context'; import { TypeTreeNode } from '@/types'; import { AcceleratorConfigurationNode, ConfigurationNode } from '../configuration'; import { WizardField } from '../components/fields'; export interface ConfigureGlobalSettingsStepProps { state: any; configuration: any; } const globalOptionsNode = AcceleratorConfigurationNode.nested('global-options'); const controlTowerNode = globalOptionsNode.nested('ct-baseline'); const centralBucketNode = globalOptionsNode.nested('central-bucket'); // prettier-ignore const securityEmailsNode = globalOptionsNode .nested('central-log-services') .nested('sns-subscription-emails'); /* TODO: Debug backend common.ts code vpcReplacements line 267 */ const vpcReplacements = (props: string) => { const rawConfigStr = props; /* eslint-disable no-template-curly-in-string */ const ouOrAccountReplacementRegex = '\\${CONFIG::OU_NAME}'; const vpcConfigSections = ['workload-account-configs', 'mandatory-account-configs', 'organizational-units']; const rawConfig = JSON.parse(rawConfigStr); for (const vpcConfigSection of vpcConfigSections) { Object.entries(rawConfig[vpcConfigSection]).map(([key, _]) => { const replacements = { '\\${CONFIG::VPC_NAME}': key, '\\${CONFIG::VPC_NAME_L}': key.toLowerCase(), '\\${CONFIG::OU_NAME}': key, }; // eslint-disable-next-line @typescript-eslint/no-explicit-any for (const [index, vpcConfig] of Object.entries(rawConfig[vpcConfigSection][key].vpc || []) as [string, any]) { vpcConfig.name = vpcConfig.name.replace(new RegExp(ouOrAccountReplacementRegex, 'g'), key); let vpcConfigStr = JSON.stringify(vpcConfig); for (const [key, value] of Object.entries(replacements)) { vpcConfigStr = vpcConfigStr.replace(new RegExp(key, 'g'), value); } rawConfig[vpcConfigSection][key].vpc[index] = JSON.parse(vpcConfigStr); } }); } /* eslint-enable */ return rawConfig; } export const ConfigureGlobalSettingsStep = observer(function ConfigureGlobalSettingsStep({ state, configuration, }: ConfigureGlobalSettingsStepProps) { const { tr } = useI18n(); const { configuration: awsConfiguration, setModalVisible: setAwsConfigurationModalVisible } = useAwsConfiguration(); const [importVisible, setImportDialogVisible] = useState(false); const [alertVisible, setAlertVisible] = useState(false); const [filename, setFileName] = useState("") const controlTowerEnabled = controlTowerNode.get(configuration); const handleAwsConfiguration = useCallback(() => { setAwsConfigurationModalVisible(true); }, []); const handleSelectConfiguration = () => { setImportDialogVisible(true); }; const handleImportSubmit: ImportModalProps['onSubmit'] = action(value => { const value2 = vpcReplacements(JSON.stringify(value)); set(configuration, value2); // Set configuration to the imported value set(state, {}); // Reset wizard state setImportDialogVisible(false); setFileName(value['global-options']['workloadaccounts-param-filename']) setAlertVisible(true); }); const handleImportDismiss: ImportModalProps['onDismiss'] = () => { setImportDialogVisible(false); }; // Detect control tower useEffectAsync( action(async () => { state.region = state.region ?? (awsConfiguration.region as t.Region); const credentialsSet = hasCredentials(awsConfiguration); if (state.authenticated === undefined) { if (credentialsSet) { try { const sts = new STS(awsConfiguration); await sts.getCallerIdentity({}); runInAction(() => { state.authenticated = true; }); } catch (e) { runInAction(() => { state.authenticated = false; }); } } } else if (!credentialsSet) { runInAction(() => { state.authenticated = undefined; }); } if (state.controlTowerDetected === undefined) { try { const catalog = new ServiceCatalog(awsConfiguration); await catalog.describeProduct({ Name: 'AWS Control Tower Account Factory', }); runInAction(() => { state.controlTowerDetected = true; state.installationType = 'CONTROL_TOWER'; }); } catch (e) { runInAction(() => { state.controlTowerDetected = false; state.installationType = 'STANDALONE'; }); } } }), [awsConfiguration], ); return ( <> <SpaceBetween size="xxl"> <Container header={ <Header variant="h2" description={tr('wizard.headers.aws_configuration_desc')}> {tr('wizard.headers.aws_configuration')} </Header> } > <SpaceBetween size="xl" direction="vertical"> <FormField label={tr('wizard.fields.aws_credentials')} description={tr('wizard.fields.aws_credentials_desc')} stretch > <SpaceBetween size="s"> <Button onClick={handleAwsConfiguration}>{tr('wizard.buttons.configure_aws_credentials')}</Button> {state.authenticated == null ? ( <StatusIndicator type="warning">{tr('wizard.labels.credentials_not_set')}</StatusIndicator> ) : state.authenticated ? ( <StatusIndicator type="success">{tr('wizard.labels.credentials_valid')}</StatusIndicator> ) : ( <StatusIndicator type="error">{tr('wizard.labels.credentials_not_valid')}</StatusIndicator> )} </SpaceBetween> </FormField> </SpaceBetween> </Container> <Container header={ <Header variant="h2" description={tr('wizard.headers.framework_desc')}> {tr('wizard.headers.framework')} </Header> } > <SpaceBetween size="xl" direction="vertical"> <FormField label={tr('wizard.fields.architecture_template')} description={tr('wizard.fields.architecture_template_desc')} stretch > <SpaceBetween size="xl" direction="vertical"> <Button onClick={handleSelectConfiguration}>{tr('wizard.buttons.select_configuration_file')}</Button> <Alert onDismiss={() => setAlertVisible(false)} visible={alertVisible} dismissAriaLabel="Close alert" dismissible type="success"> Successfully uploaded configuration file: {filename} </Alert> </SpaceBetween> </FormField> </SpaceBetween> </Container> <Container header={ <Header variant="h2" description={tr('wizard.headers.basic_settings_desc')}> {tr('wizard.headers.basic_settings')} </Header> } > <SpaceBetween size="xl" direction="vertical"> <FormField label={tr('wizard.fields.installation_region')} description={tr('wizard.fields.installation_region_desc')} stretch > <EnumField state={state} node={ConfigurationNode.nested('region') as TypeTreeNode<t.EnumType<any>>} /> </FormField> <FormField label={tr('wizard.fields.installation_type')} description={tr('wizard.fields.installation_type_desc')} stretch > <SpaceBetween size="xs"> <InstallationTypeComponent state={configuration} node={controlTowerNode} /> {state.authenticated == null ? ( controlTowerEnabled ? ( <StatusIndicator type="warning" className="break-word"> {tr('wizard.labels.ct_enabled_not_authenticated')} </StatusIndicator> ) : ( <StatusIndicator type="warning" className="break-word"> {tr('wizard.labels.ct_disabled_not_authenticated')} </StatusIndicator> ) ) : state.controlTowerDetected ? ( controlTowerEnabled ? ( <StatusIndicator type="success" className="break-word"> {tr('wizard.labels.ct_detected_and_enabled')} </StatusIndicator> ) : ( <StatusIndicator type="warning" className="break-word"> {tr('wizard.labels.ct_detected_and_disabled')} </StatusIndicator> ) ) : controlTowerEnabled ? ( <StatusIndicator type="warning" className="break-word"> {tr('wizard.labels.ct_not_detected_and_enabled')} </StatusIndicator> ) : ( <StatusIndicator type="success" className="break-word"> {tr('wizard.labels.ct_not_detected_and_disabled')} </StatusIndicator> )} </SpaceBetween> </FormField> <WizardField state={configuration} node={centralBucketNode} context={{ replacement: false }} /> </SpaceBetween> </Container> <Container header={ <Header variant="h2" description={tr('wizard.headers.security_notifications_desc')}> {tr('wizard.headers.security_notifications')} </Header> } > <SpaceBetween size="m"> <Box>{tr('wizard.labels.security_notifications_text')}</Box> <StatusIndicator type="info">{tr('wizard.labels.security_notifications_email_not_unique')}</StatusIndicator> <SpaceBetween size="xs"> <WizardField node={securityEmailsNode.nested('High').nested(0)} state={configuration} context={{ label: tr('wizard.fields.high_priority_email'), description: tr('wizard.fields.high_priority_email_desc'), }} /> <WizardField node={securityEmailsNode.nested('Medium').nested(0)} state={configuration} context={{ label: tr('wizard.fields.medium_priority_email'), description: tr('wizard.fields.medium_priority_email_desc'), }} /> <WizardField node={securityEmailsNode.nested('Low').nested(0)} state={configuration} context={{ label: tr('wizard.fields.low_priority_email'), description: tr('wizard.fields.low_priority_email_desc'), }} /> </SpaceBetween> </SpaceBetween> </Container> </SpaceBetween> <ImportModal visible={importVisible} onSubmit={handleImportSubmit} onDismiss={handleImportDismiss} /> </> ); }); interface InstallationTypeComponentProps { state: any; node: TypeTreeNode; } const installationTypeOptions: SelectProps['options'] = [ { label: 'Standalone', value: '0', }, { label: 'Control Tower', value: '1', }, ]; const InstallationTypeComponent = observer((props: InstallationTypeComponentProps) => { const { value: selectedOption, onChange } = useStateInput<SelectProps.ChangeDetail, boolean, SelectProps.Option>({ node: props.node, state: props.state, mapStateToValue: (stateValue: boolean) => (stateValue ? installationTypeOptions[1] : installationTypeOptions[0]), mapDetailToValue: detail => detail.selectedOption.value === '1', }); return <Select selectedOption={selectedOption} options={installationTypeOptions} onChange={onChange} />; }); function hasCredentials(awsConfiguration: AwsConfiguration | undefined) { const credentials = awsConfiguration?.credentials; if (!credentials) { return false; } return ( !credentials.accessKeyId || !credentials.secretAccessKey || credentials.accessKeyId === '' || credentials.secretAccessKey === '' ); } function getStringFromObject(rawConfig: any, JSON_FORMAT: any): string | PromiseLike<string> { throw new Error('Function not implemented.'); } function JSON_FORMAT(rawConfig: any, JSON_FORMAT: any): string | PromiseLike<string> { throw new Error('Function not implemented.'); }
the_stack
/* Copyright (c) 2019-2020 Integrative Software LLC Created: 5/2019 Author: Pablo Carbonell */ import { ContentArrayNode, ContentElementNode, ContentNode, ContentNodeType, ContentPlaceholder, ContentTextNode } from "./ContentInterfaces" import * as Delta from "./DeltaInterfaces" import { listenServerEvents } from "./index" import { subscribe, unsubscribe } from "./RegisteredEvents" export function processResult(steps: Delta.BaseDelta[]): void { for (const step of steps) { if (!processStepCatch(step)) { return } } } function processStepCatch(step: Delta.BaseDelta): boolean { try { processStep(step) return true } catch (Error) { // eslint-disable-next-line no-console console.log("Error processing step:") // eslint-disable-next-line no-console console.log(Error) // eslint-disable-next-line no-console console.log(step) return false } } function processStep(step: Delta.BaseDelta): void { switch (step.Type) { case Delta.DeltaType.Append: append(step as Delta.NodeAddedDelta) break case Delta.DeltaType.Insert: insert(step as Delta.NodeInsertedDelta) break case Delta.DeltaType.TextModified: textModified(step as Delta.TextModifiedDelta) break case Delta.DeltaType.Remove: remove(step as Delta.NodeRemovedDelta) break case Delta.DeltaType.EditAttribute: editAttribute(step as Delta.AttributeEditedDelta) break case Delta.DeltaType.RemoveAttribute: removeAttribute(step as Delta.AttributeRemovedDelta) break case Delta.DeltaType.Focus: focus(step as Delta.FocusDelta) break case Delta.DeltaType.SetId: setId(step as Delta.SetIdDelta) break case Delta.DeltaType.SetValue: setValue(step as Delta.SetValueDelta) break case Delta.DeltaType.SubmitJS: submitJS(step as Delta.SubmitJsDelta) break case Delta.DeltaType.SetChecked: setChecked(step as Delta.SetCheckedDelta) break case Delta.DeltaType.ClearChildren: clearChildren(step as Delta.ClearChildrenDelta) break case Delta.DeltaType.Replace: replaceLocation(step as Delta.ReplaceDelta) break case Delta.DeltaType.ServerEvents: listenServerEvents() break case Delta.DeltaType.SwapChildren: swapChildren(step as Delta.SwapChildrenDelta) break case Delta.DeltaType.Subscribe: subscribe(step as Delta.SubscribeDelta) break case Delta.DeltaType.Unsubscribe: unsubscribe(step as Delta.UnsubscribeDelta) break case Delta.DeltaType.RemoveElementId: removeElementId(step as Delta.RemoveElement) break case Delta.DeltaType.Render: render(step as Delta.RenderDelta) break case Delta.DeltaType.UnRender: unRender(step as Delta.UnRenderDelta) break default: // eslint-disable-next-line no-console console.log( "Error processing event response. Unknown step type: " + step.Type ) } } function append(delta: Delta.NodeAddedDelta): void { const el = document.getElementById(delta.ParentId) const children = createNodes(delta.Node) appendChildren(el, children) } function appendChildren(el: Element, children: Node[]): void { for (const child of children) { el.appendChild(child) } } function insert(delta: Delta.NodeInsertedDelta): void { const el = document.getElementById(delta.ParentElementId) const children = createNodes(delta.ContentNode) if (delta.Index < el.childNodes.length) { const before = el.childNodes[delta.Index] insertBeforeChildren(el, before, children) } else { appendChildren(el, children) } } function render(delta: Delta.RenderDelta): void { const stub = locateNode(delta.Locator) const elements = createNodes(delta.Node) if (elements.length == 0) { stub.remove() return } let last = elements.pop() const parent = stub.parentElement parent.replaceChild(last, stub) while (elements.length) { const pop = elements.pop() parent.insertBefore(pop, last) last = pop } } function insertBeforeChildren( el: Element, before: ChildNode, children: Node[] ): void { for (const child of children) { el.insertBefore(child, before) before = child.nextSibling } } function createNodes(node: ContentNode): Node[] { const list: Node[] = [] pushNodes(node, list) return list } function pushNodes(node: ContentNode, list: Node[]): void { if (node.Type == ContentNodeType.Text) { list.push(createTextNode(node as ContentTextNode)) } else if (node.Type == ContentNodeType.Element) { list.push(createElementNode(node as ContentElementNode)) } else if (node.Type == ContentNodeType.Array) { pushArrayNodes(node as ContentArrayNode, list) } else if (node.Type == ContentNodeType.Placeholder) { list.push(createPlaceholder(node as ContentPlaceholder)) } else { // eslint-disable-next-line no-console console.log( "Error processing event response. Unknown content type: " + node.Type ) document.createTextNode("") } } function pushArrayNodes(node: ContentArrayNode, list: Node[]): void { for (let index = 0; index < node.Nodes.length; index++) { const item = node.Nodes[index] pushNodes(item, list) } } function createTextNode(node: ContentTextNode): Node { const div = document.createElement("div") div.innerHTML = node.Data return document.createTextNode(div.innerText) } function createElementNode(node: ContentElementNode): Element { const child = createRootNode(node) for (const attribute of node.Attributes) { setAttribute(child, attribute.Attribute, attribute.Value) } for (const branch of node.Children) { const nodes = createNodes(branch) for (const node of nodes) { child.appendChild(node) } } return child } function createPlaceholder(node: ContentPlaceholder): Element { const stub = document.createElement("script") stub.id = node.ElementId stub.type = "placeholder/lara" return stub } function setAttribute(child: Element, attribute: string, value: string): void { if (!value) { value = "" } if ( attribute == "value" && (child instanceof HTMLInputElement || child instanceof HTMLSelectElement || child instanceof HTMLTextAreaElement) ) { child.value = value return } if (attribute == "checked" && child instanceof HTMLInputElement) { child.checked = true return } child.setAttribute(attribute, value) } function createRootNode(node: ContentElementNode): Element { if (node.NS) { return document.createElementNS(node.NS, node.TagName) } else { return document.createElement(node.TagName) } } function textModified(delta: Delta.TextModifiedDelta): void { const el = document.getElementById(delta.ParentElementId) const child = el.childNodes[delta.ChildNodeIndex] child.textContent = delta.Text } function remove(delta: Delta.NodeRemovedDelta): void { const parent = document.getElementById(delta.ParentId) const child = parent.childNodes[delta.ChildIndex] child.remove() } function editAttribute(delta: Delta.AttributeEditedDelta): void { const el = document.getElementById(delta.ElementId) if (el.tagName == "OPTION" && delta.Attribute == "selected") { const option = el as HTMLOptionElement option.selected = true } else { el.setAttribute(delta.Attribute, delta.Value) } } function removeAttribute(delta: Delta.AttributeRemovedDelta): void { const el = document.getElementById(delta.ElementId) if (el.tagName == "OPTION" && delta.Attribute == "selected") { const option = el as HTMLOptionElement option.selected = false } else { el.removeAttribute(delta.Attribute) } } function focus(delta: Delta.FocusDelta): void { const el = document.getElementById(delta.ElementId) el.focus() } function setId(delta: Delta.SetIdDelta): void { const el = document.getElementById(delta.OldId) el.id = delta.NewId } function setValue(delta: Delta.SetValueDelta): void { const input = document.getElementById(delta.ElementId) as HTMLInputElement input.value = delta.Value } function submitJS(context: Delta.SubmitJsDelta): void { try { eval(context.Code) } catch (e) { // eslint-disable-next-line no-console console.log((<Error>e).message) } } function setChecked(delta: Delta.SetCheckedDelta): void { const input = document.getElementById(delta.ElementId) as HTMLInputElement input.checked = delta.Checked } function clearChildren(delta: Delta.ClearChildrenDelta): void { const parent = document.getElementById(delta.ElementId) while (parent.lastChild) { parent.removeChild(parent.lastChild) } } function replaceLocation(delta: Delta.ReplaceDelta): void { location.replace(delta.Location) } function swapChildren(step: Delta.SwapChildrenDelta): void { const el = document.getElementById(step.ParentId) const node1 = el.childNodes[step.Index1] const node2 = el.childNodes[step.Index2] swapDom(node1, node2) } function swapDom(obj1: Node, obj2: Node): void { const temp = document.createElement("div") obj1.parentNode.insertBefore(temp, obj1) obj2.parentNode.insertBefore(obj1, obj2) temp.parentNode.insertBefore(obj2, temp) temp.parentNode.removeChild(temp) } function removeElementId(delta: Delta.RemoveElement): void { const element = document.getElementById(delta.ElementId) element.remove() } function unRender(delta: Delta.UnRenderDelta): void { const node = locateNode(delta.Locator) const stub = document.createElement("script") if (node instanceof Element) { stub.id = node.id } stub.type = "placeholder/lara" node.parentElement.replaceChild(stub, node) } function locateNode(locator: Delta.NodeLocator): ChildNode { const element = document.getElementById(locator.StartingId) const index = locator.ChildIndex if (index == 0 || index > 0) { return element.childNodes[index] } return element }
the_stack
// Copyright (c) 2012-2021 lfortin // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. const os = require('os'), events = require('events'), stream = require('readable-stream'), _ = require('underscore'), { version } = require('./package.json'), critical: number = os.cpus().length; class Monitor extends stream.Readable { constructor() { super({highWaterMark: 102400}); } public get version(): string { return version; } public get constants(): MonitorConstants { return { events: { MONITOR: 'monitor', UPTIME: 'uptime', FREEMEM: 'freemem', LOADAVG1: 'loadavg1', LOADAVG5: 'loadavg5', LOADAVG15: 'loadavg15', START: 'start', STOP: 'stop', CONFIG: 'config', RESET: 'reset', DESTROY: 'destroy' }, defaults: { delay : 3000, critical1 : critical, critical5 : critical, critical15: critical, freemem : 0, uptime : 0, silent : false, stream : false, immediate : false } }; } // expose Thenable class public Thenable: typeof Thenable = Thenable; // expose main Monitor class public Monitor: typeof Monitor = Monitor; // expose OS module public os = os; // expose Underscore public _ = _; private _monitorState: MonitorState = { running: false, ended: false, streamBuffering: true, interval: undefined, config: Monitor.prototype.constants.defaults, throttled: [] }; // readable stream implementation requirement private _read(): void { this._monitorState.streamBuffering = true; } public sendEvent(event: string, obj: InfoObject = {}): Monitor { let eventObject: EventObject = _.extend({type: event, timestamp: Math.floor(_.now() / 1000)}, obj); // for EventEmitter this.emit(event, eventObject); // for readable Stream if(this.config().stream && this._monitorState.streamBuffering) { let prettyJSON = JSON.stringify(eventObject, null, 2); if(!this.push(`${os.EOL}${prettyJSON}`)) { this._monitorState.streamBuffering = false; } } return this; } private _cycle(): void { let info: InfoObject = { loadavg : os.loadavg(), uptime : os.uptime(), freemem : os.freemem(), totalmem : os.totalmem() }, config = this.config(), freemem = (config.freemem < 1) ? config.freemem * info.totalmem : config.freemem; if(!config.silent) { this.sendEvent(this.constants.events.MONITOR, info); } if(info.loadavg[0] > config.critical1) { this.sendEvent(this.constants.events.LOADAVG1, info); } if(info.loadavg[1] > config.critical5) { this.sendEvent(this.constants.events.LOADAVG5, info); } if(info.loadavg[2] > config.critical15) { this.sendEvent(this.constants.events.LOADAVG15, info); } if(info.freemem < freemem) { this.sendEvent(this.constants.events.FREEMEM, info); } if(Number(config.uptime) && info.uptime > Number(config.uptime)) { this.sendEvent(this.constants.events.UPTIME, info); } } public start(options?: ConfigObject): Monitor { if(this._isEnded()) { this.emit('error', new Error("monitor has been ended by .destroy() method")); return this; } this.stop() .config(options); if(this.config().immediate) { process.nextTick(() => this._cycle()); } this._monitorState.interval = setInterval(() => this._cycle(), this.config().delay); this._monitorState.running = true; this.sendEvent(this.constants.events.START); return this; } public stop(): Monitor { clearInterval(this._monitorState.interval); if(this.isRunning()) { this._monitorState.running = false; this.sendEvent(this.constants.events.STOP); } return this; } public reset(): Monitor { this.sendEvent(this.constants.events.RESET); this[this.isRunning() ? 'start' : 'config'](this.constants.defaults); return this; }; public destroy(err?: unknown): Monitor { if(!this._isEnded()) { this.sendEvent(this.constants.events.DESTROY); this.stop(); this.emit('close'); stream.Readable.prototype.destroy.apply(this, [err]); this._monitorState.ended = true; } return this; } public config(options?: ConfigObject): ConfigObject { if(_.isObject(options)) { _.extend(this._monitorState.config, options); this.sendEvent(this.constants.events.CONFIG, { options: _.clone(options) }); } return this._monitorState.config; } public isRunning(): boolean { return !!this._monitorState.running; } private _isEnded(): boolean { return !!this._monitorState.ended; } public throttle(event: string, handler: Function, wait: number): Monitor { let self = this, _handler = _.wrap(handler, function(fn: Function) { if(self.isRunning()) { fn.apply(self, _.toArray(arguments).slice(1)); } }), throttledFn = _.throttle(_handler, wait || this.config().throttle); this._monitorState.throttled.push({originalFn: handler, throttledFn: throttledFn}); return this.on(event, throttledFn); } public unthrottle(event: string, handler: Function): Monitor { const throttled = this._monitorState.throttled; for(let i = throttled.length - 1; i >= 0; i--) { let pair = throttled[i]; if(pair.originalFn === handler) { this.removeListener(event, pair.throttledFn); throttled.splice(i, 1); } } return this; } public when(event: string): Promise<EventObjectThenable> | EventObjectThenable { let deferred: EventObjectThenable = new Thenable(); let wrappedDeferred: Promise<EventObjectThenable>; this.once(event, (eventObj: EventObject) => { deferred.resolve(eventObj); }); try { wrappedDeferred = Promise.resolve(deferred); return wrappedDeferred; } catch(err: unknown) { return deferred; } } /* * convenience methods */ private _sanitizeNumber(n: number): number { if(!_.isNumber(n)) { throw new Error("Number expected"); } if(!n || n < 0) { throw new Error("Number must be greater than 0"); } // Math.pow(2, 31); if(n >= 2147483648) { throw new Error("Number must be smaller than 2147483648"); } return n; } public seconds(n: number): number { return this._sanitizeNumber(n * 1000); } public minutes(n: number): number { return this._sanitizeNumber(n * this.seconds(60)); }; public hours(n: number): number { return this._sanitizeNumber(n * this.minutes(60)); }; public days(n: number): number { return this._sanitizeNumber(n * this.hours(24)); }; }; class Thenable<Type> extends events.EventEmitter { constructor() { super(); } static constants = { state: { PENDING: 'pending', FULFILLED: 'fulfilled', REJECTED: 'rejected' } }; private _thenableState = { state: Thenable.constants.state.PENDING, result: undefined }; public resolve(result: Type): Thenable<Type> { const state = Thenable.constants.state; if(this._thenableState.state === state.PENDING) { this._thenableState.state = state.FULFILLED; this._thenableState.result = result; this.emit('resolve', result); } return this; } public reject(error: unknown): Thenable<Type> { const state = Thenable.constants.state; if(this._thenableState.state === state.PENDING) { this._thenableState.state = state.REJECTED; this._thenableState.result = error; this.emit('reject', error); } return this; } public then(onFulfilled: Function | undefined, onRejected: Function | undefined): void { const state = Thenable.constants.state; if(this._thenableState.state === state.PENDING) { this.once('resolve', (result: EventObject) => { this._callOnFulfilled(onFulfilled); }); this.once('reject', error => { this._callOnRejected(onRejected); }); } this._callOnFulfilled(onFulfilled); this._callOnRejected(onRejected); } public catch(onRejected: Function | undefined): void { return this.then(undefined, onRejected); } private _callOnFulfilled(onFulfilled: Function): void { const state = Thenable.constants.state; if(onFulfilled && this._thenableState.state === state.FULFILLED) { onFulfilled(this._thenableState.result); } } private _callOnRejected(onRejected: Function): void { const state = Thenable.constants.state; if(onRejected && this._thenableState.state === state.REJECTED) { onRejected(this._thenableState.result); } } } module.exports = new Monitor(); interface ConfigObject { delay? : number; critical1? : number; critical5? : number; critical15?: number; freemem? : number; uptime? : number; silent? : boolean; stream? : boolean; immediate? : boolean; throttle? : number; } interface MonitorState { running: boolean; ended: boolean; streamBuffering: boolean; interval: NodeJS.Timeout; config: ConfigObject; throttled: Array<{ originalFn: Function, throttledFn: Function }>; } interface MonitorConstants { events: { MONITOR: string; UPTIME: string; FREEMEM: string; LOADAVG1: string; LOADAVG5: string; LOADAVG15: string; START: string; STOP: string; CONFIG: string; RESET: string; DESTROY: string; }, defaults: ConfigObject } interface InfoObject { loadavg? : Array<number>; uptime? : number; freemem? : number; totalmem? : number; options? : ConfigObject; } interface EventObject extends InfoObject { type : string; timestamp : number; } type EventObjectThenable = Thenable<EventObject>;
the_stack
import * as helper from "./tools/helper"; const document = helper.getDocument("qwery.html"); import * as CSSselect from "../src"; import * as DomUtils from "domutils"; import type { Element } from "domhandler"; import { parseDOM } from "htmlparser2"; const location = { hash: "" }; CSSselect.pseudos.target = (elem, { adapter }) => adapter.getAttributeValue(elem, "id") === location.hash.substr(1); // --- /* * Adapted from https://github.com/ded/qwery/blob/master/tests/tests.js */ CSSselect.pseudos.humanoid = (e) => CSSselect.is(e, ":matches(li,ol):contains(human)"); const frag = parseDOM( '<root><div class="d i v">' + '<p id="oooo"><em></em><em id="emem"></em></p>' + "</div>" + '<p id="sep">' + '<div class="a"><span></span></div>' + "</p></root>" ); const doc = parseDOM( '<root><div id="hsoob">' + '<div class="a b">' + '<div class="d e sib" test="fg" id="booshTest"><p><span id="spanny"></span></p></div>' + '<em nopass="copyrighters" rel="copyright booshrs" test="f g" class="sib"></em>' + '<span class="h i a sib"></span>' + "</div>" + '<p class="odd"></p>' + "</div>" + '<div id="lonelyHsoob"></div></root>' ); const el = DomUtils.getElementById("attr-child-boosh", document); if (!el) throw new Error("Couldn't find element"); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const pseudos = DomUtils.getElementById("pseudos", document)!.children.filter( DomUtils.isTag ); describe("qwery", () => { describe("Contexts", () => { it("should be able to pass optional context", () => { expect(CSSselect.selectAll(".a", document)).toHaveLength(3); // No context found 3 elements (.a) expect( CSSselect.selectAll( ".a", CSSselect.selectAll("#boosh", document) ) ).toHaveLength(2); // Context found 2 elements (#boosh .a) }); it("should be able to pass qwery result as context", () => { expect( CSSselect.selectAll( ".a", CSSselect.selectAll("#boosh", document) ) ).toHaveLength(2); // Context found 2 elements(.a, #boosh) expect( CSSselect.selectAll("> .a", CSSselect.selectAll(".a", document)) ).toHaveLength(1); // Context found 0 elements(.a, .a) expect( CSSselect.selectAll("> .a", CSSselect.selectAll(".b", document)) ).toHaveLength(1); // Context found 1 elements(.a, .b) expect( CSSselect.selectAll( "> .a", CSSselect.selectAll("#boosh .b", document) ) ).toHaveLength(1); // Context found 1 elements(.a, #boosh .b) expect( CSSselect.selectAll( "> .b", CSSselect.selectAll("#boosh .b", document) ) ).toHaveLength(0); // Context found 0 elements(.b, #boosh .b) }); it("should not return duplicates from combinators", () => { expect(CSSselect.selectAll("#boosh,#boosh", document)).toHaveLength( 1 ); // Two booshes dont make a thing go right expect( CSSselect.selectAll("#boosh,.apples,#boosh", document) ).toHaveLength(1); // Two booshes and an apple dont make a thing go right }); it("byId sub-queries within context", () => { expect( CSSselect.selectAll( "#booshTest", CSSselect.selectAll("#boosh", document) ) ).toHaveLength(1); // Found "#id #id" expect( CSSselect.selectAll( ".a.b #booshTest", CSSselect.selectAll("#boosh", document) ) ).toHaveLength(1); // Found ".class.class #id" expect( CSSselect.selectAll( ".a>#booshTest", CSSselect.selectAll("#boosh", document) ) ).toHaveLength(1); // Found ".class>#id" expect( CSSselect.selectAll( ">.a>#booshTest", CSSselect.selectAll("#boosh", document) ) ).toHaveLength(1); // Found ">.class>#id" expect( CSSselect.selectAll( "#boosh", CSSselect.selectAll("#booshTest", document) ) ).toHaveLength(0); // Shouldn't find #boosh (ancestor) within #booshTest (descendent) expect( CSSselect.selectAll( "#boosh", CSSselect.selectAll("#lonelyBoosh", document) ) ).toHaveLength(0); // Shouldn't find #boosh within #lonelyBoosh (unrelated) }); }); describe("CSS 1", () => { it("get element by id", () => { const result = CSSselect.selectAll("#boosh", document); expect(result[0]).toBeTruthy(); // Found element with id=boosh expect(CSSselect.selectAll("h1", document)[0]).toBeTruthy(); // Found 1 h1 }); it("byId sub-queries", () => { expect( CSSselect.selectAll("#boosh #booshTest", document) ).toHaveLength(1); // Found "#id #id" expect( CSSselect.selectAll(".a.b #booshTest", document) ).toHaveLength(1); // Found ".class.class #id" expect( CSSselect.selectAll("#boosh>.a>#booshTest", document) ).toHaveLength(1); // Found "#id>.class>#id" expect(CSSselect.selectAll(".a>#booshTest", document)).toHaveLength( 1 ); // Found ".class>#id" }); it("get elements by class", () => { expect(CSSselect.selectAll("#boosh .a", document)).toHaveLength(2); // Found two elements expect( CSSselect.selectAll("#boosh div.a", document)[0] ).toBeTruthy(); // Found one element expect(CSSselect.selectAll("#boosh div", document)).toHaveLength(2); // Found two {div} elements expect( CSSselect.selectAll("#boosh span", document)[0] ).toBeTruthy(); // Found one {span} element expect( CSSselect.selectAll("#boosh div div", document)[0] ).toBeTruthy(); // Found a single div expect(CSSselect.selectAll("a.odd", document)).toHaveLength(1); // Found single a }); it("combos", () => { expect( CSSselect.selectAll("#boosh div,#boosh span", document) ).toHaveLength(3); // Found 2 divs and 1 span }); it("class with dashes", () => { expect( CSSselect.selectAll(".class-with-dashes", document) ).toHaveLength(1); // Found something }); it("should ignore comment nodes", () => { expect(CSSselect.selectAll("#boosh *", document)).toHaveLength(4); // Found only 4 elements under #boosh }); it("deep messy relationships", () => { /* * These are mostly characterised by a combination of tight relationships and loose relationships * on the right side of the query it's easy to find matches but they tighten up quickly as you * go to the left * they are useful for making sure the dom crawler doesn't stop short or over-extend as it works * up the tree the crawl needs to be comprehensive */ expect( CSSselect.selectAll("div#fixtures > div a", document) ).toHaveLength(5); // Found four results for "div#fixtures > div a" expect( CSSselect.selectAll( ".direct-descend > .direct-descend .lvl2", document ) ).toHaveLength(1); // Found one result for ".direct-descend > .direct-descend .lvl2" expect( CSSselect.selectAll( ".direct-descend > .direct-descend div", document ) ).toHaveLength(1); // Found one result for ".direct-descend > .direct-descend div" expect( CSSselect.selectAll( ".direct-descend > .direct-descend div", document ) ).toHaveLength(1); // Found one result for ".direct-descend > .direct-descend div" expect( CSSselect.selectAll("div#fixtures div ~ a div", document) ).toHaveLength(0); // Found no results for odd query expect( CSSselect.selectAll( ".direct-descend > .direct-descend > .direct-descend ~ .lvl2", document ) ).toHaveLength(0); // Found no results for another odd query }); }); describe("CSS 2", () => { it("get elements by attribute", () => { const wanted = CSSselect.selectAll("#boosh div[test]", document)[0]; const expected = DomUtils.getElementById("booshTest", document); expect(wanted).toBe(expected); // Found attribute expect( CSSselect.selectAll("#boosh div[test=fg]", document)[0] ).toBe(expected); // Found attribute with value expect( CSSselect.selectAll('em[rel~="copyright"]', document) ).toHaveLength(1); // Found em[rel~="copyright"] expect( CSSselect.selectAll('em[nopass~="copyright"]', document) ).toHaveLength(0); // Found em[nopass~="copyright"] }); it("should not throw error by attribute selector", () => { expect(CSSselect.selectAll('[foo^="bar"]', document)).toHaveLength( 1 ); // Found 1 element }); it("crazy town", () => { const el = DomUtils.getElementById("attr-test3", document); expect( CSSselect.selectAll( 'div#attr-test3.found.you[title="whatup duders"]', document )[0] ).toBe(el); // Found the right element }); }); describe("attribute selectors", () => { /* CSS 2 SPEC */ it("[attr]", () => { const expected = DomUtils.getElementById("attr-test-1", document); expect( CSSselect.selectAll("#attributes div[unique-test]", document)[0] ).toBe(expected); // Found attribute with [attr] }); it("[attr=val]", () => { const expected = DomUtils.getElementById("attr-test-2", document); expect( CSSselect.selectAll( '#attributes div[test="two-foo"]', document )[0] ).toBe(expected); // Found attribute with = expect( CSSselect.selectAll( "#attributes div[test='two-foo']", document )[0] ).toBe(expected); // Found attribute with = expect( CSSselect.selectAll( "#attributes div[test=two-foo]", document )[0] ).toBe(expected); // Found attribute with = }); it("[attr~=val]", () => { const expected = DomUtils.getElementById("attr-test-3", document); expect( CSSselect.selectAll("#attributes div[test~=three]", document)[0] ).toBe(expected); // Found attribute with ~= }); it("[attr|=val]", () => { const expected = DomUtils.getElementById("attr-test-2", document); expect( CSSselect.selectAll( '#attributes div[test|="two-foo"]', document )[0] ).toBe(expected); // Found attribute with |= expect( CSSselect.selectAll("#attributes div[test|=two]", document)[0] ).toBe(expected); // Found attribute with |= }); it("[href=#x] special case", () => { const expected = DomUtils.getElementById("attr-test-4", document); expect( CSSselect.selectAll('#attributes a[href="#aname"]', document)[0] ).toBe(expected); // Found attribute with href=#x }); /* CSS 3 SPEC */ it("[attr^=val]", () => { const expected = DomUtils.getElementById("attr-test-2", document); expect( CSSselect.selectAll("#attributes div[test^=two]", document)[0] ).toBe(expected); // Found attribute with ^= }); it("[attr$=val]", () => { const expected = DomUtils.getElementById("attr-test-2", document); expect( CSSselect.selectAll("#attributes div[test$=foo]", document)[0] ).toBe(expected); // Found attribute with $= }); it("[attr*=val]", () => { const expected = DomUtils.getElementById("attr-test-3", document); expect( CSSselect.selectAll("#attributes div[test*=hree]", document)[0] ).toBe(expected); // Found attribute with *= }); it("direct descendants", () => { expect( CSSselect.selectAll( "#direct-descend > .direct-descend", document ) ).toHaveLength(2); // Found two direct descendents expect( CSSselect.selectAll( "#direct-descend > .direct-descend > .lvl2", document ) ).toHaveLength(3); // Found three second-level direct descendents }); it("sibling elements", () => { expect( CSSselect.selectAll( "#sibling-selector ~ .sibling-selector", document ) ).toHaveLength(2); // Found two siblings expect( CSSselect.selectAll( "#sibling-selector ~ div.sibling-selector", document ) ).toHaveLength(2); // Found two siblings expect( CSSselect.selectAll( "#sibling-selector + div.sibling-selector", document ) ).toHaveLength(1); // Found one sibling expect( CSSselect.selectAll( "#sibling-selector + .sibling-selector", document ) ).toHaveLength(1); // Found one sibling expect( CSSselect.selectAll(".parent .oldest ~ .sibling", document) ).toHaveLength(4); // Found four younger siblings expect( CSSselect.selectAll(".parent .middle ~ .sibling", document) ).toHaveLength(2); // Found two younger siblings expect( CSSselect.selectAll(".parent .middle ~ h4", document) ).toHaveLength(1); // Found next sibling by tag expect( CSSselect.selectAll(".parent .middle ~ h4.younger", document) ).toHaveLength(1); // Found next sibling by tag and class expect( CSSselect.selectAll(".parent .middle ~ h3", document) ).toHaveLength(0); // An element can't be its own sibling expect( CSSselect.selectAll(".parent .middle ~ h2", document) ).toHaveLength(0); // Didn't find an older sibling expect( CSSselect.selectAll(".parent .youngest ~ .sibling", document) ).toHaveLength(0); // Found no younger siblings expect( CSSselect.selectAll(".parent .oldest + .sibling", document) ).toHaveLength(1); // Found next sibling expect( CSSselect.selectAll(".parent .middle + .sibling", document) ).toHaveLength(1); // Found next sibling expect( CSSselect.selectAll(".parent .middle + h4", document) ).toHaveLength(1); // Found next sibling by tag expect( CSSselect.selectAll(".parent .middle + h3", document) ).toHaveLength(0); // An element can't be its own sibling expect( CSSselect.selectAll(".parent .middle + h2", document) ).toHaveLength(0); // Didn't find an older sibling expect( CSSselect.selectAll(".parent .youngest + .sibling", document) ).toHaveLength(0); // Found no younger siblings }); }); describe("element-context queries", () => { it("relationship-first queries", () => { expect( CSSselect.selectAll( "> .direct-descend", CSSselect.selectAll("#direct-descend", document) ) ).toHaveLength(2); // Found two direct descendents using > first expect( CSSselect.selectAll( "~ .sibling-selector", CSSselect.selectAll("#sibling-selector", document) ) ).toHaveLength(2); // Found two siblings with ~ first expect( CSSselect.selectAll( "+ .sibling-selector", CSSselect.selectAll("#sibling-selector", document) ) ).toHaveLength(1); // Found one sibling with + first expect( CSSselect.selectAll( "> .tokens a", CSSselect.selectAll(".idless", document)[0] ) ).toHaveLength(1); // Found one sibling from a root with no id }); // Should be able to query on an element that hasn't been inserted into the dom it("detached fragments", () => { expect(CSSselect.selectAll(".a span", frag)).toHaveLength(1); // Should find child elements of fragment expect(CSSselect.selectAll("> div p em", frag)).toHaveLength(2); // Should find child elements of fragment, relationship first }); it("byId sub-queries within detached fragment", () => { expect(CSSselect.selectAll("#emem", frag)).toHaveLength(1); // Found "#id" in fragment expect(CSSselect.selectAll(".d.i #emem", frag)).toHaveLength(1); // Found ".class.class #id" in fragment expect(CSSselect.selectAll(".d #oooo #emem", frag)).toHaveLength(1); // Found ".class #id #id" in fragment expect(CSSselect.selectAll("> div #oooo", frag)).toHaveLength(1); // Found "> .class #id" in fragment expect( CSSselect.selectAll("#oooo", CSSselect.selectAll("#emem", frag)) ).toHaveLength(0); // Shouldn't find #oooo (ancestor) within #emem (descendent) expect( CSSselect.selectAll("#sep", CSSselect.selectAll("#emem", frag)) ).toHaveLength(0); // Shouldn't find #sep within #emem (unrelated) }); it("exclude self in match", () => { expect( CSSselect.selectAll( ".order-matters", CSSselect.selectAll("#order-matters", document)[0] ) ).toHaveLength(4); // Should not include self in element-context queries }); // Because form's have .length it("forms can be used as contexts", () => { expect( CSSselect.selectAll( "*", CSSselect.selectAll("form", document)[0] ) ).toHaveLength(3); // Found 3 elements under &lt;form&gt; }); }); describe("tokenizer", () => { it("should not get weird tokens", () => { expect( CSSselect.selectAll('div .tokens[title="one"]', document)[0] ).toBe(DomUtils.getElementById("token-one", document)); // Found div .tokens[title="one"] expect( CSSselect.selectAll('div .tokens[title="one two"]', document)[0] ).toBe(DomUtils.getElementById("token-two", document)); // Found div .tokens[title="one two"] expect( CSSselect.selectAll( 'div .tokens[title="one two three #%"]', document )[0] ).toBe(DomUtils.getElementById("token-three", document)); // Found div .tokens[title="one two three #%"] expect( CSSselect.selectAll( "div .tokens[title='one two three #%'] a", document )[0] ).toBe(DomUtils.getElementById("token-four", document)); // Found div .tokens[title=\'one two three #%\'] a expect( CSSselect.selectAll( 'div .tokens[title="one two three #%"] a[href$=foo] div', document )[0] ).toBe(DomUtils.getElementById("token-five", document)); // Found div .tokens[title="one two three #%"] a[href=foo] div }); }); describe("interesting syntaxes", () => { it("should parse bad selectors", () => { expect( CSSselect.selectAll("#spaced-tokens p em a", document) .length ).toBeTruthy(); // Found element with funny tokens }); }); describe("order matters", () => { /* * <div id="order-matters"> * <p class="order-matters"></p> * <a class="order-matters"> * <em class="order-matters"></em><b class="order-matters"></b> * </a> * </div> */ it("the order of elements return matters", () => { function tag(el: Element) { return el.name.toLowerCase(); } const els = CSSselect.selectAll( "#order-matters .order-matters", document ) as Element[]; expect(tag(els[0])).toBe("p"); // First element matched is a {p} tag expect(tag(els[1])).toBe("a"); // First element matched is a {a} tag expect(tag(els[2])).toBe("em"); // First element matched is a {em} tag expect(tag(els[3])).toBe("b"); // First element matched is a {b} tag }); }); describe("pseudo-selectors", () => { it(":contains", () => { expect( CSSselect.selectAll("li:contains(humans)", document) ).toHaveLength(1); // Found by "element:contains(text)" expect( CSSselect.selectAll(":contains(humans)", document) ).toHaveLength(5); // Found by ":contains(text)", including all ancestors // * Is an important case, can cause weird errors expect( CSSselect.selectAll("*:contains(humans)", document) ).toHaveLength(5); // Found by "*:contains(text)", including all ancestors expect( CSSselect.selectAll("ol:contains(humans)", document) ).toHaveLength(1); // Found by "ancestor:contains(text)" }); it(":not", () => { expect(CSSselect.selectAll(".odd:not(div)", document)).toHaveLength( 1 ); // Found one .odd :not an &lt;a&gt; }); it(":first-child", () => { expect( CSSselect.selectAll("#pseudos div:first-child", document)[0] ).toBe(pseudos[0]); // Found first child expect( CSSselect.selectAll("#pseudos div:first-child", document) ).toHaveLength(1); // Found only 1 }); it(":last-child", () => { const all = DomUtils.getElementsByTagName("div", pseudos); expect( CSSselect.selectAll("#pseudos div:last-child", document)[0] ).toBe(all[all.length - 1]); // Found last child expect( CSSselect.selectAll("#pseudos div:last-child", document) ).toHaveLength(1); // Found only 1 }); it('ol > li[attr="boosh"]:last-child', () => { const expected = DomUtils.getElementById( "attr-child-boosh", document ); expect( CSSselect.selectAll( 'ol > li[attr="boosh"]:last-child', document ) ).toHaveLength(1); // Only 1 element found expect( CSSselect.selectAll( 'ol > li[attr="boosh"]:last-child', document )[0] ).toBe(expected); // Found correct element }); it(":nth-child(odd|even|x)", () => { const second = DomUtils.getElementsByTagName("div", pseudos)[1]; expect( CSSselect.selectAll("#pseudos :nth-child(odd)", document) ).toHaveLength(4); // Found 4 odd elements expect( CSSselect.selectAll("#pseudos div:nth-child(odd)", document) ).toHaveLength(3); // Found 3 odd elements with div tag expect( CSSselect.selectAll("#pseudos div:nth-child(even)", document) ).toHaveLength(3); // Found 3 even elements with div tag expect( CSSselect.selectAll("#pseudos div:nth-child(2)", document)[0] ).toBe(second); // Found 2nd nth-child of pseudos }); it(":nth-child(expr)", () => { const fifth = DomUtils.getElementsByTagName("a", pseudos)[0]; const sixth = DomUtils.getElementsByTagName("div", pseudos)[4]; expect( CSSselect.selectAll("#pseudos :nth-child(3n+1)", document) ).toHaveLength(3); // Found 3 elements expect( CSSselect.selectAll("#pseudos :nth-child(+3n-2)", document) ).toHaveLength(3); // Found 3 elements' expect( CSSselect.selectAll("#pseudos :nth-child(-n+6)", document) ).toHaveLength(6); // Found 6 elements expect( CSSselect.selectAll("#pseudos :nth-child(-n+5)", document) ).toHaveLength(5); // Found 5 elements expect( CSSselect.selectAll("#pseudos :nth-child(3n+2)", document)[1] ).toBe(fifth); // Second :nth-child(3n+2) is the fifth child expect( CSSselect.selectAll("#pseudos :nth-child(3n)", document)[1] ).toBe(sixth); // Second :nth-child(3n) is the sixth child }); it(":nth-last-child(odd|even|x)", () => { const second = DomUtils.getElementsByTagName("div", pseudos)[1]; expect( CSSselect.selectAll("#pseudos :nth-last-child(odd)", document) ).toHaveLength(4); // Found 4 odd elements expect( CSSselect.selectAll( "#pseudos div:nth-last-child(odd)", document ) ).toHaveLength(3); // Found 3 odd elements with div tag expect( CSSselect.selectAll( "#pseudos div:nth-last-child(even)", document ) ).toHaveLength(3); // Found 3 even elements with div tag expect( CSSselect.selectAll( "#pseudos div:nth-last-child(6)", document )[0] ).toBe(second); // 6th nth-last-child should be 2nd of 7 elements }); it(":nth-last-child(expr)", () => { const third = DomUtils.getElementsByTagName("div", pseudos)[2]; expect( CSSselect.selectAll("#pseudos :nth-last-child(3n+1)", document) ).toHaveLength(3); // Found 3 elements expect( CSSselect.selectAll("#pseudos :nth-last-child(3n-2)", document) ).toHaveLength(3); // Found 3 elements expect( CSSselect.selectAll("#pseudos :nth-last-child(-n+6)", document) ).toHaveLength(6); // Found 6 elements expect( CSSselect.selectAll("#pseudos :nth-last-child(-n+5)", document) ).toHaveLength(5); // Found 5 elements expect( CSSselect.selectAll( "#pseudos :nth-last-child(3n+2)", document )[0] ).toBe(third); // First :nth-last-child(3n+2) is the third child }); it(":nth-of-type(expr)", () => { const a = DomUtils.getElementsByTagName("a", pseudos)[0]; expect( CSSselect.selectAll("#pseudos div:nth-of-type(3n+1)", document) ).toHaveLength(2); // Found 2 div elements expect( CSSselect.selectAll("#pseudos a:nth-of-type(3n+1)", document) ).toHaveLength(1); // Found 1 a element expect( CSSselect.selectAll("#pseudos a:nth-of-type(3n+1)", document)[0] ).toBe(a); // Found the right a element expect( CSSselect.selectAll("#pseudos a:nth-of-type(3n)", document) ).toHaveLength(0); // No matches for every third a expect( CSSselect.selectAll("#pseudos a:nth-of-type(odd)", document) ).toHaveLength(1); // Found the odd a expect( CSSselect.selectAll("#pseudos a:nth-of-type(1)", document) ).toHaveLength(1); // Found the first a }); it(":nth-last-of-type(expr)", () => { const second = DomUtils.getElementsByTagName("div", pseudos)[1]; expect( CSSselect.selectAll( "#pseudos div:nth-last-of-type(3n+1)", document ) ).toHaveLength(2); // Found 2 div elements expect( CSSselect.selectAll( "#pseudos a:nth-last-of-type(3n+1)", document ) ).toHaveLength(1); // Found 1 a element expect( CSSselect.selectAll( "#pseudos div:nth-last-of-type(5)", document )[0] ).toBe(second); // 5th nth-last-of-type should be 2nd of 7 elements }); it(":first-of-type", () => { expect( CSSselect.selectAll("#pseudos a:first-of-type", document)[0] ).toBe(DomUtils.getElementsByTagName("a", pseudos)[0]); // Found first a element expect( CSSselect.selectAll("#pseudos a:first-of-type", document) ).toHaveLength(1); // Found only 1 }); it(":last-of-type", () => { const all = DomUtils.getElementsByTagName("div", pseudos); expect( CSSselect.selectAll("#pseudos div:last-of-type", document)[0] ).toBe(all[all.length - 1]); // Found last div element expect( CSSselect.selectAll("#pseudos div:last-of-type", document) ).toHaveLength(1); // Found only 1 }); it(":only-of-type", () => { expect( CSSselect.selectAll("#pseudos a:only-of-type", document)[0] ).toBe(DomUtils.getElementsByTagName("a", pseudos)[0]); // Found the only a element expect( CSSselect.selectAll("#pseudos a:first-of-type", document) ).toHaveLength(1); // Found only 1 }); it(":target", () => { location.hash = ""; expect( CSSselect.selectAll("#pseudos:target", document) ).toHaveLength(0); // #pseudos is not the target location.hash = "#pseudos"; expect( CSSselect.selectAll("#pseudos:target", document) ).toHaveLength(1); // Now #pseudos is the target location.hash = ""; }); it("custom pseudos", () => { // :humanoid implemented just for testing purposes expect(CSSselect.selectAll(":humanoid", document)).toHaveLength(2); // Selected using custom pseudo }); }); describe("is()", () => { it("simple selectors", () => { expect(CSSselect.is(el, "li")).toBeTruthy(); // Tag expect(CSSselect.is(el, "*")).toBeTruthy(); // Wildcard expect(CSSselect.is(el, "#attr-child-boosh")).toBeTruthy(); // #id expect(CSSselect.is(el, "[attr]")).toBeTruthy(); // [attr] expect(CSSselect.is(el, "[attr=boosh]")).toBeTruthy(); // [attr=val] expect(CSSselect.is(el, "div")).toBeFalsy(); // Wrong tag expect(CSSselect.is(el, "#foo")).toBeFalsy(); // Wrong #id expect(CSSselect.is(el, "[foo]")).toBeFalsy(); // Wrong [attr] expect(CSSselect.is(el, "[attr=foo]")).toBeFalsy(); // Wrong [attr=val] }); it("selector sequences", () => { expect( CSSselect.is(el, "li#attr-child-boosh[attr=boosh]") ).toBeTruthy(); // Tag#id[attr=val] expect( CSSselect.is(el, "div#attr-child-boosh[attr=boosh]") ).toBeFalsy(); // Wrong tag#id[attr=val] }); it("selector sequences combinators", () => { expect(CSSselect.is(el, "ol li")).toBeTruthy(); // Tag tag expect(CSSselect.is(el, "ol>li")).toBeTruthy(); // Tag>tag expect(CSSselect.is(el, "ol>li+li")).toBeTruthy(); // Tab>tag+tag expect( CSSselect.is(el, "ol#list li#attr-child-boosh[attr=boosh]") ).toBeTruthy(); // Tag#id tag#id[attr=val] expect( CSSselect.is(el, "ol#list>li#attr-child-boosh[attr=boosh]") ).toBeFalsy(); // Wrong tag#id>tag#id[attr=val] expect( CSSselect.is(el, "ol ol li#attr-child-boosh[attr=boosh]") ).toBeTruthy(); // Tag tag tag#id[attr=val] expect( CSSselect.is( CSSselect.selectAll("#token-four", document)[0], "div#fixtures>div a" ) ).toBeTruthy(); // Tag#id>tag tag where ambiguous middle tag requires backtracking }); it("pseudos", () => { expect(CSSselect.is(el, "li:contains(hello)")).toBe(true); // Matching :contains(text) expect(CSSselect.is(el, "li:contains(human)")).toBe(false); // Non-matching :contains(text) expect( CSSselect.is( CSSselect.selectAll("#list>li", document)[2], ":humanoid" ) ).toBe(true); // Matching custom pseudo expect( CSSselect.is( CSSselect.selectAll("#list>li", document)[1], ":humanoid" ) ).toBe(false); // Non-matching custom pseudo }); it("context", () => { expect( CSSselect.is(el, "li#attr-child-boosh[attr=boosh]", { context: CSSselect.selectAll( "#list", document )[0] as Element, }) ).toBeTruthy(); // Context expect( CSSselect.is(el, "ol#list li#attr-child-boosh[attr=boosh]", { context: CSSselect.selectAll( "#boosh", document )[0] as Element, }) ).toBeFalsy(); // Wrong context }); }); describe("selecting elements in other documents", () => { it("get element by id", () => { const result = CSSselect.selectAll("#hsoob", doc); expect(result[0]).toBeTruthy(); // Found element with id=hsoob }); it("get elements by class", () => { expect(CSSselect.selectAll("#hsoob .a", doc)).toHaveLength(2); // Found two elements expect(CSSselect.selectAll("#hsoob div.a", doc)[0]).toBeTruthy(); // Found one element expect(CSSselect.selectAll("#hsoob div", doc)).toHaveLength(2); // Found two {div} elements expect(CSSselect.selectAll("#hsoob span", doc)[0]).toBeTruthy(); // Found one {span} element expect(CSSselect.selectAll("#hsoob div div", doc)[0]).toBeTruthy(); // Found a single div expect(CSSselect.selectAll("p.odd", doc)).toHaveLength(1); // Found single br }); it("complex selectors", () => { expect(CSSselect.selectAll(".d ~ .sib", doc)).toHaveLength(2); // Found one ~ sibling expect(CSSselect.selectAll(".a .d + .sib", doc)).toHaveLength(1); // Found 2 + siblings expect(CSSselect.selectAll("#hsoob > div > .h", doc)).toHaveLength( 1 ); // Found span using child selectors expect( CSSselect.selectAll('.a .d ~ .sib[test="f g"]', doc) ).toHaveLength(1); // Found 1 ~ sibling with test attribute }); it("byId sub-queries", () => { expect(CSSselect.selectAll("#hsoob #spanny", doc)).toHaveLength(1); // Found "#id #id" in frame expect(CSSselect.selectAll(".a #spanny", doc)).toHaveLength(1); // Found ".class #id" in frame expect( CSSselect.selectAll(".a #booshTest #spanny", doc) ).toHaveLength(1); // Found ".class #id #id" in frame expect(CSSselect.selectAll("> #hsoob", doc)).toHaveLength(1); // Found "> #id" in frame }); it("byId sub-queries within sub-context", () => { expect( CSSselect.selectAll( "#spanny", CSSselect.selectAll("#hsoob", doc) ) ).toHaveLength(1); // Found "#id -> #id" in frame expect( CSSselect.selectAll( ".a #spanny", CSSselect.selectAll("#hsoob", doc) ) ).toHaveLength(1); // Found ".class #id" in frame expect( CSSselect.selectAll( ".a #booshTest #spanny", CSSselect.selectAll("#hsoob", doc) ) ).toHaveLength(1); // Found ".class #id #id" in frame expect( CSSselect.selectAll( ".a > #booshTest", CSSselect.selectAll("#hsoob", doc) ) ).toHaveLength(1); // Found "> .class #id" in frame expect( CSSselect.selectAll( "#booshTest", CSSselect.selectAll("#spanny", doc) ) ).toHaveLength(0); // Shouldn't find #booshTest (ancestor) within #spanny (descendent) expect( CSSselect.selectAll( "#booshTest", CSSselect.selectAll("#lonelyHsoob", doc) ) ).toHaveLength(0); // Shouldn't find #booshTest within #lonelyHsoob (unrelated) }); }); });
the_stack
interface PromiseConstructor { /** * A reference to the prototype. */ readonly prototype: Promise<any> /** * Creates a new Promise. * @param executor A callback used to initialize the promise. This callback is passed two arguments: * a resolve callback used resolve the promise with a value or the result of another promise, * and a reject callback used to reject the promise with a provided reason or error. */ new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T> /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>( values: [ T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | PromiseLike<T10> ] ): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]> /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T1, T2, T3, T4, T5, T6, T7, T8, T9>( values: [ T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9> ] ): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]> /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T1, T2, T3, T4, T5, T6, T7, T8>( values: [ T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8> ] ): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]> /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T1, T2, T3, T4, T5, T6, T7>( values: [ T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7> ] ): Promise<[T1, T2, T3, T4, T5, T6, T7]> /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T1, T2, T3, T4, T5, T6>( values: [ T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6> ] ): Promise<[T1, T2, T3, T4, T5, T6]> /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T1, T2, T3, T4, T5>( values: [ T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5> ] ): Promise<[T1, T2, T3, T4, T5]> /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T1, T2, T3, T4>( values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>] ): Promise<[T1, T2, T3, T4]> /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T1, T2, T3>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<[T1, T2, T3]> /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T1, T2>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<[T1, T2]> /** * Creates a Promise that is resolved with an array of results when all of the provided Promises * resolve, or rejected when any Promise is rejected. * @param values An array of Promises. * @returns A new Promise. */ all<T>(values: (T | PromiseLike<T>)[]): Promise<T[]> /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>( values: [ T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | PromiseLike<T10> ] ): Promise<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9 | T10> /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T1, T2, T3, T4, T5, T6, T7, T8, T9>( values: [ T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9> ] ): Promise<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8 | T9> /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T1, T2, T3, T4, T5, T6, T7, T8>( values: [ T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8> ] ): Promise<T1 | T2 | T3 | T4 | T5 | T6 | T7 | T8> /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T1, T2, T3, T4, T5, T6, T7>( values: [ T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7> ] ): Promise<T1 | T2 | T3 | T4 | T5 | T6 | T7> /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T1, T2, T3, T4, T5, T6>( values: [ T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6> ] ): Promise<T1 | T2 | T3 | T4 | T5 | T6> /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T1, T2, T3, T4, T5>( values: [ T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>, T5 | PromiseLike<T5> ] ): Promise<T1 | T2 | T3 | T4 | T5> /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T1, T2, T3, T4>( values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike<T4>] ): Promise<T1 | T2 | T3 | T4> /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T1, T2, T3>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<T1 | T2 | T3> /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T1, T2>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<T1 | T2> /** * Creates a Promise that is resolved or rejected when any of the provided Promises are resolved * or rejected. * @param values An array of Promises. * @returns A new Promise. */ race<T>(values: (T | PromiseLike<T>)[]): Promise<T> /** * Creates a new rejected promise for the provided reason. * @param reason The reason the promise was rejected. * @returns A new rejected Promise. */ reject<T = never>(reason?: any): Promise<T> /** * Creates a new resolved promise for the provided value. * @param value A promise. * @returns A promise whose internal state matches the provided promise. */ resolve<T>(value: T | PromiseLike<T>): Promise<T> /** * Creates a new resolved promise . * @returns A resolved promise. */ resolve(): Promise<void> } declare var Promise: PromiseConstructor /// --- FETCH --- type RequestRedirect = 'follow' | 'error' | 'manual' type ResponseType = 'basic' | 'cors' | 'default' | 'error' | 'opaque' | 'opaqueredirect' interface RequestInit { // whatwg/fetch standard options body?: string headers?: { [index: string]: string } method?: string redirect?: RequestRedirect } interface ReadOnlyHeaders { get(name: string): string | null has(name: string): boolean forEach(callbackfn: (value: string, key: string, parent: ReadOnlyHeaders) => void, thisArg?: any): void } interface Response { readonly headers: ReadOnlyHeaders readonly ok: boolean readonly redirected: boolean readonly status: number readonly statusText: string readonly type: ResponseType readonly url: string json(): Promise<any> text(): Promise<string> } declare function fetch(url: string, init?: RequestInit): Promise<Response> /// --- WebSocket --- interface Event { readonly type: string } interface MessageEvent extends Event { /** * Returns the data of the message. */ readonly data: any } interface CloseEvent extends Event { readonly code: number readonly reason: string readonly wasClean: boolean } interface WebSocket { readonly bufferedAmount: number readonly extensions: string onclose: ((this: WebSocket, ev: CloseEvent) => any) | null onerror: ((this: WebSocket, ev: Event) => any) | null onmessage: ((this: WebSocket, ev: MessageEvent) => any) | null onopen: ((this: WebSocket, ev: Event) => any) | null readonly protocol: string readonly readyState: number readonly url: string close(code?: number, reason?: string): void send(data: string): void readonly CLOSED: number readonly CLOSING: number readonly CONNECTING: number readonly OPEN: number } declare var WebSocket: { prototype: WebSocket new (url: string, protocols?: string | string[]): WebSocket readonly CLOSED: number readonly CLOSING: number readonly CONNECTING: number readonly OPEN: number }
the_stack
import {Solver, Outcome, Derivative} from '../src/odex' import assert = require('power-assert') describe('Odex', () => { let NewSolver = (n: number) => { let s = new Solver(n) s.maxSteps = 200 return s } let airy: Derivative = (x: number, y: number[]) => [y[1], x * y[0]] let vanDerPol: (e: number) => Derivative = e => (x, y) => [ y[1], ((1 - Math.pow(y[0], 2)) * y[1] - y[0]) / e ] let bessel: (a: number) => Derivative = (a) => (x, y) => { let xsq = x * x return [y[1], ((a * a - xsq) * y[0] - x * y[1]) / xsq] } let lotkaVolterra: (a: number, b: number, c: number, d: number) => Derivative = (a, b, c, d) => (x, y) => [ a * y[0] - b * y[0] * y[1], c * y[0] * y[1] - d * y[1] ] let trig: Derivative = (x, y) => [y[1], -y[0]] describe('stepSizeSequence', () => { it('is correct for Type 1', () => assert.deepEqual([0, 2, 4, 6, 8, 10, 12, 14, 16], Solver.stepSizeSequence(1, 8))) it('is correct for Type 2', () => assert.deepEqual([0, 2, 4, 8, 12, 16, 20, 24, 28], Solver.stepSizeSequence(2, 8))) it('is correct for Type 3', () => assert.deepEqual([0, 2, 4, 6, 8, 12, 16, 24, 32], Solver.stepSizeSequence(3, 8))) it('is correct for Type 4', () => assert.deepEqual([0, 2, 6, 10, 14, 18, 22, 26, 30], Solver.stepSizeSequence(4, 8))) it('is correct for Type 5', () => assert.deepEqual([0, 4, 8, 12, 16, 20, 24, 28, 32], Solver.stepSizeSequence(5, 8))) it('throws for a bad Type', () => assert.throws(() => Solver.stepSizeSequence(6, 8), Error)) it('throws for a bad Type', () => assert.throws(() => Solver.stepSizeSequence(0, 8), Error)) }) describe('Van der Pol equation w/o dense output', () => { const s = NewSolver(2) const tol = 1e-5 s.absoluteTolerance = s.relativeTolerance = tol s.initialStepSize = 0.01 s.maxSteps = 50 const y0 = [2, 0] const {y: [y1, y1p], outcome: outcome} = s.solve(vanDerPol(0.1), 0, y0, 2) it('converged', () => assert.equal(outcome, Outcome.Converged)) it('worked for y', () => assert(Math.abs(y1 + 1.58184) < tol * 10)) it(`worked for y'`, () => assert(Math.abs(y1p - 0.978449) < tol * 10)) }) describe(`y' = y, (exp)`, () => { let s = NewSolver(1) const tol = 1e-8 s.absoluteTolerance = s.relativeTolerance = tol let y0 = [1] let {y: [y1], outcome: outcome} = s.solve((x, y) => y, 0, y0, 1) it('converged', () => assert.equal(outcome, Outcome.Converged)) it('worked for y', () => assert(Math.abs(y1 - Math.exp(1)) < tol * 10)) }) describe('y" = -y (sine/cosine)', () => { let s = NewSolver(2) let y0 = [0, 1] let {y: [y1, y1p], outcome: outcome} = s.solve(trig, 0, y0, 1) it('converged', () => assert.equal(outcome, Outcome.Converged)) it('worked for y', () => assert(Math.abs(y1 - Math.sin(1)) < 1e-5)) it(`worked for y'`, () => assert(Math.abs(y1p - Math.cos(1)) < 1e-5)) let c = s.solve(trig, 0, y0, 10) it('converged: long range', () => assert.equal(c.outcome, Outcome.Converged)) it('worked for y', () => assert(Math.abs(c.y[0] - Math.sin(10)) < 1e-4)) it(`worked for y'`, () => assert(Math.abs(c.y[1] - Math.cos(10)) < 1e-4)) }) describe('Airy equation y" = xy', () => { let s = NewSolver(2) s.initialStepSize = 1e-4 let y0 = [0.3550280539, -0.2588194038] let a = s.solve(airy, 0, y0, 1) it('worked', () => assert(a.outcome === Outcome.Converged)) it('1st kind: works for y', () => assert(Math.abs(a.y[0] - 0.1352924163) < 1e-5)) it(`1st kind: works for y'`, () => assert(Math.abs(a.y[1] + 0.1591474413) < 1e-5)) // Airy equation of the second kind (or "Bairy equation"); this has different // initial conditions y0 = [0.6149266274, 0.4482883574] let b = s.solve(airy, 0, y0, 1) it('worked', () => assert(b.outcome === Outcome.Converged)) it('2nd kind: works for y', () => assert(Math.abs(b.y[0] - 1.207423595) < 1e-5)) it(`2nd kind: works for y'`, () => assert.ok(Math.abs(b.y[1] - 0.9324359334) < 1e-5)) }) describe('Bessel equation x^2 y" + x y\' + (x^2-a^2) y = 0', () => { let s = NewSolver(2) let y1 = [0.4400505857, 0.3251471008] let y2 = s.solve(bessel(1), 1, y1, 2) it('converged', () => assert(y2.outcome === Outcome.Converged)) it('y', () => assert(Math.abs(y2.y[0] - 0.5767248078) < 1e-5)) it(`y"`, () => assert(Math.abs(y2.y[1] + 0.06447162474) < 1e-5)) s.initialStepSize = 1e-6 let y3 = s.solve(bessel(1), 1, y1, 2) it('converged', () => assert(y3.outcome === Outcome.Converged)) it('y (small step size)', () => assert(Math.abs(y3.y[0] - 0.5767248078) < 1e-6)) it(`y' (small step size)`, () => assert(Math.abs(y3.y[1] + 0.06447162474) < 1e-6)) s.absoluteTolerance = s.relativeTolerance = 1e-12 let y4 = s.solve(bessel(1), 1, y1, 2) it('converged', () => assert(y4.outcome === Outcome.Converged)) it('y (low tolerance)', () => assert(Math.abs(y4.y[0] - 0.5767248078) < 1e-10)) it('y\' (low tolerance)', () => assert(Math.abs(y4.y[1] + 0.06447162474) < 1e-10)) }) describe('max step control', () => { let s = NewSolver(2) s.maxSteps = 2 let o = s.solve(vanDerPol(0.1), 0, [2, 0], 10) it('didn\' t converge', () => assert(o.outcome === Outcome.MaxStepsExceeded)) it('tried', () => assert(o.nStep === s.maxSteps)) }) describe('exits early when asked to', () => { let s = NewSolver(1) let evalLimit = 3 let evalCount = 0 let o = s.solve((x, y) => [y[0]], 0, [1], 1, () => { if (++evalCount === evalLimit) return false }) it('noticed the early exit', () => assert(o.outcome === Outcome.EarlyReturn)) it('took the right number of steps', () => assert(o.nStep === evalLimit - 1)) let t = NewSolver(1) let evalCount2 = 0 t.denseOutput = true let o2 = t.solve((x, y) => y, 0, [1], 1, t.grid(0.01, () => { if (++evalCount2 === evalLimit) return false })) it('noticed the early exit using grid', () => assert(o2.outcome === Outcome.EarlyReturn)) it('took fewer than expected steps using grid', () => assert(o2.nStep < 10)) }) describe('cosine (observer)', () => { let s = NewSolver(2) let o = s.solve(trig, 0, [1, 0], 2 * Math.PI, (n, xOld, x, y) => { it('is accurate at grid point ' + n, () => assert(Math.abs(y[0] - Math.cos(x)) < 1e-4)) // console.log('observed cos', Math.abs(y[0]-Math.cos(x))) }) it('converged', () => assert(o.outcome === Outcome.Converged)) }) describe('sine (observer)', () => { let s = NewSolver(2) let o = s.solve(trig, 0, [0, 1], 2 * Math.PI, (n, xOld, x, y) => { it('is accurate at grid point ' + n, () => assert(Math.abs(y[0] - Math.sin(x)) < 1e-5)) }) it('converged', () => assert(o.outcome === Outcome.Converged)) }) describe('cosine (dense output)', () => { let s = NewSolver(2) s.denseOutput = true let o = s.solve(trig, 0, [1, 0], 2 * Math.PI, () => { // console.log('dense cos', Math.abs(y[0]-Math.cos(x))) }) it('converged', () => assert(o.outcome === Outcome.Converged)) }) describe('cosine (dense output, no error estimation)', () => { let s = NewSolver(2) s.denseOutput = true s.denseOutputErrorEstimator = false let o = s.solve(trig, 0, [1, 0], 2 * Math.PI, () => { // console.log('dense cos n.e.', Math.abs(y[0]-Math.cos(x))) }) it('converged', () => assert(o.outcome === Outcome.Converged)) it('evaluated f the correct number of times', () => assert(o.nEval === 183)) it('took the correct number of steps', () => assert(o.nStep === 8)) it('had no rejection steps', () => assert(o.nReject === 0)) }) describe('cosine (dense output, grid evaluation)', () => { let s = NewSolver(2) s.denseOutput = true const grid = 0.1 let current = 0.0 let o = s.solve(trig, 0, [1, 0], Math.PI / 2, (n, xOld, x, y, f) => { while (current >= xOld && current < x) { let k = current let v = f(0, current) let vp = f(1, current) // console.log('eval', xOld, x, current, v, Math.abs(v-Math.cos(current))) it('is accurate at interpolated grid point', () => assert(Math.abs(v - Math.cos(k)) < 1e-5)) it('derivative is accurate at interpolated grid point', () => assert(Math.abs(vp + Math.sin(k)) < 1e-5)) current += grid } }) it('converged', () => assert(o.outcome === Outcome.Converged)) it('evaluated f the correct number of times', () => assert(o.nEval === 101)) it('took the correct number of steps', () => assert(o.nStep === 7)) it('had no rejection steps', () => assert(o.nReject === 0)) }) describe('cosine (observer, long range)', () => { let s = NewSolver(2) s.denseOutput = false let o = s.solve(trig, 0, [1, 0], 16 * Math.PI, (n, xOld, x, y) => { it('is accurate at grid point ' + n, () => assert(Math.abs(y[0] - Math.cos(x)) < 2e-4)) // console.log('observed cos l.r.', n, x, y[0], Math.abs(y[0]-Math.cos(x))) }) it('converged', () => assert(o.outcome === Outcome.Converged)) it('evaluated f the correct number of times', () => assert(o.nEval === 920)) it('took the correct number of steps', () => assert(o.nStep === 34)) it('had no rejection steps', () => assert(o.nReject === 0)) }) describe('bogus parameters', () => { it('throws if maxSteps is <= 0', () => { let s = NewSolver(2) s.maxSteps = -2 assert.throws(() => { s.solve(trig, 0, [1, 0], 1) }, Error) }) it('throws if maxExtrapolationColumns is <= 2', () => { let s = NewSolver(2) s.maxExtrapolationColumns = 1 assert.throws(() => { s.solve(trig, 0, [1, 0], 1) }, Error) }) it('throws for dense-output-incompatible step sequence', () => { let s = NewSolver(2) s.stepSizeSequence = 1 s.denseOutput = true assert.throws(() => { s.solve(trig, 0, [1, 0], 1) }, Error) }) it('throws when dense output is requested but no observer function is given', () => { let s = NewSolver(2) s.denseOutput = true assert.throws(() => { s.solve(trig, 0, [1, 0], 1) }, Error) }) it('throws for bad interpolation formula degree', () => { let s = NewSolver(2) s.interpolationFormulaDegree = 99 assert.throws(() => { s.solve(trig, 0, [1, 0], 1) }, Error) }) it('throws for bad uRound', () => { let s = NewSolver(1) s.uRound = Math.PI assert.throws(() => { s.solve(trig, 0, [1, 0], 1) }, Error) }) it('throws for bad dense component', () => { let s = NewSolver(2) s.denseOutput = true s.denseComponents = [5] assert.throws(() => { s.solve(trig, 0, [1, 0], 1, () => undefined) }, Error) }) }) describe('requesting specific dense output component', () => { let s = NewSolver(2) s.denseComponents = [1] // we only want y', e.g., -sin(x), densely output s.denseOutput = true let component = (k: number) => { let diff = 1e10 s.solve(trig, 0, [1, 0], 1, (n, xOld, x, y, f) => { if (x > 0) { let xh = (x - xOld) / 2 diff = Math.abs(f(k, xh) + Math.sin(xh)) return false } }) return diff } it('works for the selected component', () => assert(component(1) < 1e-5)) it('throws for unselected component', () => assert.throws(() => component(0), Error)) }) describe('lotka-volterra equations', () => { // Validation data from Mathematica: // LV[a_, b_, c_, d_] := // NDSolve[{y1'[x] == a y1[x] - b y1[x] y2[x], // y2'[x] == c y1[x] y2[x] - d y2[x], // y1[0] == 1, // y2[0] == 1}, // {y1, y2}, {x, 0, 25}] // Table[{y1[t], y2[t]} /. LV[2/3, 4/3, 1, 1], {t, 0, 15}] let data = [ [1., 1.], [0.574285, 0.777439], [0.489477, 0.47785], [0.576685, 0.296081], [0.80643, 0.2148], [1.19248, 0.211939], [1.65428, 0.325282], [1.69637, 0.684714], [1.01791, 0.999762], [0.580062, 0.786245], [0.489149, 0.484395], [0.572558, 0.299455], [0.798319, 0.215934], [1.18032, 0.21089], [1.64389, 0.319706], [1.70715, 0.672033] ] let s = NewSolver(2) s.denseOutput = true let i = 0 s.solve(lotkaVolterra(2 / 3, 4 / 3, 1, 1), 0, [1, 1], 15, s.grid(1, (x, y) => { let diff = Math.abs(y[0] - data[i][0]) it('works for y1 at grid point ' + i, () => assert(diff < 1e-4)) ++i })) }) describe(`Topologist's sine function`, () => { // Here we supply a differential equation designed to test the limits. // Let y = sin(1/x). Then y' = -cos(1/x) / x^2. const left = 0.005 let s = NewSolver(1) s.denseOutput = true s.absoluteTolerance = s.relativeTolerance = [1e-6] let o = s.solve((x, y) => [-Math.cos(1 / x) / (x * x)], left, [Math.sin(1 / left)], 2, s.grid(0.1, (x, y) => { let diff = Math.abs(y[0] - Math.sin(1 / x)) it('works for y at grid point ' + x, () => assert(diff < 1e-4)) })) it('rejected some steps', () => assert(o.nReject > 0)) }) describe('Configuration debugging', () => { it ('throws when you use grid without denseOutput', () => { let s = NewSolver(1) assert.throws(() => { s.solve((x, y) => y, 0, [1], 1, s.grid(0.1, (x, y) => { console.log(x, y) })) }, /denseOutput/, 'expected recommendation to use denseOutput') }) }) })
the_stack
import { Position, Range, TextDocument } from "vscode"; import { findFirst } from "../../utils/arrays"; import { consumerModel, Model, producerModel } from "../model"; export enum NodeKind { document, producerBlock, producerValue, consumerBlock, consumerGroupId, property, propertyKey, propertyAssigner, propertyValue, mustacheExpression, calleeFunction, parameter } export interface Node { start: Position; end: Position; range(): Range; findNodeBefore(offset: Position): Node; findNodeAt(offset: Position): Node; lastChild: Node | undefined; parent: Node | undefined; kind: NodeKind; } class BaseNode implements Node { public parent: Node | undefined; constructor(public readonly start: Position, public readonly end: Position, public readonly kind: NodeKind) { } public range(): Range { const start = this.start; const end = this.end; return new Range(start, end); } public findNodeBefore(offset: Position): Node { return this; } public findNodeAt(offset: Position): Node { return this; } public get lastChild(): Node | undefined { return undefined; } } class ChildrenNode<T extends Node> extends BaseNode { protected readonly children: Array<T> = []; public addChild(node: T) { node.parent = this; this.children.push(node); } public findNodeBefore(offset: Position): Node { const idx = findFirst(this.children, c => offset.isBeforeOrEqual(c.start)) - 1; if (idx >= 0) { const child = this.children[idx]; if (offset.isAfter(child.start)) { if (offset.isBefore(child.end)) { return child.findNodeBefore(offset); } const lastChild = child.lastChild; if (lastChild && lastChild.end.isEqual(child.end)) { return child.findNodeBefore(offset); } return child; } } return this; } public findNodeAt(offset: Position): Node { const idx = findFirst(this.children, c => offset.isBeforeOrEqual(c.start)) - 1; if (idx >= 0) { const child = this.children[idx]; if (offset.isAfter(child.start) && offset.isBeforeOrEqual(child.end)) { return child.findNodeAt(offset); } } return this; } public get lastChild(): Node | undefined { return this.children.length ? this.children[this.children.length - 1] : void 0; }; } export class KafkaFileDocument extends ChildrenNode<Block> { constructor(start: Position, end: Position) { super(start, end, NodeKind.document); } public get blocks(): Array<Block> { return this.children; } } export class Chunk extends BaseNode { constructor(public readonly content: string, start: Position, end: Position, kind: NodeKind) { super(start, end, kind); } } export class Property extends BaseNode { constructor(public readonly key?: Chunk, public readonly assignerCharacter?: number, public readonly value?: Chunk) { super(key?.start || value?.start || new Position(0, 0,), value?.end || key?.end || new Position(0, 0,), NodeKind.property); if (key) { key.parent = this; } if (value) { value.parent = this; } } public get propertyName(): string | undefined { return this.key?.content.trim(); } public get propertyValue(): string | undefined { return this.value?.content.trim(); } public get propertyKeyRange(): Range { const start = this.start; const end = this.assignerCharacter ? new Position(this.start.line, this.assignerCharacter) : this.end; return new Range(start, end); } public get propertyValueRange(): Range | undefined { if (!this.assignerCharacter) { return; } const start = new Position(this.start.line, this.assignerCharacter + 1); const end = this.end; return new Range(start, end); } public get propertyTrimmedValueRange(): Range | undefined { if (!this.assignerCharacter) { return; } const value = this.value?.content; if (!value) { return; } let startChar = 0; for (startChar = 0; startChar < value.length; startChar++) { if (value.charAt(startChar) !== ' ') { break; } } let endChar = value.length; for (endChar = value.length - 1; endChar >= 0; endChar--) { if (value.charAt(endChar) !== ' ') { endChar++; break; } } const start = new Position(this.start.line, startChar + this.assignerCharacter + 1); const end = new Position(this.end.line, endChar + this.assignerCharacter + 1); return new Range(start, end); } isBeforeAssigner(position: Position): boolean { if (this.assignerCharacter) { return position.character <= this.assignerCharacter; } return true; } findNodeAt(position: Position): Node { if (this.isBeforeAssigner(position)) { return this.key?.findNodeAt(position) || this; } return this.value?.findNodeAt(position) || this; } } export abstract class Block extends ChildrenNode<Property | Chunk> { constructor(start: Position, end: Position, public readonly type: BlockType, public readonly model: Model) { super(start, end, type === BlockType.consumer ? NodeKind.consumerBlock : NodeKind.producerBlock); } public get properties(): Array<Property> { return <Array<Property>>( this.children .filter(node => node.kind === NodeKind.property)); } getPropertyValue(name: string): string | undefined { const property = this.getProperty(name); return property?.propertyValue; } getProperty(name: string): Property | undefined { return this.properties.find(p => p.propertyName === name); } } export class ProducerBlock extends Block { public value: DynamicChunk | undefined; constructor(start: Position, end: Position) { super(start, end, BlockType.producer, producerModel); } } export class ConsumerBlock extends Block { public consumerGroupId: Chunk | undefined; constructor(start: Position, end: Position) { super(start, end, BlockType.consumer, consumerModel); } } export class DynamicChunk extends ChildrenNode<MustacheExpression> { constructor(public readonly content: string, start: Position, end: Position, kind: NodeKind) { super(start, end, kind); parseMustacheExpressions(this); } public get expressions(): Array<MustacheExpression> { return <Array<MustacheExpression>>( this.children .filter(node => node.kind === NodeKind.mustacheExpression)); } } export class Parameter extends Chunk { name?: string; public get value() : string { return this.content?.trim(); } } export class CalleeFunction extends ChildrenNode<Parameter> { startParametersCharacter?: number; endParametersCharacter?: number; constructor(public readonly content: string, start: Position, end: Position) { super(start, end, NodeKind.calleeFunction); parseParameters(this); } public get functionName() : string { return this.startParametersCharacter ? this.content.substring(0, this.startParametersCharacter - this.start.character).trim() : this.content.trim(); } public get parameters(): Array<Parameter> { return this.children; } } /** * Mustache expression AST (ex : {{random.words}}) */ export class MustacheExpression extends Chunk { // Unexpected start edges '{{' inside the expression (ex : {{random.w{{ords}}) public readonly unexpectedEdges: Array<ExpressionEdge> = []; constructor(content: string, start: Position, public readonly opened: boolean, end: Position, public readonly closed: boolean) { super(content, start, end, NodeKind.mustacheExpression); } /** * Returns the range of the enclosed expression * * For example for {{random.words}}, it will return ranges of random.words. */ public get enclosedExpressionRange(): Range { const start = new Position(this.start.line, this.start.character + ((this.opened) ? 2 : 0)); const end = new Position(this.end.line, this.end.character - ((this.closed) ? 2 : 0)); return new Range(start, end); } /** * Return true if the given position is after an unexpected edge (ex : {{random.w{{| and false otherwise. * * @param position the position to check. * * @returns true if the given position is after an unexpected edge (ex : {{random.w{{| and false otherwise. */ public isAfterAnUnexpectedEdge(position: Position): boolean { if (this.unexpectedEdges.length < 1) { return false; } const pos = this.unexpectedEdges[0]; return position.isAfterOrEqual(pos.position); } } export enum BlockType { producer = 'PRODUCER', consumer = 'CONSUMER' } export function parseKafkaFile(document: TextDocument): KafkaFileDocument { const lineCount = document.lineCount; const start = new Position(0, 0); const end = document.lineAt(lineCount - 1).range.end; const kafkaFileDocument = new KafkaFileDocument(start, end); // Create block PRODUCER / CONSUMER block codeLens let blockStartLine = 0; let blockEndLine = 0; let currentBlockType = undefined; for (let currentLine = 0; currentLine < document.lineCount; currentLine++) { const lineText = document.lineAt(currentLine).text; if (currentBlockType === undefined) { // Search start of PRODUCER / CONSUMER block const blockType = getBlockType(lineText); if (blockType !== undefined) { blockStartLine = currentLine; currentBlockType = blockType; continue; } } else { // A PRODUCER / CONSUMER block is parsing, check if it's the end of the block if (isEndBlock(lineText, currentBlockType)) { blockEndLine = currentLine - 1; kafkaFileDocument.addChild(createBlock(blockStartLine, blockEndLine, document, currentBlockType)); if (currentBlockType === BlockType.consumer) { currentBlockType = getBlockType(lineText); if (currentBlockType !== undefined) { blockStartLine = currentLine; } } else { currentBlockType = undefined; } continue; } } } if (currentBlockType !== undefined) { kafkaFileDocument.addChild(createBlock(blockStartLine, document.lineCount - 1, document, currentBlockType)); } return kafkaFileDocument; } function getBlockType(lineText: string): BlockType | undefined { if (lineText.startsWith(BlockType.producer.toString())) { return BlockType.producer; } else if (lineText.startsWith(BlockType.consumer.toString())) { return BlockType.consumer; } return undefined; } function isEndBlock(lineText: string, blockType: BlockType): boolean { if (blockType === BlockType.consumer) { return isSeparator(lineText) || getBlockType(lineText) !== undefined; } return isSeparator(lineText); } function isSeparator(lineText: string): boolean { return lineText.startsWith("###"); } function createBlock(blockStartLine: number, blockEndLine: number, document: TextDocument, blockType: BlockType): Block { const start = new Position(blockStartLine, 0); const end = document.lineAt(blockEndLine).range.end; if (blockType === BlockType.consumer) { const block = new ConsumerBlock(start, end); parseConsumerBlock(block, document); return block; } const block = new ProducerBlock(start, end); parseProducerBlock(block, document); return block; } function parseProducerBlock(block: ProducerBlock, document: TextDocument) { for (let currentLine = block.start.line + 1; currentLine <= block.end.line; currentLine++) { const lineText = document.lineAt(currentLine).text; if (isIgnoreLine(lineText)) { // The line is a comment or a blank line continue; } if (isPropertyLine(lineText, block.model)) { // Known properties block.addChild(createProperty(lineText, currentLine, block)); continue; } // The rest of the content is the value const startValue = new Position(currentLine, 0); const endValue = new Position(block.end.line + 1, 0); const contentValue = document.getText(new Range(startValue, endValue)).trim(); block.value = new DynamicChunk(contentValue, startValue, endValue, NodeKind.producerValue); block.addChild(block.value); break; } } function isPropertyLine(lineText: string, model: Model): boolean { const index = lineText.indexOf(':'); if (index === -1) { return false; } const propertyName = lineText.substring(0, index); return model.hasDefinition(propertyName); } function isIgnoreLine(lineText: string): boolean { return lineText.startsWith("--") || lineText.trim().length === 0; } function parseConsumerBlock(block: ConsumerBlock, document: TextDocument) { for (let currentLine = block.start.line; currentLine <= block.end.line; currentLine++) { const lineText = document.lineAt(currentLine).text; if (currentLine === block.start.line) { const start = "CONSUMER".length; const end = lineText.length; const content = lineText.substr(start).trim(); const consumerGroupId = new Chunk(content, new Position(currentLine, start), new Position(currentLine, end), NodeKind.consumerGroupId); consumerGroupId.parent = block; block.consumerGroupId = consumerGroupId; continue; } if (isIgnoreLine(lineText)) { // The line is a comment or a blank line continue; } // Add the line content as property (ex : topic: MY_TOPIC) block.addChild(createProperty(lineText, currentLine, block)); } } function createProperty(lineText: string, lineNumber: number, parent: Block): Property { let propertyKey: Chunk | undefined = undefined; let propertyValue: Chunk | undefined = undefined; let separatorCharacter = undefined; let withinValue = false; let start = -1; for (let i = 0; i < lineText.length; i++) { const ch = lineText[i]; if (ch === ' ' || ch === '\t') { if (start === -1) { continue; } } else if (ch === ':') { if (!withinValue) { if (start !== -1) { const end = i; const content = lineText.substr(start, end); propertyKey = new Chunk(content, new Position(lineNumber, start), new Position(lineNumber, end), NodeKind.propertyKey); } separatorCharacter = i; withinValue = true; start = i + 1; } } else { if (start === -1) { start = i; } } } if (start !== -1) { const end = lineText.length; const content = lineText.substr(start, end); if (withinValue) { const propertyName = propertyKey?.content.trim(); switch (propertyName) { case "key": propertyValue = new DynamicChunk(content, new Position(lineNumber, start), new Position(lineNumber, end), NodeKind.propertyValue); break; case "key-format": case "value-format": propertyValue = new CalleeFunction(content, new Position(lineNumber, start), new Position(lineNumber, end)); break; default: propertyValue = new Chunk(content, new Position(lineNumber, start), new Position(lineNumber, end), NodeKind.propertyValue); break; } } else { propertyKey = new Chunk(content, new Position(lineNumber, start), new Position(lineNumber, end), NodeKind.propertyKey); } } return new Property(propertyKey, separatorCharacter, propertyValue); } /** * Position and offset of mustache expression edge : * - start '{{' * - end '}}' . */ export class ExpressionEdge { constructor(readonly position: Position, readonly offset: number, readonly open: boolean) { } } function parseParameters(parent: CalleeFunction) { const content = parent.content; let startLine = parent.start.line; let startColumn = parent.start.character; let currentLine = startLine; let currentColumn = startColumn; let previousChar: string | undefined; let startParameter: number | undefined; function addParameterIfNeeded() { if (startParameter) { const value = content.substring(startParameter - startColumn, currentColumn - startColumn); const start = new Position(currentLine, startParameter); const end = new Position(currentLine, currentColumn); parent.addChild(new Parameter(value, start, end, NodeKind.parameter)); } } for (let currentOffset = 0; currentOffset < content.length; currentOffset++) { const currentChar = content[currentOffset]; switch (currentChar) { case '\r': // compute line, column position currentLine++; currentColumn = 0; break; case '\n': { if (previousChar !== '\r') { // compute line, column position currentLine++; currentColumn = 0; } break; } case '(': { if (!parent.startParametersCharacter) { parent.startParametersCharacter = currentColumn; startParameter = currentColumn + 1; } break; } case ')': { parent.endParametersCharacter = currentColumn; addParameterIfNeeded(); startParameter = undefined; break; } case ',': { addParameterIfNeeded(); startParameter = currentColumn + 1; break; } } if (currentChar !== '\r' && currentChar !== '\n') { currentColumn++; } } addParameterIfNeeded(); } function parseMustacheExpressions(parent: DynamicChunk) { const content = parent.content; let startLine = parent.start.line; let startColumn = parent.start.character; let currentLine = startLine; let currentColumn = startColumn; let previousChar: string | undefined; // 1. Collect start/end expression edges position and offset const edges: Array<ExpressionEdge> = []; let currentOffset = 0; for (currentOffset = 0; currentOffset < content.length; currentOffset++) { const currentChar = content[currentOffset]; switch (currentChar) { case '\r': // compute line, column position currentLine++; currentColumn = 0; break; case '\n': { if (previousChar !== '\r') { // compute line, column position currentLine++; currentColumn = 0; } break; } case '{': { if (previousChar === '{') { // Start mustache expression edges.push(new ExpressionEdge(new Position(currentLine, currentColumn - 1), currentOffset - 1, true)); } break; } case '}': { if (previousChar === '}') { // End mustache expression edges.push(new ExpressionEdge(new Position(currentLine, currentColumn + 1), currentOffset + 1, false)); } break; } } if (currentChar !== '\r' && currentChar !== '\n') { currentColumn++; } previousChar = currentChar; } // 2. create mustache expression AST by visiting collected edges let previousEdge = new ExpressionEdge(new Position(startLine, startColumn), 0, true); const endOfValueEdge = new ExpressionEdge(new Position(currentLine, currentColumn), currentOffset, false); for (let i = 0; i < edges.length; i++) { const currentEdge = edges[i]; if (currentEdge.open) { // '{{' edge encountered // Try to get the next '}}' edge let matchingClosedEdge: ExpressionEdge | undefined; const j = getBestIndexForClosingExpression(edges, i + 1); if (j < edges.length) { matchingClosedEdge = edges[j]; } const openedEdge = currentEdge; let closedEdge = endOfValueEdge; let closed = false; if (matchingClosedEdge) { // '}}' has been found closed = true; closedEdge = matchingClosedEdge; } const expressionContent = content.substring(openedEdge.offset + 2, closedEdge.offset - (closed ? 2 : 0)); const expression = new MustacheExpression(expressionContent, openedEdge.position, true, closedEdge.position, closed); // Update unexepcted edges for (let index = i + 1; index < j; index++) { expression.unexpectedEdges.push(edges[index]); } parent.addChild(expression); i = j; previousEdge = closedEdge; } else { // '}}' edge encountered const closedEdge = currentEdge; const openedEdge = previousEdge; const expressionContent = content.substring(openedEdge.offset, closedEdge.offset - 2); const expression = new MustacheExpression(expressionContent, openedEdge.position, false, closedEdge.position, true); parent.addChild(expression); } } } function getBestIndexForClosingExpression(edges: ExpressionEdge[], start: number): number { for (let i = start; i < edges.length; i++) { const currentPos = edges[i]; if (!currentPos.open) { return i; } } return edges.length; }
the_stack
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { DebugElement, Type } from '@angular/core'; import { TestTextArea } from './test-textarea'; import { TestElement } from './test-element'; import { TestInput } from './test-input'; import { TestSelect } from './test-select'; import { TestButton } from './test-button'; import { TestElementQuerier } from './test-element-querier'; import { TestHtmlElement } from './test-html-element'; /** * The main entry point of the API. It wraps an Angular ComponentFixture<T>, and gives access to its * most used properties and methods. It also allows getting elements wrapped in TestElement (and its subclasses) * @param <C> the type of the component to test */ export class ComponentTester<C> { /** * The test element of the component */ readonly testElement: TestElement<HTMLElement>; /** * The component fixture of the component */ readonly fixture: ComponentFixture<C>; /** * Creates a component fixture of the given type with the TestBed and wraps it into a ComponentTester */ static create<C>(componentType: Type<C>): ComponentTester<C> { const fixture = TestBed.createComponent(componentType); return new ComponentTester(fixture); } /** * Creates a ComponentFixture for the given component type using the TestBed, and creates a ComponentTester * wrapping (and delegating) to this fixture. If a fixture is passed, then delegates to this fixture directly. * * Note that no `detectChanges()` call is made by this constructor. It's up to the subclass constructor, * or to the user of the created ComponentTester, to call `detectChanges()` at least once to trigger change * detection. This is necessary because some component templates can only be evaluated once inputs * have been set on the component instance. * * @param arg the type of the component to wrap, or a component fixture to wrap */ constructor(arg: Type<C> | ComponentFixture<C>) { this.fixture = arg instanceof ComponentFixture ? arg : TestBed.createComponent(arg); this.testElement = TestElementQuerier.wrap(this.debugElement, this) as TestElement<HTMLElement>; } /** * The native DOM host element of the component */ get nativeElement(): HTMLElement { return this.fixture.nativeElement; } /** * Gets the instance of the tested component from the wrapped fixture */ get componentInstance(): C { return this.fixture.componentInstance; } /** * Gets the debug element from the wrapped fixture */ get debugElement(): DebugElement { return this.fixture.debugElement; } /** * Gets the first element matching the given CSS selector and wraps it into a TestElement. The actual type * of the returned value is the TestElement subclass matching the type of the found element. So, if the * matched element is an input for example, the method will return a TestInput. * <p>Usage:</p> * <code> * const testElement: TestHtmlElement&lt;HTMLDivElement> | null = tester.element('div'); * </code> * @param selector a CSS selector * @returns the wrapped element, or null if no element matches the selector. */ element<K extends keyof HTMLElementTagNameMap>(selector: K): TestHtmlElement<HTMLElementTagNameMap[K]> | null; /** * Gets the first element matching the given CSS selector and wraps it into a TestElement. The actual type * of the returned value is the TestElement subclass matching the type of the found element. So, if the * matched element is an input for example, the method will return a TestInput. * <p>Usage:</p> * <code> * const testElement: TestElement&lt;SVGLineElement> | null = tester.element('line'); * </code> * @param selector a CSS selector * @returns the wrapped element, or null if no element matches the selector. */ element<K extends keyof SVGElementTagNameMap>(selector: K): TestElement<SVGElementTagNameMap[K]> | null; /** * Gets the first element matching the given CSS selector and wraps it into a TestElement. The actual type * of the returned value is the TestElement subclass matching the type of the found element. So, if the * matched element is an input for example, the method will return a TestInput. * <p>Usage:</p> * <code> * const testElement: TestElement | null = tester.element('.selector'); * </code> * @param selector a CSS selector * @returns the wrapped element, or null if no element matches the selector. */ element(selector: string): TestElement | null; /** * Gets the first element matching the given CSS selector and wraps it into a TestElement. The actual type * of the returned value is the TestElement subclass matching the type of the found element. So, if the * matched element is an input for example, the method will return a TestInput. * <p>Usage:</p> * <code> * const testElement: TestInput | null = tester.element&lt;HTMLInputElement>('.selector'); * </code> * @param selector a CSS selector * @returns the wrapped element, or null if no element matches the selector. */ element<T extends HTMLInputElement>(selector: string): TestInput | null; /** * Gets the first element matching the given CSS selector and wraps it into a TestElement. The actual type * of the returned value is the TestElement subclass matching the type of the found element. So, if the * matched element is an input for example, the method will return a TestInput. * <p>Usage:</p> * <code> * const testElement: TestTextArea | null = tester.element&lt;HTMLTextAreaElement>('.selector'); * </code> * @param selector a CSS selector * @returns the wrapped element, or null if no element matches the selector. */ element<T extends HTMLTextAreaElement>(selector: string): TestTextArea | null; /** * Gets the first element matching the given CSS selector and wraps it into a TestElement. The actual type * of the returned value is the TestElement subclass matching the type of the found element. So, if the * matched element is an input for example, the method will return a TestInput. * <p>Usage:</p> * <code> * const testElement: TestSelect | null = tester.element&lt;HTMLSelectElement>('.selector'); * </code> * @param selector a CSS selector * @returns the wrapped element, or null if no element matches the selector. */ element<T extends HTMLSelectElement>(selector: string): TestSelect | null; /** * Gets the first element matching the given CSS selector and wraps it into a TestElement. The actual type * of the returned value is the TestElement subclass matching the type of the found element. So, if the * matched element is an input for example, the method will return a TestInput. * <p>Usage:</p> * <code> * const testElement: TestButton | null = tester.element&lt;HTMLButtonElement>('.selector'); * </code> * @param selector a CSS selector * @returns the wrapped element, or null if no element matches the selector. */ element<T extends HTMLButtonElement>(selector: string): TestButton | null; /** * Gets the first element matching the given CSS selector and wraps it into a TestElement. The actual type * of the returned value is the TestElement subclass matching the type of the found element. So, if the * matched element is an input for example, the method will return a TestInput. * <p>Usage:</p> * <code> * const testElement: TestHtmlElement&lt;HTMLDivElement> | null = tester.element&lt;HTMLDivElement>('.selector'); * </code> * @param selector a CSS selector * @returns the wrapped element, or null if no element matches the selector. */ element<T extends HTMLElement>(selector: string): TestHtmlElement<T> | null; /** * Gets the first element matching the given CSS selector and wraps it into a TestElement. The actual type * of the returned value is the TestElement subclass matching the type of the found element. So, if the * matched element is an input for example, the method will return a TestInput. * <p>Usage:</p> * <code> * const testElement: TestElement&lt;SVGLineElement> | null = tester.element&lt;SVGLineElement>('.selector'); * </code> * @param selector a CSS selector * @returns the wrapped element, or null if no element matches the selector. */ element<T extends Element>(selector: string): TestElement<T> | null; element(selector: string): TestElement | null { return this.testElement.element(selector); } /** * Gets all the elements matching the given CSS selector and wraps them into a TestElement. The actual type * of the returned elements is the TestElement subclass matching the type of the found element. So, if the * matched elements are inputs for example, the method will return an array of TestInput. * <p>Usage:</p> * <code> * const testElements: Array&lt;TestHtmlElement&lt;HTMLDivElement>> = tester.elements('div'); * </code> * @param selector a CSS selector * @returns the array of matched elements, empty if no element was matched */ elements<K extends keyof HTMLElementTagNameMap>(selector: K): Array<TestHtmlElement<HTMLElementTagNameMap[K]>>; /** * Gets all the elements matching the given CSS selector and wraps them into a TestElement. The actual type * of the returned elements is the TestElement subclass matching the type of the found element. So, if the * matched elements are inputs for example, the method will return an array of TestInput. * <p>Usage:</p> * <code> * const testElements: Array&lt;TestElement&lt;SVGLineElement>> = tester.elements('line'); * </code> * @param selector a CSS selector * @returns the array of matched elements, empty if no element was matched */ elements<K extends keyof SVGElementTagNameMap>(selector: K): Array<TestElement<SVGElementTagNameMap[K]>>; /** * Gets all the elements matching the given CSS selector and wraps them into a TestElement. The actual type * of the returned elements is the TestElement subclass matching the type of the found element. So, if the * matched elements are inputs for example, the method will return an array of TestInput. * <p>Usage:</p> * <code> * const testElements: Array&lt;TestElement> = tester.elements('.selector'); * </code> * @param selector a CSS selector * @returns the array of matched elements, empty if no element was matched */ elements(selector: string): Array<TestElement>; /** * Gets all the elements matching the given CSS selector and wraps them into a TestElement. The actual type * of the returned elements is the TestElement subclass matching the type of the found element. So, if the * matched elements are inputs for example, the method will return an array of TestInput. * <p>Usage:</p> * <code> * const testElements: Array&lt;TestInput> = tester.elements&lt;HTMLInputElement>('.selector'); * </code> * @param selector a CSS selector * @returns the array of matched elements, empty if no element was matched */ elements<T extends HTMLInputElement>(selector: string): Array<TestInput>; /** * Gets all the elements matching the given CSS selector and wraps them into a TestElement. The actual type * of the returned elements is the TestElement subclass matching the type of the found element. So, if the * matched elements are inputs for example, the method will return an array of TestInput. * <p>Usage:</p> * <code> * const testElements: Array&lt;TestTextArea> = tester.elements&lt;HTMLTextAreaElement>('.selector'); * </code> * @param selector a CSS selector * @returns the array of matched elements, empty if no element was matched */ elements<T extends HTMLTextAreaElement>(selector: string): Array<TestTextArea>; /** * Gets all the elements matching the given CSS selector and wraps them into a TestElement. The actual type * of the returned elements is the TestElement subclass matching the type of the found element. So, if the * matched elements are inputs for example, the method will return an array of TestInput. * <p>Usage:</p> * <code> * const testElements: Array&lt;TestButton> = tester.elements&lt;HTMLButtonElement>('.selector'); * </code> * @param selector a CSS selector * @returns the array of matched elements, empty if no element was matched */ elements<T extends HTMLButtonElement>(selector: string): Array<TestButton>; /** * Gets all the elements matching the given CSS selector and wraps them into a TestElement. The actual type * of the returned elements is the TestElement subclass matching the type of the found element. So, if the * matched elements are inputs for example, the method will return an array of TestInput. * <p>Usage:</p> * <code> * const testElements: Array&lt;TestSelect> = tester.elements<HTMLSelectElement>('.selector'); * </code> * @param selector a CSS selector * @returns the array of matched elements, empty if no element was matched */ elements<T extends HTMLSelectElement>(selector: string): Array<TestSelect>; /** * Gets all the elements matching the given CSS selector and wraps them into a TestElement. The actual type * of the returned elements is the TestElement subclass matching the type of the found element. So, if the * matched elements are inputs for example, the method will return an array of TestInput. * <p>Usage:</p> * <code> * const testElements: Array&lt;TestHtmlElement&lt;HTMLDivElement>> = tester.elements&lt;HTMLDivElement>('.selector'); * </code> * @param selector a CSS selector * @returns the array of matched elements, empty if no element was matched */ elements<T extends HTMLElement>(selector: string): Array<TestHtmlElement<T>>; /** * Gets all the elements matching the given CSS selector and wraps them into a TestElement. The actual type * of the returned elements is the TestElement subclass matching the type of the found element. So, if the * matched elements are inputs for example, the method will return an array of TestInput. * <p>Usage:</p> * <code> * const testElements: Array&lt;TestElement&lt;SVGLineElement>> = tester.elements&lt;SVGLineElement>('.selector'); * </code> * @param selector a CSS selector * @returns the array of matched elements, empty if no element was matched */ elements<T extends Element>(selector: string): Array<TestElement<T>>; elements(selector: string): Array<TestElement> { return this.testElement.elements(selector); } /** * Gets the first input matched by the given selector. Throws an Error if the matched element isn't actually an input. * @param selector a CSS selector * @returns the wrapped input, or null if no element was matched */ input(selector: string): TestInput | null { return this.testElement.input(selector); } /** * Gets the first select matched by the given selector. Throws an Error if the matched element isn't actually a select. * @param selector a CSS selector * @returns the wrapped select, or null if no element was matched */ select(selector: string): TestSelect | null { return this.testElement.select(selector); } /** * Gets the first textarea matched by the given selector * @param selector a CSS selector * @returns the wrapped textarea, or null if no element was matched. Throws an Error if the matched element isn't actually a textarea. * @throws {Error} if the matched element isn't actually a textarea */ textarea(selector: string): TestTextArea | null { return this.testElement.textarea(selector); } /** * Gets the first button matched by the given selector. Throws an Error if the matched element isn't actually a button. * @param selector a CSS selector * @returns the wrapped button, or null if no element was matched */ button(selector: string): TestButton | null { return this.testElement.button(selector); } /** * Triggers a change detection using the wrapped fixture */ detectChanges(checkNoChanges?: boolean): void { this.fixture.detectChanges(checkNoChanges); } }
the_stack
import { Inject, Injectable, Optional } from '@angular/core'; import { Http, Headers, URLSearchParams } from '@angular/http'; import { RequestMethod, RequestOptions, RequestOptionsArgs } from '@angular/http'; import { Response, ResponseContentType } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import '../rxjs-operators'; import { Examination } from '../model/examination'; import { InlineResponse200 } from '../model/inlineResponse200'; import { InlineResponse2001 } from '../model/inlineResponse2001'; import { InlineResponse2002 } from '../model/inlineResponse2002'; import { InlineResponse2003 } from '../model/inlineResponse2003'; import { InlineResponse2005 } from '../model/inlineResponse2005'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { Configuration } from '../configuration'; /* tslint:disable:no-unused-variable member-ordering */ @Injectable() export class ExaminationService { protected basePath = 'http://localhost:3000/api'; public defaultHeaders: Headers = new Headers(); public configuration: Configuration = new Configuration(); constructor(protected http: Http, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { if (basePath) { this.basePath = basePath; } if (configuration) { this.configuration = configuration; this.basePath = basePath || configuration.basePath || this.basePath; } } /** * * Extends object by coping non-existing properties. * @param objA object to be extended * @param objB source object */ private extendObj<T1,T2>(objA: T1, objB: T2) { for(let key in objB){ if(objB.hasOwnProperty(key)){ (objA as any)[key] = (objB as any)[key]; } } return <T1&T2>objA; } /** * @param consumes string[] mime-types * @return true: consumes contains 'multipart/form-data', false: otherwise */ private canConsumeForm(consumes: string[]): boolean { const form = 'multipart/form-data'; for (let consume of consumes) { if (form === consume) { return true; } } return false; } /** * Count instances of the model matched by where from the data source. * * @param where Criteria to match model instances */ public examinationCount(where?: string, extraHttpRequestParams?: any): Observable<InlineResponse200> { return this.examinationCountWithHttpInfo(where, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Create a new instance of the model and persist it into the data source. * * @param data Model instance data */ public examinationCreate(data?: Examination, extraHttpRequestParams?: any): Observable<Examination> { return this.examinationCreateWithHttpInfo(data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Create a change stream. * * @param options */ public examinationCreateChangeStreamGetExaminationsChangeStream(options?: string, extraHttpRequestParams?: any): Observable<Blob> { return this.examinationCreateChangeStreamGetExaminationsChangeStreamWithHttpInfo(options, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.blob(); } }); } /** * Create a change stream. * * @param options */ public examinationCreateChangeStreamPostExaminationsChangeStream(options?: string, extraHttpRequestParams?: any): Observable<Blob> { return this.examinationCreateChangeStreamPostExaminationsChangeStreamWithHttpInfo(options, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.blob(); } }); } /** * Deletes all data. * */ public examinationDeleteAllExaminations(extraHttpRequestParams?: any): Observable<InlineResponse2003> { return this.examinationDeleteAllExaminationsWithHttpInfo(extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Delete a model instance by {{id}} from the data source. * * @param id Model id */ public examinationDeleteById(id: string, extraHttpRequestParams?: any): Observable<any> { return this.examinationDeleteByIdWithHttpInfo(id, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Check whether a model instance exists in the data source. * * @param id Model id */ public examinationExistsGetExaminationsidExists(id: string, extraHttpRequestParams?: any): Observable<InlineResponse2001> { return this.examinationExistsGetExaminationsidExistsWithHttpInfo(id, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Check whether a model instance exists in the data source. * * @param id Model id */ public examinationExistsHeadExaminationsid(id: string, extraHttpRequestParams?: any): Observable<InlineResponse2001> { return this.examinationExistsHeadExaminationsidWithHttpInfo(id, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Find all instances of the model matched by filter from the data source. * * @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public examinationFind(filter?: string, extraHttpRequestParams?: any): Observable<Array<Examination>> { return this.examinationFindWithHttpInfo(filter, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Find a model instance by {{id}} from the data source. * * @param id Model id * @param filter Filter defining fields and include - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public examinationFindById(id: string, filter?: string, extraHttpRequestParams?: any): Observable<Examination> { return this.examinationFindByIdWithHttpInfo(id, filter, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Find first instance of the model matched by filter from the data source. * * @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public examinationFindOne(filter?: string, extraHttpRequestParams?: any): Observable<Examination> { return this.examinationFindOneWithHttpInfo(filter, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Insert sample data set of test examinations. * * @param sectionNumber The section number according to http://icd9cm.chrisendres.com/index.php?action&#x3D;procslist, e.g. \&quot;3\&quot;, \&quot;3A\&quot; or \&quot;12\&quot;. * @param locale The locale to use for test examinations. Defaults to \&quot;en_US\&quot;. Currently only \&quot;de_**\&quot; are available. */ public examinationInsertTestData(sectionNumber: string, locale?: string, extraHttpRequestParams?: any): Observable<InlineResponse2005> { return this.examinationInsertTestDataWithHttpInfo(sectionNumber, locale, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Patch an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public examinationPatchOrCreate(data?: Examination, extraHttpRequestParams?: any): Observable<Examination> { return this.examinationPatchOrCreateWithHttpInfo(data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Patch attributes for a model instance and persist it into the data source. * * @param id Examination id * @param data An object of model property name/value pairs */ public examinationPrototypePatchAttributes(id: string, data?: Examination, extraHttpRequestParams?: any): Observable<Examination> { return this.examinationPrototypePatchAttributesWithHttpInfo(id, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Replace attributes for a model instance and persist it into the data source. * * @param id Model id * @param data Model instance data */ public examinationReplaceByIdPostExaminationsidReplace(id: string, data?: Examination, extraHttpRequestParams?: any): Observable<Examination> { return this.examinationReplaceByIdPostExaminationsidReplaceWithHttpInfo(id, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Replace attributes for a model instance and persist it into the data source. * * @param id Model id * @param data Model instance data */ public examinationReplaceByIdPutExaminationsid(id: string, data?: Examination, extraHttpRequestParams?: any): Observable<Examination> { return this.examinationReplaceByIdPutExaminationsidWithHttpInfo(id, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Replace an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public examinationReplaceOrCreatePostExaminationsReplaceOrCreate(data?: Examination, extraHttpRequestParams?: any): Observable<Examination> { return this.examinationReplaceOrCreatePostExaminationsReplaceOrCreateWithHttpInfo(data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Replace an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public examinationReplaceOrCreatePutExaminations(data?: Examination, extraHttpRequestParams?: any): Observable<Examination> { return this.examinationReplaceOrCreatePutExaminationsWithHttpInfo(data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Update instances of the model matched by {{where}} from the data source. * * @param where Criteria to match model instances * @param data An object of model property name/value pairs */ public examinationUpdateAll(where?: string, data?: Examination, extraHttpRequestParams?: any): Observable<InlineResponse2002> { return this.examinationUpdateAllWithHttpInfo(where, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Update an existing model instance or insert a new one into the data source based on the where criteria. * * @param where Criteria to match model instances * @param data An object of model property name/value pairs */ public examinationUpsertWithWhere(where?: string, data?: Examination, extraHttpRequestParams?: any): Observable<Examination> { return this.examinationUpsertWithWhereWithHttpInfo(where, data, extraHttpRequestParams) .map((response: Response) => { if (response.status === 204) { return undefined; } else { return response.json(); } }); } /** * Count instances of the model matched by where from the data source. * * @param where Criteria to match model instances */ public examinationCountWithHttpInfo(where?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations/count'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (where !== undefined) { queryParameters.set('where', <any>where); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Create a new instance of the model and persist it into the data source. * * @param data Model instance data */ public examinationCreateWithHttpInfo(data?: Examination, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Create a change stream. * * @param options */ public examinationCreateChangeStreamGetExaminationsChangeStreamWithHttpInfo(options?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations/change-stream'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (options !== undefined) { queryParameters.set('options', <any>options); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, responseType: ResponseContentType.Blob, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Create a change stream. * * @param options */ public examinationCreateChangeStreamPostExaminationsChangeStreamWithHttpInfo(options?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations/change-stream'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Content-Type header let consumes: string[] = [ 'application/json', 'application/x-www-form-urlencoded', 'application/xml', 'text/xml' ]; let canConsumeForm = this.canConsumeForm(consumes); let useForm = false; let formParams = new (useForm ? FormData : URLSearchParams as any)() as { set(param: string, value: any): void; }; // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; if (options !== undefined) { formParams.set('options', <any>options); } let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: formParams, responseType: ResponseContentType.Blob, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Deletes all data. * */ public examinationDeleteAllExaminationsWithHttpInfo(extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations/deleteAll'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Delete a model instance by {{id}} from the data source. * * @param id Model id */ public examinationDeleteByIdWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling examinationDeleteById.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Delete, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Check whether a model instance exists in the data source. * * @param id Model id */ public examinationExistsGetExaminationsidExistsWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations/${id}/exists' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling examinationExistsGetExaminationsidExists.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Check whether a model instance exists in the data source. * * @param id Model id */ public examinationExistsHeadExaminationsidWithHttpInfo(id: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling examinationExistsHeadExaminationsid.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Head, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Find all instances of the model matched by filter from the data source. * * @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public examinationFindWithHttpInfo(filter?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (filter !== undefined) { queryParameters.set('filter', <any>filter); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Find a model instance by {{id}} from the data source. * * @param id Model id * @param filter Filter defining fields and include - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public examinationFindByIdWithHttpInfo(id: string, filter?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling examinationFindById.'); } if (filter !== undefined) { queryParameters.set('filter', <any>filter); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Find first instance of the model matched by filter from the data source. * * @param filter Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) */ public examinationFindOneWithHttpInfo(filter?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations/findOne'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (filter !== undefined) { queryParameters.set('filter', <any>filter); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Get, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Insert sample data set of test examinations. * * @param sectionNumber The section number according to http://icd9cm.chrisendres.com/index.php?action&#x3D;procslist, e.g. \&quot;3\&quot;, \&quot;3A\&quot; or \&quot;12\&quot;. * @param locale The locale to use for test examinations. Defaults to \&quot;en_US\&quot;. Currently only \&quot;de_**\&quot; are available. */ public examinationInsertTestDataWithHttpInfo(sectionNumber: string, locale?: string, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations/insertTestData'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'sectionNumber' is not null or undefined if (sectionNumber === null || sectionNumber === undefined) { throw new Error('Required parameter sectionNumber was null or undefined when calling examinationInsertTestData.'); } if (sectionNumber !== undefined) { queryParameters.set('sectionNumber', <any>sectionNumber); } if (locale !== undefined) { queryParameters.set('locale', <any>locale); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Patch an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public examinationPatchOrCreateWithHttpInfo(data?: Examination, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Patch, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Patch attributes for a model instance and persist it into the data source. * * @param id Examination id * @param data An object of model property name/value pairs */ public examinationPrototypePatchAttributesWithHttpInfo(id: string, data?: Examination, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling examinationPrototypePatchAttributes.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Patch, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Replace attributes for a model instance and persist it into the data source. * * @param id Model id * @param data Model instance data */ public examinationReplaceByIdPostExaminationsidReplaceWithHttpInfo(id: string, data?: Examination, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations/${id}/replace' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling examinationReplaceByIdPostExaminationsidReplace.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Replace attributes for a model instance and persist it into the data source. * * @param id Model id * @param data Model instance data */ public examinationReplaceByIdPutExaminationsidWithHttpInfo(id: string, data?: Examination, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations/${id}' .replace('${' + 'id' + '}', String(id)); let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // verify required parameter 'id' is not null or undefined if (id === null || id === undefined) { throw new Error('Required parameter id was null or undefined when calling examinationReplaceByIdPutExaminationsid.'); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Replace an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public examinationReplaceOrCreatePostExaminationsReplaceOrCreateWithHttpInfo(data?: Examination, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations/replaceOrCreate'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Replace an existing model instance or insert a new one into the data source. * * @param data Model instance data */ public examinationReplaceOrCreatePutExaminationsWithHttpInfo(data?: Examination, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Put, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Update instances of the model matched by {{where}} from the data source. * * @param where Criteria to match model instances * @param data An object of model property name/value pairs */ public examinationUpdateAllWithHttpInfo(where?: string, data?: Examination, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations/update'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (where !== undefined) { queryParameters.set('where', <any>where); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } /** * Update an existing model instance or insert a new one into the data source based on the where criteria. * * @param where Criteria to match model instances * @param data An object of model property name/value pairs */ public examinationUpsertWithWhereWithHttpInfo(where?: string, data?: Examination, extraHttpRequestParams?: any): Observable<Response> { const path = this.basePath + '/Examinations/upsertWithWhere'; let queryParameters = new URLSearchParams(); let headers = new Headers(this.defaultHeaders.toJSON()); // https://github.com/angular/angular/issues/6845 if (where !== undefined) { queryParameters.set('where', <any>where); } // to determine the Accept header let produces: string[] = [ 'application/json', 'application/xml', 'text/xml', 'application/javascript', 'text/javascript' ]; headers.set('Content-Type', 'application/json'); let requestOptions: RequestOptionsArgs = new RequestOptions({ method: RequestMethod.Post, headers: headers, body: data == null ? '' : JSON.stringify(data), // https://github.com/angular/angular/issues/10612 search: queryParameters }); // https://github.com/swagger-api/swagger-codegen/issues/4037 if (extraHttpRequestParams) { requestOptions = (<any>Object).assign(requestOptions, extraHttpRequestParams); } return this.http.request(path, requestOptions); } }
the_stack
import { createElement } from "@syncfusion/ej2-base"; import { BarcodeGenerator } from "../../../src/barcode/barcode"; let barcode: BarcodeGenerator; let ele: HTMLElement; describe('Barcode Control ', () => { describe('rendering of basic coda bar rendering', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'codabar1' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Codabar', value: '12341234', mode: 'SVG', }); barcode.appendTo('#codabar1'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('rendering of basic coda bar rendering', (done: Function) => { let barcode = document.getElementById('codabar1') let children: HTMLElement = barcode.children[0] as HTMLElement expect(Math.round(Number(children.children[0].getAttribute('x'))) === 56 || Math.round(Number(children.children[0].getAttribute('x'))) === 52 && children.children[1].getAttribute('x') === '10' && Math.round(Number(children.children[1].getAttribute('width'))) === 2 && Math.round(Number(children.children[2].getAttribute('width'))) === 4 && Math.round(Number(children.children[1].getAttribute('x'))) === 10 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 188).toBe(true); done() }); }); describe('rendering of basic coda bar rendering', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'invalid' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Codabar', value: 'yyy', mode: 'SVG', }); barcode.appendTo('#invalid'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('rendering of basic coda bar rendering', (done: Function) => { done() }); }); }); describe('Barcode Control ', () => { describe('rendering of basic coda bar rendering', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'codabar2' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '600px', height: '150px', type: 'Codabar', value: '12341234', mode: 'SVG', }); barcode.appendTo('#codabar2'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('rendering of basic coda bar rendering', (done: Function) => { let barcode = document.getElementById('codabar2') let children: HTMLElement = barcode.children[0] as HTMLElement expect(Math.round(Number(children.children[0].getAttribute('x'))) === 256 || Math.round(Number(children.children[0].getAttribute('x'))) === 252 && children.children[1].getAttribute('x') === '10' && Math.round(Number(children.children[1].getAttribute('width'))) === 6 && Math.round(Number(children.children[2].getAttribute('width'))) === 11 && Math.round(Number(children.children[1].getAttribute('x'))) === 10 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 584).toBe(true); done() }); }); }); describe('Barcode Control ', () => { describe('Checking the general rendering of bar code - width testing using pixels', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'codabar3' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Codabar', value: '12341234', mode: 'SVG', margin: { right: -10, left: 30, top: -10 } //margin:{left:20,right:-20,top:-30,bottom:10} }); barcode.appendTo('#codabar3'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('Checking the general rendering of bar code - width testing using pixels', (done: Function) => { let barcode = document.getElementById('codabar3') let children: HTMLElement = barcode.children[0] as HTMLElement expect(Math.round(Number(children.children[0].getAttribute('x'))) === 76 || Math.round(Number(children.children[0].getAttribute('x'))) === 72 && children.children[1].getAttribute('x') === '30' && Math.round(Number(children.children[1].getAttribute('width'))) === 2 && Math.round(Number(children.children[2].getAttribute('width'))) === 4 && Math.round(Number(children.children[1].getAttribute('x'))) === 30 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 208 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('y'))) === -10 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('height'))) === 136 || Math.round(Number(children.children[children.childElementCount - 1].getAttribute('height'))) === 137).toBe(true); done() }); }); }); describe('Barcode Control ', () => { describe('coda bar testing for margin', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'codabar4' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Codabar', value: '12341234', mode: 'SVG', margin: { bottom: -20, top: -20, left: -20, right: -20 } //margin:{left:20,right:-20,top:-30,bottom:10} }); barcode.appendTo('#codabar4'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('coda bar testing for margin', (done: Function) => { let barcode = document.getElementById('codabar4') let children: HTMLElement = barcode.children[0] as HTMLElement expect(Math.round(Number(children.children[0].getAttribute('x'))) === 56 && children.children[1].getAttribute('x') === '-20' && Math.round(Number(children.children[1].getAttribute('width'))) === 2 && Math.round(Number(children.children[2].getAttribute('width'))) === 5 && Math.round(Number(children.children[1].getAttribute('x'))) === -20 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 218 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('y'))) === -20 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('height'))) === 176); done() }); }); }); describe('Barcode Control ', () => { describe('coda bar testing for margin', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'codabar5' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Codabar', value: '12341234', mode: 'SVG', margin: { bottom: 20, top: 20, left: 20, right: 20 } }); barcode.appendTo('#codabar5'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('coda bar testing for margin', (done: Function) => { let barcode = document.getElementById('codabar5') let children: HTMLElement = barcode.children[0] as HTMLElement expect(Math.round(Number(children.children[1].getAttribute('width'))) === 2 && Math.round(Number(children.children[1].getAttribute('height'))) === 96 && Math.round(Number(children.children[1].getAttribute('x'))) === 20 && Math.round(Number(children.children[1].getAttribute('y'))) === 20 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('x'))) === 178 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('y'))) === 20 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('height'))) === 96 && Math.round(Number(children.children[children.childElementCount - 1].getAttribute('width'))) === 2 && Math.round(Number(children.children[0].getAttribute('x'))) === 56 && Math.round(Number(children.children[0].getAttribute('y'))) === 130 && (children.children[0] as HTMLElement).style.fontSize === '20px'); done() }); }); }); describe('Barcode Control ', () => { describe('coda bar testing for displaytext margin', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'codabar6' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Codabar', value: '12341234', mode: 'SVG', displayText: { text: 'codabar', margin: { left: 70, right: 70, top: 30, bottom: 30 } } }); barcode.appendTo('#codabar6'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('coda bar testing for displaytext margin', (done: Function) => { let barcode = document.getElementById('codabar6') let children: HTMLElement = barcode.children[0] as HTMLElement expect(Math.round(Number(children.children[1].getAttribute('width'))) === 2 && Math.round(Number(children.children[1].getAttribute('height'))) === 56 && Math.round(Number(children.children[1].getAttribute('x'))) === 10 && Math.round(Number(children.children[1].getAttribute('y'))) === 10 && Math.round(Number(children.children[2].getAttribute('width'))) === 4 && Math.round(Number(children.children[0].getAttribute('x'))) === 80 && Math.round(Number(children.children[0].getAttribute('y'))) === 110 && (children.children[0] as HTMLElement).style.fontSize === '10.2px'); done() }); }); }); describe('Barcode Control ', () => { describe('coda bar testing for displaytext margin', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'codabar7' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Codabar', value: '12341234', mode: 'SVG', displayText: { text: 'codabar', margin: { left: 70, right: 70, top: -40 } } }); barcode.appendTo('#codabar7'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('coda bar testing for displaytext margin', (done: Function) => { let barcode = document.getElementById('codabar7') let children: HTMLElement = barcode.children[0] as HTMLElement expect(Math.round(Number(children.children[1].getAttribute('width'))) === 2 && Math.round(Number(children.children[1].getAttribute('height'))) === 116 && Math.round(Number(children.children[1].getAttribute('x'))) === 10 && Math.round(Number(children.children[1].getAttribute('y'))) === 10 && Math.round(Number(children.children[2].getAttribute('width'))) === 4 && Math.round(Number(children.children[0].getAttribute('x'))) === 80 && Math.round(Number(children.children[0].getAttribute('y'))) === 100 && (children.children[0] as HTMLElement).style.fontSize === '10.2px'); done() }); }); }); var output1 = { 0: { width: "1.78", height: "86.50", x: 10, y: 10 },//code changed 1: { width: "3.56", height: "86.50", x: 14, y: 10 }, 2: { width: "1.78", height: "86.50", x: 21, y: 10 }, 3: { width: "1.78", height: "86.50", x: 26, y: 10 }, 4: { width: "1.78", height: "86.50", x: 30, y: 10 }, 5: { width: "1.78", height: "86.50", x: 33, y: 10 }, 6: { width: "3.56", height: "86.50", x: 37, y: 10 }, 7: { width: "1.78", height: "86.50", x: 44, y: 10 }, 8: { width: "1.78", height: "86.50", x: 47, y: 10 }, 9: { width: "1.78", height: "86.50", x: 51, y: 10 }, 10: { width: "1.78", height: "86.50", x: 56, y: 10 }, 11: { width: "3.56", height: "86.50", x: 60, y: 10 }, 12: { width: "3.56", height: "86.50", x: 65, y: 10 }, 13: { width: "1.78", height: "86.50", x: 72, y: 10 }, 14: { width: "1.78", height: "86.50", x: 76, y: 10 }, 15: { width: "1.78", height: "86.50", x: 80, y: 10 }, 16: { width: "1.78", height: "86.50", x: 83, y: 10 }, 17: { width: "3.56", height: "86.50", x: 87, y: 10 }, 18: { width: "1.78", height: "86.50", x: 92, y: 10 }, 19: { width: "1.78", height: "86.50", x: 97, y: 10 }, 20: { width: "1.78", height: "86.50", x: 101, y: 10 }, 21: { width: "1.78", height: "86.50", x: 104, y: 10 }, 22: { width: "3.56", height: "86.50", x: 108, y: 10 }, 23: { width: "1.78", height: "86.50", x: 115, y: 10 }, 24: { width: "1.78", height: "86.50", x: 119, y: 10 }, 25: { width: "1.78", height: "86.50", x: 122, y: 10 }, 26: { width: "1.78", height: "86.50", x: 128, y: 10 }, 27: { width: "3.56", height: "86.50", x: 131, y: 10 }, 28: { width: "3.56", height: "86.50", x: 137, y: 10 }, 29: { width: "1.78", height: "86.50", x: 144, y: 10 }, 30: { width: "1.78", height: "86.50", x: 147, y: 10 }, 31: { width: "1.78", height: "86.50", x: 151, y: 10 }, 32: { width: "1.78", height: "86.50", x: 154, y: 10 }, 33: { width: "3.56", height: "86.50", x: 158, y: 10 }, 34: { width: "1.78", height: "86.50", x: 163, y: 10 }, 35: { width: "1.78", height: "86.50", x: 169, y: 10 }, 36: { width: "1.78", height: "86.50", x: 172, y: 10 }, 37: { width: "3.56", height: "86.50", x: 176, y: 10 }, 38: { width: "1.78", height: "86.50", x: 183, y: 10 }, 39: { width: "1.78", height: "86.50", x: 188, y: 10 }, }; describe('Barcode Control ', () => { describe('coda bar testing for all lines check', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'codabar8' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Codabar', value: '12341234', mode: 'SVG', displayText: { text: 'codabar', margin: { left: 70, right: 70, top: -40, bottom: 30 } } }); barcode.appendTo('#codabar8'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('checking the bar code all lines width height offset x offsety testcase4', (done: Function) => { let barcode = document.getElementById('codabar8') let children: HTMLElement = barcode.children[0] as HTMLElement expect(Math.round(Number(children.children[0].getAttribute('x'))) === 80 && (children.children[0] as HTMLElement).style.fontSize === '10.2px' || (children.children[0] as HTMLElement).style.fontSize === '9.4px').toBe(true); for (let j: number = 1; j < children.children.length - 1; j++) { expect(Math.round(Number(children.children[j + 1].getAttribute('x'))) === output1[j].x && Math.round(Number(children.children[j + 1].getAttribute('y'))) === output1[j].y && parseFloat((children.children[j + 1].getAttribute('width'))).toFixed(2) === output1[j].width && parseFloat((children.children[j + 1].getAttribute('height'))).toFixed(2) === output1[j].height).toBe(true); } done(); }); }); }); describe('Barcode Control ', () => { describe('coda bar testing for all lines check', () => { //let barcode: BarcodeGenerator; //let ele: HTMLElement; beforeAll((): void => { ele = createElement('div', { id: 'codabar9' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '700px', height: '150px', type: 'Codabar', value: '12341234', mode: 'SVG', margin: { left: 70, right: 70, top: -40, bottom: 30 }, displayText: { text: 'codabarcodabarcodabarcodabarcodabarcodabarcodabarcodabarcodabar', margin: { left: 70, right: 70 } } }); barcode.appendTo('#codabar9'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); var output2 = { 0: { width: "5.54", height: "146.50", x: 70, y: -40 }, 1: { width: "11.09", height: "146.50", x: 81, y: -40 }, 2: { width: "5.54", height: "146.50", x: 103, y: -40 }, 3: { width: "5.54", height: "146.50", x: 120, y: -40 }, 4: { width: "5.54", height: "146.50", x: 131, y: -40 }, 5: { width: "5.54", height: "146.50", x: 142, y: -40 }, 6: { width: "11.09", height: "146.50", x: 153, y: -40 }, 7: { width: "5.54", height: "146.50", x: 175, y: -40 }, 8: { width: "5.54", height: "146.50", x: 186, y: -40 }, 9: { width: "5.54", height: "146.50", x: 198, y: -40 }, 10: { width: "5.54", height: "146.50", x: 214, y: -40 }, 11: { width: "11.09", height: "146.50", x: 225, y: -40 }, 12: { width: "11.09", height: "146.50", x: 242, y: -40 }, 13: { width: "5.54", height: "146.50", x: 264, y: -40 }, 14: { width: "5.54", height: "146.50", x: 275, y: -40 }, 15: { width: "5.54", height: "146.50", x: 286, y: -40 }, 16: { width: "5.54", height: "146.50", x: 297, y: -40 }, 17: { width: "11.09", height: "146.50", x: 308, y: -40 }, 18: { width: "5.54", height: "146.50", x: 325, y: -40 }, 19: { width: "5.54", height: "146.50", x: 342, y: -40 }, 20: { width: "5.54", height: "146.50", x: 353, y: -40 }, 21: { width: "5.54", height: "146.50", x: 364, y: -40 }, 22: { width: "11.09", height: "146.50", x: 375, y: -40 }, 23: { width: "5.54", height: "146.50", x: 397, y: -40 }, 24: { width: "5.54", height: "146.50", x: 408, y: -40 }, 25: { width: "5.54", height: "146.50", x: 419, y: -40 }, 26: { width: "5.54", height: "146.50", x: 436, y: -40 }, 27: { width: "11.09", height: "146.50", x: 447, y: -40 }, 28: { width: "11.09", height: "146.50", x: 464, y: -40 }, 29: { width: "5.54", height: "146.50", x: 486, y: -40 }, 30: { width: "5.54", height: "146.50", x: 497, y: -40 }, 31: { width: "5.54", height: "146.50", x: 508, y: -40 }, 32: { width: "5.54", height: "146.50", x: 519, y: -40 }, 33: { width: "11.09", height: "146.50", x: 530, y: -40 }, 34: { width: "5.54", height: "146.50", x: 547, y: -40 }, 35: { width: "5.54", height: "146.50", x: 563, y: -40 }, 36: { width: "5.54", height: "146.50", x: 575, y: -40 }, 37: { width: "11.09", height: "146.50", x: 586, y: -40 }, 38: { width: "5.54", height: "146.50", x: 608, y: -40 }, 39: { width: "5.54", height: "146.50", x: 624, y: -40 }, }; it('checking the bar code all lines width height offset x offsety testcase4', (done: Function) => { let barcode = document.getElementById('codabar9') let children: HTMLElement = barcode.children[0] as HTMLElement expect(Math.round(Number(children.children[0].getAttribute('x'))) === 140 && (children.children[0] as HTMLElement).style.fontSize === '12px' || (children.children[0] as HTMLElement).style.fontSize === '11px').toBe(true); for (let j: number = 1; j < children.children.length - 1; j++) { expect(Math.round(Number(children.children[j + 1].getAttribute('x'))) === output2[j].x && Math.round(Number(children.children[j + 1].getAttribute('y'))) === output2[j].y && parseFloat((children.children[j + 1].getAttribute('width'))).toFixed(2) === output2[j].width && parseFloat((children.children[j + 1].getAttribute('height'))).toFixed(2) === output2[j].height).toBe(true); } done(); }); }); }); describe('barcode export - SVG mode', () => { beforeAll((): void => { ele = createElement('div', { id: 'codabar2' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', value: "ABCD", displayText: { visibility: true, size: 9, text: "ABCD"}, }); barcode.appendTo('#codabar2'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('barcode export - - return Base64 in JPG format', (done: Function) => { barcode.exportAsBase64Image('JPG'); done() console.log('########################################################################'); }); it('barcode export - return Base64 in PNG format', (done: Function) => { barcode.exportAsBase64Image('PNG'); done() }); it('barcode export - Download the image in JPG format', (done: Function) => { let svg: any; svg = barcode.exportImage('Export','JPG'); expect(svg).not.toBeNull(); done() }); }); describe('barcode export - Canvas mode', () => { beforeAll((): void => { ele = createElement('div', { id: 'codabar2' }); document.body.appendChild(ele); barcode = new BarcodeGenerator({ width: '200px', height: '150px', type: 'Code39', mode:'Canvas', value: "ABCD", displayText: { visibility: true, size: 9, text: ""}, }); barcode.appendTo('#codabar2'); }); afterAll((): void => { barcode.destroy(); ele.remove(); }); it('barcode export - return Base64 in JPG format', (done: Function) => { barcode.exportAsBase64Image('JPG') ; done() }); it('barcode export - return Base64 in PNG format' ,(done: Function) => { barcode.exportAsBase64Image('PNG'); done() }); it('barcode export - Download the image in JPG format', (done: Function) => { let svg: any; svg = barcode.exportImage('Export','JPG'); expect(svg).not.toBeNull(); done() }); });
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/backupPoliciesMappers"; import * as Parameters from "../models/parameters"; import { StorSimple8000SeriesManagementClientContext } from "../storSimple8000SeriesManagementClientContext"; /** Class representing a BackupPolicies. */ export class BackupPolicies { private readonly client: StorSimple8000SeriesManagementClientContext; /** * Create a BackupPolicies. * @param {StorSimple8000SeriesManagementClientContext} client Reference to the service client. */ constructor(client: StorSimple8000SeriesManagementClientContext) { this.client = client; } /** * Gets all the backup policies in a device. * @param deviceName The device name * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<Models.BackupPoliciesListByDeviceResponse> */ listByDevice(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.BackupPoliciesListByDeviceResponse>; /** * @param deviceName The device name * @param resourceGroupName The resource group name * @param managerName The manager name * @param callback The callback */ listByDevice(deviceName: string, resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.BackupPolicyList>): void; /** * @param deviceName The device name * @param resourceGroupName The resource group name * @param managerName The manager name * @param options The optional parameters * @param callback The callback */ listByDevice(deviceName: string, resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BackupPolicyList>): void; listByDevice(deviceName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BackupPolicyList>, callback?: msRest.ServiceCallback<Models.BackupPolicyList>): Promise<Models.BackupPoliciesListByDeviceResponse> { return this.client.sendOperationRequest( { deviceName, resourceGroupName, managerName, options }, listByDeviceOperationSpec, callback) as Promise<Models.BackupPoliciesListByDeviceResponse>; } /** * Gets the properties of the specified backup policy name. * @param deviceName The device name * @param backupPolicyName The name of backup policy to be fetched. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<Models.BackupPoliciesGetResponse> */ get(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.BackupPoliciesGetResponse>; /** * @param deviceName The device name * @param backupPolicyName The name of backup policy to be fetched. * @param resourceGroupName The resource group name * @param managerName The manager name * @param callback The callback */ get(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, callback: msRest.ServiceCallback<Models.BackupPolicy>): void; /** * @param deviceName The device name * @param backupPolicyName The name of backup policy to be fetched. * @param resourceGroupName The resource group name * @param managerName The manager name * @param options The optional parameters * @param callback The callback */ get(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.BackupPolicy>): void; get(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.BackupPolicy>, callback?: msRest.ServiceCallback<Models.BackupPolicy>): Promise<Models.BackupPoliciesGetResponse> { return this.client.sendOperationRequest( { deviceName, backupPolicyName, resourceGroupName, managerName, options }, getOperationSpec, callback) as Promise<Models.BackupPoliciesGetResponse>; } /** * Creates or updates the backup policy. * @param deviceName The device name * @param backupPolicyName The name of the backup policy to be created/updated. * @param parameters The backup policy. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<Models.BackupPoliciesCreateOrUpdateResponse> */ createOrUpdate(deviceName: string, backupPolicyName: string, parameters: Models.BackupPolicy, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<Models.BackupPoliciesCreateOrUpdateResponse> { return this.beginCreateOrUpdate(deviceName,backupPolicyName,parameters,resourceGroupName,managerName,options) .then(lroPoller => lroPoller.pollUntilFinished()) as Promise<Models.BackupPoliciesCreateOrUpdateResponse>; } /** * Deletes the backup policy. * @param deviceName The device name * @param backupPolicyName The name of the backup policy. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginDeleteMethod(deviceName,backupPolicyName,resourceGroupName,managerName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Backup the backup policy now. * @param deviceName The device name * @param backupPolicyName The backup policy name. * @param backupType The backup Type. This can be cloudSnapshot or localSnapshot. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ backupNow(deviceName: string, backupPolicyName: string, backupType: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginBackupNow(deviceName,backupPolicyName,backupType,resourceGroupName,managerName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * Creates or updates the backup policy. * @param deviceName The device name * @param backupPolicyName The name of the backup policy to be created/updated. * @param parameters The backup policy. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginCreateOrUpdate(deviceName: string, backupPolicyName: string, parameters: Models.BackupPolicy, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, backupPolicyName, parameters, resourceGroupName, managerName, options }, beginCreateOrUpdateOperationSpec, options); } /** * Deletes the backup policy. * @param deviceName The device name * @param backupPolicyName The name of the backup policy. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(deviceName: string, backupPolicyName: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, backupPolicyName, resourceGroupName, managerName, options }, beginDeleteMethodOperationSpec, options); } /** * Backup the backup policy now. * @param deviceName The device name * @param backupPolicyName The backup policy name. * @param backupType The backup Type. This can be cloudSnapshot or localSnapshot. * @param resourceGroupName The resource group name * @param managerName The manager name * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginBackupNow(deviceName: string, backupPolicyName: string, backupType: string, resourceGroupName: string, managerName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { deviceName, backupPolicyName, backupType, resourceGroupName, managerName, options }, beginBackupNowOperationSpec, options); } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listByDeviceOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/backupPolicies", urlParameters: [ Parameters.deviceName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BackupPolicyList }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/backupPolicies/{backupPolicyName}", urlParameters: [ Parameters.deviceName, Parameters.backupPolicyName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.BackupPolicy }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginCreateOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/backupPolicies/{backupPolicyName}", urlParameters: [ Parameters.deviceName, Parameters.backupPolicyName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.BackupPolicy, required: true } }, responses: { 200: { bodyMapper: Mappers.BackupPolicy }, 202: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/backupPolicies/{backupPolicyName}", urlParameters: [ Parameters.deviceName, Parameters.backupPolicyName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginBackupNowOperationSpec: msRest.OperationSpec = { httpMethod: "POST", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.StorSimple/managers/{managerName}/devices/{deviceName}/backupPolicies/{backupPolicyName}/backup", urlParameters: [ Parameters.deviceName, Parameters.backupPolicyName, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.managerName ], queryParameters: [ Parameters.backupType, Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
import * as chai from 'chai'; import chaiEnzyme from 'chai-enzyme'; import {shallow, ShallowWrapper} from 'enzyme'; import * as sinon from 'sinon'; import GestureControls, { GestureControlsAction, GestureControlsProps, GestureControlsState, sameOppositeQuadrant, PAN_BUTTON, ZOOM_BUTTON, ROTATE_BUTTON } from './gestureControls'; describe('GestureControls component', () => { chai.use(chaiEnzyme()); const sandbox = sinon.createSandbox(); const baseEvent = { preventDefault: sinon.stub(), stopPropagation: sinon.stub(), currentTarget: {getBoundingClientRect: () => ({left: 0, top: 0})}, isDefaultPrevented: () => false }; const mouseDownEvent = 'mouseDown'; const mouseMoveEvent = 'mouseMove'; const mouseUpEvent = 'mouseUp'; const mouseWheelEvent = 'wheel'; const touchStartEvent = 'touchStart'; const touchMoveEvent = 'touchMove'; const touchEndEvent = 'touchEnd'; let onTap: sinon.SinonStub, onPress: sinon.SinonStub, onPan: sinon.SinonStub; let component: ShallowWrapper<GestureControlsProps, GestureControlsState>; let stubSetTimeout: sinon.SinonStub, stubClearTimeout: sinon.SinonStub; beforeEach(() => { onTap = sinon.stub(); onPress = sinon.stub(); onPan = sinon.stub(); component = shallow(<GestureControls onTap={onTap} onPress={onPress} onPan={onPan}/>); stubSetTimeout = sandbox.stub(window, 'setTimeout'); stubClearTimeout = sandbox.stub(window, 'clearTimeout'); }); afterEach(() => { sandbox.restore(); }); describe('sameOppositeQuadrant function', () => { it('should return 1 for parallel vectors', () => { let dot = sameOppositeQuadrant({x: 1, y: 0}, {x: 1, y: 0}); chai.assert.equal(dot, 1); }); it('should return -1 for antiparallel vectors', () => { let dot = sameOppositeQuadrant({x: 1, y: 0}, {x: -1, y: 0}); chai.assert.equal(dot, -1); }); it('should return 0 for vectors which diverge by 45 degrees', () => { let dot = sameOppositeQuadrant({x: 1, y: 0}, {x: 1, y: 1}); chai.assert.equal(dot, 0); }); it('should return 1 for vectors which diverge by less than 45 degrees', () => { let dot = sameOppositeQuadrant({x: 1, y: 0}, {x: 1, y: 0.999}); chai.assert.equal(dot, 1); }); }); describe('mouse events with panButton', () => { const startX = 2 * GestureControls.defaultProps.moveThreshold; const startY = 2 * GestureControls.defaultProps.moveThreshold; it('should start out treating a pan button click as a tap', () => { const event = { ...baseEvent, button: PAN_BUTTON, pageX: startX, pageY: startY }; component.simulate(mouseDownEvent, event); chai.assert.equal(component.instance().state.action, GestureControlsAction.TAPPING); component.simulate(mouseUpEvent, event); chai.assert.equal(onTap.callCount, 1); chai.assert.equal(onTap.getCall(0).args[0].x, startX); chai.assert.equal(onTap.getCall(0).args[0].y, startY); chai.assert.equal(stubClearTimeout.callCount, 1, 'should have cleared press timeout'); }); it('should change a tap to a press if it stays close to the start for long enough', () => { const clickEvent = { ...baseEvent, button: PAN_BUTTON, pageX: startX, pageY: startY }; component.simulate(mouseDownEvent, clickEvent); chai.assert.equal(component.instance().state.action, GestureControlsAction.TAPPING); chai.assert.equal(stubSetTimeout.callCount, 1, 'should have called setTimeout'); const timeoutFn = stubSetTimeout.getCall(0).args[0]; const moveEvent = { ...clickEvent, pageX: startX + GestureControls.defaultProps.moveThreshold - 1, pageY: startY }; component.simulate(mouseMoveEvent, moveEvent); timeoutFn(); chai.assert.equal(component.instance().state.action, GestureControlsAction.PRESSING); chai.assert.equal(onPress.callCount, 1); chai.assert.equal(onPress.getCall(0).args[0].x, startX); chai.assert.equal(onPress.getCall(0).args[0].y, startY); }); it('should change a tap to a pan if it moves too far', () => { const clickEvent = { ...baseEvent, button: PAN_BUTTON, pageX: startX, pageY: startY }; component.simulate(mouseDownEvent, clickEvent); chai.assert.equal(component.instance().state.action, GestureControlsAction.TAPPING); const moveEvent = { ...clickEvent, pageX: startX + GestureControls.defaultProps.moveThreshold, pageY: startY }; component.simulate(mouseMoveEvent, moveEvent); chai.assert.equal(component.instance().state.action, GestureControlsAction.PANNING); chai.assert.equal(onPan.callCount, 1); chai.assert.equal(onPan.getCall(0).args[0].x, GestureControls.defaultProps.moveThreshold); chai.assert.equal(stubClearTimeout.callCount, 1, 'should have cleared press timeout'); }); it('should remain a tap if it stays close and under the threshold time', () => { const clickEvent = { ...baseEvent, button: PAN_BUTTON, pageX: startX, pageY: startY }; component.simulate(mouseDownEvent, clickEvent); chai.assert.equal(component.instance().state.action, GestureControlsAction.TAPPING); const moveEvent = { ...clickEvent, pageX: startX + GestureControls.defaultProps.moveThreshold - 1, pageY: startY }; component.simulate(mouseMoveEvent, moveEvent); component.simulate(mouseUpEvent, moveEvent); chai.assert.equal(onTap.callCount, 1); chai.assert.equal(onTap.getCall(0).args[0].x, startX); chai.assert.equal(onTap.getCall(0).args[0].y, startY); chai.assert.equal(stubClearTimeout.callCount, 1, 'should have cleared press timeout'); }); it('should call onPan with deltas, starting from the initial click position', () => { const clickEvent = { ...baseEvent, button: PAN_BUTTON, pageX: startX, pageY: startY }; component.simulate(mouseDownEvent, clickEvent); chai.assert.equal(component.instance().state.action, GestureControlsAction.TAPPING); const moveEvent = { ...clickEvent, pageX: startX + GestureControls.defaultProps.moveThreshold - 1, pageY: startY }; component.simulate(mouseMoveEvent, moveEvent); chai.assert.equal(onPan.callCount, 0); component.simulate(mouseMoveEvent, {...moveEvent, pageX: 2 * startX}); chai.assert.equal(component.instance().state.action, GestureControlsAction.PANNING); chai.assert.equal(onPan.callCount, 1); chai.assert.equal(onPan.getCall(0).args[0].x, startX); chai.assert.equal(onPan.getCall(0).args[0].y, 0); component.simulate(mouseMoveEvent, {...moveEvent, pageX: startX, pageY: 2 * startY}); chai.assert.equal(component.instance().state.action, GestureControlsAction.PANNING); chai.assert.equal(onPan.callCount, 2); chai.assert.equal(onPan.getCall(1).args[0].x, -startX); chai.assert.equal(onPan.getCall(1).args[0].y, startY); }); }); describe('mouse events with zoomButton', () => { const startX = 100; const startY = 100; let onZoom: sinon.SinonStub; let component: ShallowWrapper<GestureControlsProps, GestureControlsState>; beforeEach(() => { onZoom = sinon.stub(); component = shallow(<GestureControls onZoom={onZoom}/>); }); it('should call onZoom with deltas, starting from the initial click position', () => { const clickEvent = { ...baseEvent, button: ZOOM_BUTTON, pageX: startX, pageY: startY }; component.simulate(mouseDownEvent, clickEvent); chai.assert.equal(component.instance().state.action, GestureControlsAction.ZOOMING); const moveEvent = { ...clickEvent, pageX: startX + GestureControls.defaultProps.moveThreshold - 1, pageY: startY }; component.simulate(mouseMoveEvent, moveEvent); chai.assert.equal(component.instance().state.action, GestureControlsAction.ZOOMING); chai.assert.equal(onZoom.callCount, 1); chai.assert.equal(onZoom.getCall(0).args[0].x, GestureControls.defaultProps.moveThreshold - 1); chai.assert.equal(onZoom.getCall(0).args[0].y, 0); component.simulate(mouseMoveEvent, {...moveEvent, pageX: startX, pageY: 2 * startY}); chai.assert.equal(component.instance().state.action, GestureControlsAction.ZOOMING); chai.assert.equal(onZoom.callCount, 2); chai.assert.equal(onZoom.getCall(1).args[0].x, -(GestureControls.defaultProps.moveThreshold - 1)); chai.assert.equal(onZoom.getCall(1).args[0].y, startY); }); }); describe('mouse events with rotateButton', () => { const startX = 100; const startY = 100; let onRotate: sinon.SinonStub; let component: ShallowWrapper<GestureControlsProps, GestureControlsState>; beforeEach(() => { onRotate = sinon.stub(); component = shallow(<GestureControls onRotate={onRotate}/>); }); it('should call onRotate with deltas, starting from the initial click position', () => { const clickEvent = { ...baseEvent, button: ROTATE_BUTTON, pageX: startX, pageY: startY }; component.simulate(mouseDownEvent, clickEvent); chai.assert.equal(component.instance().state.action, GestureControlsAction.ROTATING); const moveEvent = { ...clickEvent, pageX: startX + GestureControls.defaultProps.moveThreshold - 1, pageY: startY }; component.simulate(mouseMoveEvent, moveEvent); chai.assert.equal(component.instance().state.action, GestureControlsAction.ROTATING); chai.assert.equal(onRotate.callCount, 1); chai.assert.equal(onRotate.getCall(0).args[0].x, GestureControls.defaultProps.moveThreshold - 1); chai.assert.equal(onRotate.getCall(0).args[0].y, 0); component.simulate(mouseMoveEvent, {...moveEvent, pageX: startX, pageY: 2 * startY}); chai.assert.equal(component.instance().state.action, GestureControlsAction.ROTATING); chai.assert.equal(onRotate.callCount, 2); chai.assert.equal(onRotate.getCall(1).args[0].x, -(GestureControls.defaultProps.moveThreshold - 1)); chai.assert.equal(onRotate.getCall(1).args[0].y, startY); }); }); describe('mouse wheel events', () => { let onZoom: sinon.SinonStub; let component: ShallowWrapper<GestureControlsProps, GestureControlsState>; beforeEach(() => { onZoom = sinon.stub(); component = shallow(<GestureControls onZoom={onZoom}/>); }); it('should call onZoom with +ve Y on wheel down', () => { let event = { ...baseEvent, deltaY: 100 }; component.simulate(mouseWheelEvent, event); chai.assert.equal(onZoom.callCount, 1); // Zoom is converted to be in the Y direction only chai.assert.equal(onZoom.getCall(0).args[0].x, 0); chai.assert.isTrue(onZoom.getCall(0).args[0].y > 0); }); it('should call onZoom with -ve Y on wheel up', () => { let event = { ...baseEvent, deltaY: -100 }; component.simulate(mouseWheelEvent, event); chai.assert.equal(onZoom.callCount, 1); // Zoom is converted to be in the Y direction only chai.assert.equal(onZoom.getCall(0).args[0].x, 0); chai.assert.isTrue(onZoom.getCall(0).args[0].y < 0); }); }); describe('touch events with one finger', () => { const startX = 2 * GestureControls.defaultProps.moveThreshold; const startY = 2 * GestureControls.defaultProps.moveThreshold; let onTap: sinon.SinonStub, onPress: sinon.SinonStub, onPan: sinon.SinonStub; let component: ShallowWrapper<GestureControlsProps, GestureControlsState>; beforeEach(() => { onTap = sinon.stub(); onPress = sinon.stub(); onPan = sinon.stub(); component = shallow(<GestureControls onTap={onTap} onPress={onPress} onPan={onPan}/>); }); it('should start out treating a single finger touch as a tap', () => { const event = { ...baseEvent, touches: [ { pageX: startX, pageY: startY } ] }; component.simulate(touchStartEvent, event); chai.assert.equal(component.instance().state.action, GestureControlsAction.TAPPING); component.simulate(touchEndEvent, {...event, touches: []}); chai.assert.equal(onTap.callCount, 1); chai.assert.equal(onTap.getCall(0).args[0].x, startX); chai.assert.equal(onTap.getCall(0).args[0].y, startY); chai.assert.equal(stubClearTimeout.callCount, 1, 'should have cleared press timeout'); }); it('should change a tap to a press if it stays close to the start for long enough', () => { const touchEvent = { ...baseEvent, touches: [ { pageX: startX, pageY: startY } ] }; component.simulate(touchStartEvent, touchEvent); chai.assert.equal(component.instance().state.action, GestureControlsAction.TAPPING); chai.assert.equal(stubSetTimeout.callCount, 1, 'should have called setTimeout'); const timeoutFn = stubSetTimeout.getCall(0).args[0]; const moveEvent = { ...touchEvent, touches: [ { pageX: startX + GestureControls.defaultProps.moveThreshold - 1, pageY: startY } ] }; component.simulate(touchMoveEvent, moveEvent); timeoutFn(); chai.assert.equal(component.instance().state.action, GestureControlsAction.PRESSING); chai.assert.equal(onPress.callCount, 1); chai.assert.equal(onPress.getCall(0).args[0].x, startX); chai.assert.equal(onPress.getCall(0).args[0].y, startY); }); it('should change a tap to a pan if it moves too far', () => { const touchEvent = { ...baseEvent, touches: [ { pageX: startX, pageY: startY } ] }; component.simulate(touchStartEvent, touchEvent); chai.assert.equal(component.instance().state.action, GestureControlsAction.TAPPING); const moveEvent = { ...touchEvent, touches: [ { pageX: startX + GestureControls.defaultProps.moveThreshold, pageY: startY } ] }; component.simulate(touchMoveEvent, moveEvent); chai.assert.equal(component.instance().state.action, GestureControlsAction.PANNING); chai.assert.equal(onPan.callCount, 1); chai.assert.equal(onPan.getCall(0).args[0].x, GestureControls.defaultProps.moveThreshold); chai.assert.equal(stubClearTimeout.callCount, 1, 'should have cleared press timeout'); }); it('should remain a tap if it stays close and under the threshold time', () => { const touchEvent = { ...baseEvent, touches: [ { pageX: startX, pageY: startY } ] }; component.simulate(touchStartEvent, touchEvent); chai.assert.equal(component.instance().state.action, GestureControlsAction.TAPPING); const moveEvent = { ...touchEvent, touches: [ { pageX: startX + GestureControls.defaultProps.moveThreshold - 1, pageY: startY } ] }; component.simulate(touchMoveEvent, moveEvent); component.simulate(touchEndEvent, {...moveEvent, touches: []}); chai.assert.equal(onTap.callCount, 1); chai.assert.equal(onTap.getCall(0).args[0].x, startX); chai.assert.equal(onTap.getCall(0).args[0].y, startY); chai.assert.equal(stubClearTimeout.callCount, 1, 'should have cleared press timeout'); }); it('should call onPan with deltas, staring from the initial touch position', () => { const clickEvent = { ...baseEvent, touches: [ { pageX: startX, pageY: startY } ] }; component.simulate(touchStartEvent, clickEvent); chai.assert.equal(component.instance().state.action, GestureControlsAction.TAPPING); const moveEvent = { ...clickEvent, pageX: startX + GestureControls.defaultProps.moveThreshold - 1, pageY: startY }; component.simulate(touchMoveEvent, moveEvent); chai.assert.equal(onPan.callCount, 0); component.simulate(touchMoveEvent, { ...moveEvent, touches: [ { pageX: 2 * startX, pageY: startY } ] }); chai.assert.equal(component.instance().state.action, GestureControlsAction.PANNING); chai.assert.equal(onPan.callCount, 1); chai.assert.equal(onPan.getCall(0).args[0].x, startX); chai.assert.equal(onPan.getCall(0).args[0].y, 0); component.simulate(touchMoveEvent, { ...moveEvent, touches: [ { pageX: startX, pageY: 2 * startY } ] }); chai.assert.equal(component.instance().state.action, GestureControlsAction.PANNING); chai.assert.equal(onPan.callCount, 2); chai.assert.equal(onPan.getCall(1).args[0].x, -startX); chai.assert.equal(onPan.getCall(1).args[0].y, startY); }); }); describe('touch events with two fingers', () => { const startX1 = 100; const startY1 = 100; const startX2 = 200; const startY2 = 200; let onRotate: sinon.SinonStub, onZoom: sinon.SinonStub; let component: ShallowWrapper<GestureControlsProps, GestureControlsState>; beforeEach(() => { onRotate = sinon.stub(); onZoom = sinon.stub(); component = shallow(<GestureControls onRotate={onRotate} onZoom={onZoom}/>); }); it('should call onRotate vertically if the fingers move in parallel', () => { const event = { ...baseEvent, touches: [ { pageX: startX1, pageY: startY1 }, { pageX: startX2, pageY: startY2 } ] }; component.simulate(touchStartEvent, event); const deltaX = 20, deltaY = 10; component.simulate(touchMoveEvent, { ...event, touches: [ { pageX: startX1 + deltaX, pageY: startY1 + deltaY }, { pageX: startX2 + deltaX, pageY: startY2 + deltaY } ] }); chai.assert.equal(onRotate.callCount, 1); // Turns movement into purely vertical rotation chai.assert.equal(onRotate.getCall(0).args[0].x, 0); chai.assert.equal(onRotate.getCall(0).args[0].y, deltaY); // Should also not trigger a ping chai.assert.equal(stubClearTimeout.callCount, 1, 'should have cleared press timeout') }); it('should call onRotate if the fingers move in a clockwise direction', () => { const event = { ...baseEvent, touches: [ { pageX: startX1, pageY: startY1 }, { pageX: startX2, pageY: startY2 } ] }; component.simulate(touchStartEvent, event); const delta = 20; component.simulate(touchMoveEvent, { ...event, touches: [ { pageX: startX1 + delta, pageY: startY1 - delta }, { pageX: startX2 - delta, pageY: startY2 + delta } ] }); chai.assert.equal(onRotate.callCount, 1); // Rotate is converted to be in the X direction only chai.assert.equal(onRotate.getCall(0).args[0].x, -Math.sqrt(2 * delta * delta)); chai.assert.equal(onRotate.getCall(0).args[0].y, 0); }); it('should call onRotate if the fingers move in an anticlockwise direction', () => { const event = { ...baseEvent, touches: [ { pageX: startX1, pageY: startY1 }, { pageX: startX2, pageY: startY2 } ] }; component.simulate(touchStartEvent, event); const delta = 20; component.simulate(touchMoveEvent, { ...event, touches: [ { pageX: startX1 - delta, pageY: startY1 + delta }, { pageX: startX2 + delta, pageY: startY2 - delta } ] }); chai.assert.equal(onRotate.callCount, 1); // Rotate is converted to be in the X direction only chai.assert.equal(onRotate.getCall(0).args[0].x, Math.sqrt(2 * delta * delta)); chai.assert.equal(onRotate.getCall(0).args[0].y, 0); }); it('should call onZoom with -ve Y if the fingers move apart along the same axis', () => { const event = { ...baseEvent, touches: [ { pageX: startX1, pageY: startY1 }, { pageX: startX2, pageY: startY2 } ] }; component.simulate(touchStartEvent, event); const delta = 20; component.simulate(touchMoveEvent, { ...event, touches: [ { pageX: startX1 - delta, pageY: startY1 - delta }, { pageX: startX2 + delta, pageY: startY2 + delta } ] }); chai.assert.equal(onZoom.callCount, 1); // Zoom is converted to be in the Y direction only chai.assert.equal(onZoom.getCall(0).args[0].x, 0); chai.assert.equal(onZoom.getCall(0).args[0].y, -2 * Math.sqrt(2 * delta * delta)); }); it('should call onZoom with +ve Y if the fingers move together along the same axis', () => { const event = { ...baseEvent, touches: [ { pageX: startX1, pageY: startY1 }, { pageX: startX2, pageY: startY2 } ] }; component.simulate(touchStartEvent, event); const delta = 20; component.simulate(touchMoveEvent, { ...event, touches: [ { pageX: startX1 + delta, pageY: startY1 + delta }, { pageX: startX2 - delta, pageY: startY2 - delta } ] }); chai.assert.equal(onZoom.callCount, 1); // Zoom is converted to be in the Y direction only chai.assert.equal(onZoom.getCall(0).args[0].x, 0); chai.assert.equal(onZoom.getCall(0).args[0].y, 2 * Math.sqrt(2 * delta * delta)); }); }); });
the_stack
import * as _ from 'lodash'; import * as path from 'path'; import { performance } from 'perf_hooks'; import { CancellationToken, Range, TestItem, Uri, workspace, WorkspaceFolder } from 'vscode'; import { sendError } from 'vscode-extension-telemetry-wrapper'; import { INVOCATION_PREFIX, JavaTestRunnerDelegateCommands } from '../constants'; import { IJavaTestItem, TestLevel } from '../types'; import { executeJavaLanguageServerCommand } from '../utils/commandUtils'; import { getRequestDelay, lruCache, MovingAverage } from './debouncing'; import { runnableTag, testController } from './testController'; import { dataCache } from './testItemDataCache'; /** * Load the Java projects, which are the root nodes of the test explorer */ export async function loadJavaProjects(): Promise<void> { for (const workspaceFolder of workspace.workspaceFolders || [] ) { const testProjects: IJavaTestItem[] = await getJavaProjects(workspaceFolder); for (const project of testProjects) { if (testController?.items.get(project.id)) { continue; } const projectItem: TestItem = createTestItem(project); projectItem.canResolveChildren = true; testController?.items.add(projectItem); } } } /** * This method is used to synchronize the test items for the given parent node recursively. which means: * - If an existing child is not contained in the childrenData parameter, it will be deleted * - If a child does not exist, create it, otherwise, update it as well as its metadata. */ export function synchronizeItemsRecursively(parent: TestItem, childrenData: IJavaTestItem[] | undefined): void { if (childrenData) { // remove the out-of-date children parent.children.forEach((child: TestItem) => { if (child.id.startsWith(INVOCATION_PREFIX)) { // only remove the invocation items before a new test session starts return; } const existingItem: IJavaTestItem | undefined = childrenData.find((data: IJavaTestItem) => data.id === child.id); if (!existingItem) { parent.children.delete(child.id); } }); // update/create children for (const child of childrenData) { const childItem: TestItem = updateOrCreateTestItem(parent, child); if (child.testLevel <= TestLevel.Class) { childItem.canResolveChildren = true; } synchronizeItemsRecursively(childItem, child.children); } } } function updateOrCreateTestItem(parent: TestItem, childData: IJavaTestItem): TestItem { let childItem: TestItem | undefined = parent.children.get(childData.id); if (childItem) { updateTestItem(childItem, childData); } else { childItem = createTestItem(childData, parent); } return childItem; } function updateTestItem(testItem: TestItem, metaInfo: IJavaTestItem): void { testItem.range = asRange(metaInfo.range); if (metaInfo.testLevel !== TestLevel.Invocation) { dataCache.set(testItem, { jdtHandler: metaInfo.jdtHandler, fullName: metaInfo.fullName, projectName: metaInfo.projectName, testLevel: metaInfo.testLevel, testKind: metaInfo.testKind, }); } } /** * Create test item which will be shown in the test explorer * @param metaInfo The data from the server side of the test item * @param parent The parent node of the test item (if it has) * @returns The created test item */ export function createTestItem(metaInfo: IJavaTestItem, parent?: TestItem): TestItem { if (!testController) { throw new Error('Failed to create test item. The test controller is not initialized.'); } const item: TestItem = testController.createTestItem( metaInfo.id, metaInfo.label, metaInfo.uri ? Uri.parse(metaInfo.uri) : undefined, ); item.range = asRange(metaInfo.range); if (metaInfo.testLevel !== TestLevel.Invocation) { item.tags = [runnableTag]; dataCache.set(item, { jdtHandler: metaInfo.jdtHandler, fullName: metaInfo.fullName, projectName: metaInfo.projectName, testLevel: metaInfo.testLevel, testKind: metaInfo.testKind, }); } if (parent) { parent.children.add(item); } return item; } let updateNodeForDocumentTimeout: NodeJS.Timer; /** * Update test item in a document with adaptive debounce enabled. * @param uri uri of the document * @param testTypes test metadata */ export async function updateItemForDocumentWithDebounce(uri: Uri, testTypes?: IJavaTestItem[]): Promise<TestItem[]> { if (updateNodeForDocumentTimeout) { clearTimeout(updateNodeForDocumentTimeout); } const timeout: number = getRequestDelay(uri); return new Promise<TestItem[]>((resolve: (items: TestItem[]) => void): void => { updateNodeForDocumentTimeout = setTimeout(async () => { const startTime: number = performance.now(); const result: TestItem[] = await updateItemForDocument(uri, testTypes); const executionTime: number = performance.now() - startTime; const movingAverage: MovingAverage = lruCache.get(uri) || new MovingAverage(); movingAverage.update(executionTime); lruCache.set(uri, movingAverage); return resolve(result); }, timeout); }); } /** * Update test item in a document immediately. * @param uri uri of the document * @param testTypes test metadata */ export async function updateItemForDocument(uri: Uri, testTypes?: IJavaTestItem[]): Promise<TestItem[]> { testTypes = testTypes ?? await findTestTypesAndMethods(uri.toString()); let belongingPackage: TestItem | undefined; if (testTypes.length === 0) { belongingPackage = await resolveBelongingPackage(uri); } else { belongingPackage = findBelongingPackageItem(testTypes[0]) || await resolveBelongingPackage(uri); } if (!belongingPackage) { sendError(new Error('Failed to find the belonging package')); return []; } const tests: TestItem[] = []; if (testTypes.length === 0) { // Remove the children with the same uri when no test items is found belongingPackage.children.forEach((typeItem: TestItem) => { if (path.relative(typeItem.uri?.fsPath || '', uri.fsPath) === '') { belongingPackage!.children.delete(typeItem.id); } }); } else { for (const testType of testTypes) { // here we do not directly call synchronizeItemsRecursively() because testTypes here are just part of the // children of the belonging package, we don't want to delete other children unexpectedly. let testTypeItem: TestItem | undefined = belongingPackage.children.get(testType.id); if (!testTypeItem) { testTypeItem = createTestItem(testType, belongingPackage); testTypeItem.canResolveChildren = true; } else { updateTestItem(testTypeItem, testType); } tests.push(testTypeItem); synchronizeItemsRecursively(testTypeItem, testType.children); } } if (belongingPackage.children.size === 0) { belongingPackage.parent?.children.delete(belongingPackage.id); } return tests; } /** * Give a test item for a type, find its belonging package item according to its id. */ function findBelongingPackageItem(testType: IJavaTestItem): TestItem | undefined { const indexOfProjectSeparator: number = testType.id.indexOf('@'); if (indexOfProjectSeparator < 0) { return undefined; } const projectId: string = testType.id.substring(0, indexOfProjectSeparator); const projectItem: TestItem | undefined = testController?.items.get(projectId); if (!projectItem) { return undefined; } const indexOfPackageSeparator: number = testType.id.lastIndexOf('.'); const packageId: string = testType.id.substring(indexOfProjectSeparator + 1, indexOfPackageSeparator); const packageItem: TestItem | undefined = projectItem.children.get(`${projectId}@${packageId}`); return packageItem; } /** * Give a document uri, resolve its belonging package item. */ async function resolveBelongingPackage(uri: Uri): Promise<TestItem | undefined> { const pathsData: IJavaTestItem[] = await resolvePath(uri.toString()); if (_.isEmpty(pathsData) || pathsData.length < 2) { return undefined; } const projectData: IJavaTestItem = pathsData[0]; if (projectData.testLevel !== TestLevel.Project) { return undefined; } let belongingProject: TestItem | undefined = testController?.items.get(projectData.id); if (!belongingProject) { belongingProject = createTestItem(projectData); testController?.items.add(belongingProject); belongingProject.canResolveChildren = true; } const packageData: IJavaTestItem = pathsData[1]; if (packageData.testLevel !== TestLevel.Package) { return undefined; } let belongingPackage: TestItem | undefined = belongingProject.children.get(packageData.id); if (!belongingPackage) { belongingPackage = createTestItem(packageData, belongingProject); belongingPackage.canResolveChildren = true; } return belongingPackage; } /** * Parse the range object with server mode to client format * @param range range with server side format */ export function asRange(range: any): Range | undefined { if (!range) { return undefined; } return new Range(range.start.line, range.start.character, range.end.line, range.end.character); } export async function getJavaProjects(workspaceFolder: WorkspaceFolder, token?: CancellationToken): Promise<IJavaTestItem[]> { return await executeJavaLanguageServerCommand<IJavaTestItem[]>( JavaTestRunnerDelegateCommands.FIND_JAVA_PROJECTS, workspaceFolder.uri.toString(), token) || []; } export async function findTestPackagesAndTypes(handlerId: string, token?: CancellationToken): Promise<IJavaTestItem[]> { return await executeJavaLanguageServerCommand<IJavaTestItem[]>( JavaTestRunnerDelegateCommands.FIND_TEST_PACKAGES_AND_TYPES, handlerId, token) || []; } export async function findDirectTestChildrenForClass(handlerId: string, token?: CancellationToken): Promise<IJavaTestItem[]> { return await executeJavaLanguageServerCommand<IJavaTestItem[]>( JavaTestRunnerDelegateCommands.FIND_DIRECT_CHILDREN_FOR_CLASS, handlerId, token) || []; } export async function findTestTypesAndMethods(uri: string, token?: CancellationToken): Promise<IJavaTestItem[]> { return await executeJavaLanguageServerCommand<IJavaTestItem[]>( JavaTestRunnerDelegateCommands.FIND_TEST_TYPES_AND_METHODS, uri, token) || []; } export async function resolvePath(uri: string): Promise<IJavaTestItem[]> { return await executeJavaLanguageServerCommand<IJavaTestItem[]>( JavaTestRunnerDelegateCommands.RESOLVE_PATH, uri) || []; }
the_stack
import test, { Test } from "tape-promise/tape"; import { v4 as uuidv4 } from "uuid"; import { AddressInfo } from "net"; import express from "express"; import bodyParser from "body-parser"; import http from "http"; import { Server as SocketIoServer } from "socket.io"; import { DefaultApi as HtlcCoordinatorBesuApi, PluginFactoryHTLCCoordinatorBesu, IPluginHTLCCoordinatorBesuOptions, HtlcPackage, OwnHTLCRequest, CounterpartyHTLCRequest, Configuration, } from "../../../../main/typescript/public-api"; import { IPluginHtlcEthBesuErc20Options, PluginFactoryHtlcEthBesuErc20, } from "@hyperledger/cactus-plugin-htlc-eth-besu-erc20"; import { DefaultApi as BesuApi, EthContractInvocationType, PluginFactoryLedgerConnector, PluginLedgerConnectorBesu, Web3SigningCredentialType, Web3SigningCredential, } from "@hyperledger/cactus-plugin-ledger-connector-besu"; import { LogLevelDesc, IListenOptions, Servers, } from "@hyperledger/cactus-common"; import { PluginRegistry } from "@hyperledger/cactus-core"; import { Constants, PluginImportType } from "@hyperledger/cactus-core-api"; import { BesuTestLedger, pruneDockerAllIfGithubAction, } from "@hyperledger/cactus-test-tooling"; import { PluginKeychainMemory } from "@hyperledger/cactus-plugin-keychain-memory"; import HashTimeLockJSON from "@hyperledger/cactus-plugin-htlc-eth-besu-erc20/src/main/solidity/contracts/HashedTimeLockContract.json"; import TestTokenJSON from "@hyperledger/cactus-test-plugin-htlc-eth-besu-erc20/src/test/solidity/token-erc20-contract/Test_Token.json"; import DemoHelperJSON from "@hyperledger/cactus-test-plugin-htlc-eth-besu-erc20/src/test/solidity/token-erc20-contract/DemoHelpers.json"; const logLevel: LogLevelDesc = "INFO"; const estimatedGas = 6721975; const expiration = 2147483648; const receiver = "0x627306090abaB3A6e1400e9345bC60c78a8BEf57"; const hashLock = "0x3c335ba7f06a8b01d0596589f73c19069e21c81e5013b91f408165d1bf623d32"; const firstHighNetWorthAccount = "0x90F8bf6A479f320ead074411a4B0e7944Ea8c9C1"; const privateKey = "0x4f3edf983ac636a65a842ce7c78d9aa706d3b113bce9c46f30d7d21715b23b1d"; const connectorInstanceId = uuidv4(); const web3SigningCredential: Web3SigningCredential = { ethAccount: firstHighNetWorthAccount, secret: privateKey, type: Web3SigningCredentialType.PrivateKeyHex, } as Web3SigningCredential; const contractAddress = "0xCfEB869F69431e42cdB54A4F4f105C19C080A601"; const testCase = "Test own htlc endpoint"; test("BEFORE " + testCase, async (t: Test) => { const pruning = pruneDockerAllIfGithubAction({ logLevel }); await t.doesNotReject(pruning, "Pruning did not throw OK"); t.end(); }); test(testCase, async (t: Test) => { t.comment("Starting Besu Test Ledger"); const besuTestLedger = new BesuTestLedger(); await besuTestLedger.start(); test.onFinish(async () => { await besuTestLedger.stop(); await besuTestLedger.destroy(); }); const rpcApiHttpHost = await besuTestLedger.getRpcApiHttpHost(); const rpcApiWsHost = await besuTestLedger.getRpcApiWsHost(); const keychainId = uuidv4(); const keychainPlugin = new PluginKeychainMemory({ instanceId: uuidv4(), keychainId, // pre-provision keychain with mock backend holding the private key of the // test account that we'll reference while sending requests with the // signing credential pointing to this keychain entry. backend: new Map([ [TestTokenJSON.contractName, JSON.stringify(TestTokenJSON)], ]), logLevel, }); keychainPlugin.set( DemoHelperJSON.contractName, JSON.stringify(DemoHelperJSON), ); keychainPlugin.set( HashTimeLockJSON.contractName, JSON.stringify(HashTimeLockJSON), ); const factory = new PluginFactoryLedgerConnector({ pluginImportType: PluginImportType.Local, }); const pluginRegistry = new PluginRegistry({}); const connector: PluginLedgerConnectorBesu = await factory.create({ rpcApiHttpHost, rpcApiWsHost, logLevel, instanceId: connectorInstanceId, pluginRegistry: new PluginRegistry({ plugins: [keychainPlugin] }), }); pluginRegistry.add(connector); const iPluginHtlcEthBesuErc20Options: IPluginHtlcEthBesuErc20Options = { instanceId: uuidv4(), keychainId: keychainId, pluginRegistry, }; const pluginFactoryHtlcEthBesuErc20 = new PluginFactoryHtlcEthBesuErc20({ pluginImportType: PluginImportType.Local, }); const pluginHtlcEthBesuErc20 = await pluginFactoryHtlcEthBesuErc20.create( iPluginHtlcEthBesuErc20Options, ); pluginRegistry.add(pluginHtlcEthBesuErc20); const pluginOptions: IPluginHTLCCoordinatorBesuOptions = { instanceId: uuidv4(), logLevel, pluginRegistry, }; const factoryHTLC = new PluginFactoryHTLCCoordinatorBesu({ pluginImportType: PluginImportType.Local, }); const pluginHTLCCoordinatorBesu = await factoryHTLC.create(pluginOptions); pluginRegistry.add(pluginHTLCCoordinatorBesu); const expressApp = express(); expressApp.use(bodyParser.json({ limit: "250mb" })); const server = http.createServer(expressApp); const listenOptions: IListenOptions = { hostname: "0.0.0.0", port: 0, server, }; const addressInfo = (await Servers.listen(listenOptions)) as AddressInfo; test.onFinish(async () => await Servers.shutdown(server)); const { address, port } = addressInfo; const apiHost = `http://${address}:${port}`; const configuration = new Configuration({ basePath: apiHost }); const htlcCoordinatorBesuApiClient = new HtlcCoordinatorBesuApi( configuration, ); await pluginHTLCCoordinatorBesu.getOrCreateWebServices(); await pluginHTLCCoordinatorBesu.registerWebServices(expressApp); const besuWsApi = new SocketIoServer(server, { path: Constants.SocketIoConnectionPathV1, }); const besuConnectorConfiguration = new Configuration({ basePath: apiHost }); const besuConnectorApi = new BesuApi(besuConnectorConfiguration); await connector.getOrCreateWebServices(); await connector.registerWebServices(expressApp, besuWsApi as any); t.comment("Deploys TestToken via .json file on deployContract function"); const deployOutToken = await connector.deployContract({ contractName: TestTokenJSON.contractName, contractAbi: TestTokenJSON.abi, bytecode: TestTokenJSON.bytecode, web3SigningCredential, keychainId, constructorArgs: ["100", "token", "2", "TKN"], gas: estimatedGas, }); t.ok(deployOutToken, "deployContract() output is truthy OK"); t.ok( deployOutToken.transactionReceipt, "deployContract() output.transactionReceipt is truthy OK", ); t.ok( deployOutToken.transactionReceipt.contractAddress, "deployContract() output.transactionReceipt.contractAddress is truthy OK", ); const tokenAddress = deployOutToken.transactionReceipt .contractAddress as string; t.comment("Approve 10 Tokens to HashTimeLockAddress"); const approveTokensOutput = await besuConnectorApi.invokeContractV1({ contractName: TestTokenJSON.contractName, keychainId, signingCredential: web3SigningCredential, invocationType: EthContractInvocationType.Send, methodName: "approve", params: [contractAddress, "10"], gas: estimatedGas, }); t.equal( approveTokensOutput.data.success, true, "approve() transactionReceipt.status is true OK", ); t.comment("Get account balance"); const responseBalance = await besuConnectorApi.invokeContractV1({ contractName: TestTokenJSON.contractName, keychainId, signingCredential: web3SigningCredential, invocationType: EthContractInvocationType.Call, methodName: "balanceOf", params: [firstHighNetWorthAccount], }); t.equal( responseBalance.data.callOutput, "100", "balance of account is 100 OK", ); t.comment("Get HashTimeLock contract and account allowance"); const allowanceOutput = await besuConnectorApi.invokeContractV1({ contractName: TestTokenJSON.contractName, keychainId, signingCredential: web3SigningCredential, invocationType: EthContractInvocationType.Call, methodName: "allowance", params: [firstHighNetWorthAccount, contractAddress], }); t.equal(allowanceOutput.status, 200, "allowance status is 200 OK"); t.equal(allowanceOutput.data.callOutput, "10", "allowance amount is 10 OK"); t.comment("Create and initialize own HTLC"); const ownHTLCRequest: OwnHTLCRequest = { htlcPackage: HtlcPackage.BesuErc20, connectorInstanceId, keychainId, constructorArgs: [], web3SigningCredential, inputAmount: 10, outputAmount: 1, expiration, hashLock, tokenAddress, receiver, outputNetwork: "BTC", outputAddress: "1AcVYm7M3kkJQH28FXAvyBFQzFRL6xPKu8", gas: estimatedGas, }; const response = await htlcCoordinatorBesuApiClient.ownHtlcV1(ownHTLCRequest); t.equal(response.status, 200, "response status is 200 OK"); t.equal(response.data.success, true, "response success is true"); t.ok( response.data, "pluginHTLCCoordinatorBesu.ownHtlcV1() output is truthy OK", ); t.ok( response.data.out.transactionReceipt, "pluginHTLCCoordinatorBesu.ownHtlcV1() output.transactionReceipt is truthy OK", ); t.comment("Get HTLC id"); const responseTxId = await besuConnectorApi.invokeContractV1({ contractName: DemoHelperJSON.contractName, keychainId, signingCredential: web3SigningCredential, invocationType: EthContractInvocationType.Call, methodName: "getTxId", params: [ firstHighNetWorthAccount, receiver, 10, hashLock, expiration, tokenAddress, ], gas: estimatedGas, }); t.comment("Get counterparty HTLC"); const counterpartyHTLCRequest: CounterpartyHTLCRequest = { htlcPackage: HtlcPackage.BesuErc20, connectorInstanceId, keychainId, htlcId: responseTxId.data.callOutput, web3SigningCredential, gas: estimatedGas, }; const response2 = await htlcCoordinatorBesuApiClient.counterpartyHtlcV1( counterpartyHTLCRequest, ); t.equal(response2.status, 200, "response status is 200 OK"); t.equal(response2.data.success, true, "response success is true"); t.equal(response2.data.callOutput, "1", "the contract status is 1 - Active"); }); test("AFTER " + testCase, async (t: Test) => { const pruning = pruneDockerAllIfGithubAction({ logLevel }); await t.doesNotReject(pruning, "Pruning did not throw OK"); t.end(); });
the_stack
import { LokiEventEmitter } from "./event_emitter"; import { UniqueIndex } from "./unique_index"; import { ResultSet } from "./result_set"; import { DynamicView } from "./dynamic_view"; import { IRangedIndex } from "./ranged_indexes"; import { CloneMethod } from "./clone"; import { Doc, Dict } from "../../common/types"; import { FullTextSearch } from "../../full-text-search/src/full_text_search"; import { Analyzer } from "../../full-text-search/src/analyzer/analyzer"; /** * Collection class that handles documents of same type * @extends LokiEventEmitter * @param <TData> - the data type * @param <TNested> - nested properties of data type */ export declare class Collection<TData extends object = object, TNested extends object = object, T extends TData & TNested = TData & TNested> extends LokiEventEmitter { name: string; _data: Doc<T>[]; private _idIndex; _rangedIndexes: { [P in keyof T]?: Collection.RangedIndexMeta; }; _lokimap: { [$loki: number]: Doc<T>; }; _unindexedSortComparator: string; _defaultLokiOperatorPackage: string; /** * Unique constraints contain duplicate object references, so they are not persisted. * We will keep track of properties which have unique constraints applied here, and regenerate on load. */ _constraints: { unique: { [P in keyof T]?: UniqueIndex; }; }; /** * Transforms will be used to store frequently used query chains as a series of steps which itself can be stored along * with the database. */ _transforms: Dict<Collection.Transform<T>[]>; /** * In autosave scenarios we will use collection level dirty flags to determine whether save is needed. * currently, if any collection is dirty we will autosave the whole database if autosave is configured. * Defaulting to true since this is called from addCollection and adding a collection should trigger save. */ _dirty: boolean; private _cached; /** * Is collection transactional. */ private _transactional; /** * Options to clone objects when inserting them. */ _cloneObjects: boolean; /** * Default clone method (if enabled) is parse-stringify. */ _cloneMethod: CloneMethod; /** * If set to true we will not maintain a meta property for a document. */ private _disableMeta; /** * Disable track changes. */ private _disableChangesApi; /** * Disable delta update object style on changes. */ _disableDeltaChangesApi: boolean; /** * By default, if you insert a document with a Date value for an indexed property, we will convert that value to number. */ private _serializableIndexes; /** * Name of path of used nested properties. */ private _nestedProperties; /** * Option to activate a cleaner daemon - clears "aged" documents at set intervals. */ _ttl: Collection.TTL; private _maxId; private _dynamicViews; /** * Changes are tracked by collection and aggregated by the db. */ private _changes; /** * stages: a map of uniquely identified 'stages', which hold copies of objects to be * manipulated without affecting the data in the original collection */ private _stages; private _commitLog; _fullTextSearch: FullTextSearch; /** * @param {string} name - collection name * @param {(object)} [options={}] - a configuration object * @param {string[]} [options.unique=[]] - array of property names to define unique constraints for * @param {string[]} [options.exact=[]] - array of property names to define exact constraints for * @param {RangedIndexOptions} [options.rangedIndexes] - configuration object for ranged indexes * @param {boolean} [options.asyncListeners=false] - whether listeners are invoked asynchronously * @param {boolean} [options.disableMeta=false] - set to true to disable meta property on documents * @param {boolean} [options.disableChangesApi=true] - set to false to enable Changes API * @param {boolean} [options.disableDeltaChangesApi=true] - set to false to enable Delta Changes API (requires Changes API, forces cloning) * @param {boolean} [options.clone=false] - specify whether inserts and queries clone to/from user * @param {boolean} [options.serializableIndexes=true] - converts date values on binary indexed property values are serializable * @param {string} [options.cloneMethod="deep"] - the clone method * @param {number} [options.transactional=false] - ? * @param {number} [options.ttl=] - age of document (in ms.) before document is considered aged/stale. * @param {number} [options.ttlInterval=] - time interval for clearing out 'aged' documents; not set by default * @param {string} [options.unindexedSortComparator="js"] "js", "abstract", "abstract-date", "loki" or other registered comparator name * @param {string} [options.defaultLokiOperatorPackage="js"] "js", "loki", "comparator" (or user defined) query ops package * @param {FullTextSearch.FieldOptions} [options.fullTextSearch=] - the full-text search options * @see {@link Loki#addCollection} for normal creation of collections */ constructor(name: string, options?: Collection.Options<TData, TNested>); toJSON(): Collection.Serialized; static fromJSONObject(obj: Collection.Serialized, options?: Collection.DeserializeOptions): Collection<any, object, any>; /** * Adds a named collection transform to the collection * @param {string} name - name to associate with transform * @param {array} transform - an array of transformation 'step' objects to save into the collection */ addTransform(name: string, transform: Collection.Transform<T>[]): void; /** * Retrieves a named transform from the collection. * @param {string} name - name of the transform to lookup. */ getTransform(name: string): Collection.Transform<T>[]; /** * Updates a named collection transform to the collection * @param {string} name - name to associate with transform * @param {object} transform - a transformation object to save into collection */ setTransform(name: string, transform: Collection.Transform<T>[]): void; /** * Removes a named collection transform from the collection * @param {string} name - name of collection transform to remove */ removeTransform(name: string): void; private setTTL(age, interval); /** * Create a row filter that covers all documents in the collection. */ _prepareFullDocIndex(): number[]; /** * Ensure rangedIndex of a field. * @param field * @param indexTypeName * @param comparatorName */ ensureIndex(field: string, indexTypeName?: string, comparatorName?: string): void; /** * Ensure rangedIndex of a field. * @param field Property to create an index on (need to look into contraining on keyof T) * @param indexTypeName Name of IndexType factory within (global?) hashmap to create IRangedIndex from * @param comparatorName Name of Comparator within (global?) hashmap */ ensureRangedIndex(field: string, indexTypeName?: string, comparatorName?: string): void; ensureUniqueIndex(field: keyof T): UniqueIndex; /** * Quickly determine number of documents in collection (or query) * @param {object} query - (optional) query object to count results of * @returns {number} number of documents in the collection */ count(query?: ResultSet.Query<Doc<T>>): number; /** * Rebuild idIndex */ private _ensureId(); /** * Add a dynamic view to the collection * @param {string} name - name of dynamic view to add * @param {object} options - (optional) options to configure dynamic view with * @param {boolean} [options.persistent=false] - indicates if view is to main internal results array in 'resultdata' * @param {string} [options.sortPriority=SortPriority.PASSIVE] - the sort priority * @param {number} options.minRebuildInterval - minimum rebuild interval (need clarification to docs here) * @returns {DynamicView} reference to the dynamic view added **/ addDynamicView(name: string, options?: DynamicView.Options): DynamicView<T>; /** * Remove a dynamic view from the collection * @param {string} name - name of dynamic view to remove **/ removeDynamicView(name: string): void; /** * Look up dynamic view reference from within the collection * @param {string} name - name of dynamic view to retrieve reference of * @returns {DynamicView} A reference to the dynamic view with that name **/ getDynamicView(name: string): DynamicView<T>; /** * Applies a 'mongo-like' find query object and passes all results to an update function. * @param {object} filterObject - the 'mongo-like' query object * @param {function} updateFunction - the update function */ findAndUpdate(filterObject: ResultSet.Query<Doc<T>>, updateFunction: (obj: Doc<T>) => any): void; /** * Applies a 'mongo-like' find query object removes all documents which match that filter. * @param {object} filterObject - 'mongo-like' query object */ findAndRemove(filterObject: ResultSet.Query<Doc<T>>): void; /** * Adds object(s) to collection, ensure object(s) have meta properties, clone it if necessary, etc. * @param {(object|array)} doc - the document (or array of documents) to be inserted * @returns {(object|array)} document or documents inserted */ insert(doc: TData): Doc<T>; insert(doc: TData[]): Doc<T>[]; /** * Adds a single object, ensures it has meta properties, clone it if necessary, etc. * @param {object} doc - the document to be inserted * @param {boolean} bulkInsert - quiet pre-insert and insert event emits * @returns {object} document or 'undefined' if there was a problem inserting it */ insertOne(doc: TData, bulkInsert?: boolean): Doc<T>; /** * Refers nested properties of an object to the root of it. * @param {T} data - the object * @returns {T & TNested} the object with nested properties * @hidden */ _defineNestedProperties<U extends TData>(data: U): U & TNested; /** * Empties the collection. * @param {boolean} [removeIndices=false] - remove indices */ clear({removeIndices: removeIndices}?: { removeIndices?: boolean; }): void; /** * Updates an object and notifies collection that the document has changed. * @param {object} doc - document to update within the collection */ update(doc: Doc<T> | Doc<T>[]): void; /** * Add object to collection */ private _add(obj); /** * Applies a filter function and passes all results to an update function. * @param {function} filterFunction - the filter function * @param {function} updateFunction - the update function */ updateWhere(filterFunction: (obj: Doc<T>) => boolean, updateFunction: (obj: Doc<T>) => Doc<T>): void; /** * Remove all documents matching supplied filter function. * @param {function} filterFunction - the filter function */ removeWhere(filterFunction: (obj: Doc<T>) => boolean): void; removeDataOnly(): void; /** * Remove a document from the collection * @param {number|object} doc - document to remove from collection */ remove(doc: number | Doc<T> | Doc<T>[]): void; /** * Returns all changes. * @returns {Collection.Change[]} */ getChanges(): Collection.Change[]; /** * Enables/disables changes api. * @param {boolean} disableChangesApi * @param {boolean} disableDeltaChangesApi */ setChangesApi(disableChangesApi: boolean, disableDeltaChangesApi?: boolean): void; /** * Clears all the changes. */ flushChanges(): void; private _getObjectDelta(oldObject, newObject); /** * Compare changed object (which is a forced clone) with existing object and return the delta */ private _getChangeDelta(obj, old); /** * Creates a clone of the current status of an object and associates operation and collection name, * so the parent db can aggregate and generate a changes object for the entire db */ private _createChange(name, op, obj, old?); private _createInsertChange(obj); private _createUpdateChange(obj, old); private _insertMetaWithChange(obj); private _updateMetaWithChange(obj, old); private _insertMeta(obj); private _updateMeta(obj); /** * Get by Id - faster than other methods because of the searching algorithm * @param {int} id - $loki id of document you want to retrieve * @param {boolean} returnPosition - if 'true' we will return [object, position] * @returns {(object|array|null)} Object reference if document was found, null if not, * or an array if 'returnPosition' was passed. */ get(id: number): Doc<T>; get(id: number, returnPosition: boolean): Doc<T> | [Doc<T>, number]; /** * Retrieve doc by Unique index * @param {string} field - name of uniquely indexed property to use when doing lookup * @param {any} value - unique value to search for * @returns {object} document matching the value passed */ by(field: keyof T, value: any): Doc<T>; /** * Find one object by index property, by property equal to value * @param {object} query - query object used to perform search with * @returns {(object|null)} First matching document, or null if none */ findOne(query: ResultSet.Query<Doc<T>>): Doc<T>; /** * Chain method, used for beginning a series of chained find() and/or view() operations * on a collection. * * @param {array} transform - Ordered array of transform step objects similar to chain * @param {object} parameters - Object containing properties representing parameters to substitute * @returns {ResultSet} (this) ResultSet, or data array if any map or join functions where called */ chain(transform?: string | Collection.Transform<T>[], parameters?: object): ResultSet<T>; /** * Find method, api is similar to mongodb. * for more complex queries use [chain()]{@link Collection#chain} or [where()]{@link Collection#where}. * @example {@tutorial Query Examples} * @param {object} query - 'mongo-like' query object * @returns {array} Array of matching documents */ find(query?: ResultSet.Query<Doc<T>>): Doc<T>[]; /** * Find object by unindexed field by property equal to value, * simply iterates and returns the first element matching the query */ findOneUnindexed(prop: string, value: any): Doc<T>; /** * Transaction methods */ /** * start the transation */ startTransaction(): void; /** * Commit the transaction. */ commit(): void; /** * Rollback the transaction. */ rollback(): void; /** * Query the collection by supplying a javascript filter function. * @example * let results = coll.where(function(obj) { * return obj.legs === 8; * }); * @param {function} fun - filter function to run against all collection docs * @returns {array} all documents which pass your filter function */ where(fun: (obj: Doc<T>) => boolean): Doc<T>[]; /** * Map Reduce operation * @param {function} mapFunction - function to use as map function * @param {function} reduceFunction - function to use as reduce function * @returns {data} The result of your mapReduce operation */ mapReduce<U1, U2>(mapFunction: (value: Doc<T>, index: number, array: Doc<T>[]) => U1, reduceFunction: (array: U1[]) => U2): U2; /** * Join two collections on specified properties * @param {array} joinData - array of documents to 'join' to this collection * @param {string} leftJoinProp - property name in collection * @param {string} rightJoinProp - property name in joinData * @param {function} mapFun - (Optional) map function to use * @param dataOptions - options to data() before input to your map function * @param [dataOptions.removeMeta] - allows removing meta before calling mapFun * @param [dataOptions.forceClones] - forcing the return of cloned objects to your map object * @param [dataOptions.forceCloneMethod] - allows overriding the default or collection specified cloning method * @returns {ResultSet} Result of the mapping operation */ eqJoin(joinData: Collection<any> | ResultSet<any> | any[], leftJoinProp: string | ((obj: any) => string), rightJoinProp: string | ((obj: any) => string), mapFun?: (left: any, right: any) => any, dataOptions?: ResultSet.DataOptions): ResultSet<any>; /** * (Staging API) create a stage and/or retrieve it */ getStage(name: string): any; /** * a collection of objects recording the changes applied through a commmitStage */ /** * (Staging API) create a copy of an object and insert it into a stage */ stage<F extends TData>(stageName: string, obj: Doc<F>): F; /** * (Staging API) re-attach all objects to the original collection, so indexes and views can be rebuilt * then create a message to be inserted in the commitlog * @param {string} stageName - name of stage * @param {string} message */ commitStage(stageName: string, message: string): void; /** * Returns all values of a field. * @param {string} field - the field name * @return {any}: the array of values */ extract(field: keyof T): any[]; /** * Finds the minimum value of a field. * @param {string} field - the field name * @return {number} the minimum value */ min(field: keyof T): number; /** * Finds the maximum value of a field. * @param {string} field - the field name * @return {number} the maximum value */ max(field: keyof T): number; /** * Finds the minimum value and its index of a field. * @param {string} field - the field name * @return {object} - index and value */ minRecord(field: keyof T): { index: number; value: number; }; /** * Finds the maximum value and its index of a field. * @param {string} field - the field name * @return {object} - index and value */ maxRecord(field: keyof T): { index: number; value: number; }; /** * Returns all values of a field as numbers (if possible). * @param {string} field - the field name * @return {number[]} - the number array */ extractNumerical(field: keyof T): number[]; /** * Calculates the average numerical value of a field * @param {string} field - the field name * @returns {number} average of property in all docs in the collection */ avg(field: keyof T): number; /** * Calculate the standard deviation of a field. * @param {string} field - the field name * @return {number} the standard deviation */ stdDev(field: keyof T): number; /** * Calculates the mode of a field. * @param {string} field - the field name * @return {number} the mode */ mode(field: keyof T): number; /** * Calculates the median of a field. * @param {string} field - the field name * @return {number} the median */ median(field: keyof T): number; } export declare namespace Collection { interface Options<TData extends object, TNested extends object = {}, T extends object = TData & TNested> { unique?: (keyof T)[]; unindexedSortComparator?: string; defaultLokiOperatorPackage?: string; rangedIndexes?: RangedIndexOptions; serializableIndexes?: boolean; asyncListeners?: boolean; disableMeta?: boolean; disableChangesApi?: boolean; disableDeltaChangesApi?: boolean; clone?: boolean; serializableIndices?: boolean; cloneMethod?: CloneMethod; transactional?: boolean; ttl?: number; ttlInterval?: number; nestedProperties?: (keyof TNested | { name: keyof TNested; path: string[]; })[]; fullTextSearch?: FullTextSearch.FieldOptions[]; } interface RangedIndexOptions { [prop: string]: RangedIndexMeta; } interface DeserializeOptions { retainDirtyFlags?: boolean; fullTextSearch?: Dict<Analyzer>; [collName: string]: any | { proto?: any; inflate?: (src: object, dest?: object) => void; }; } interface BinaryIndex { dirty: boolean; values: any; } interface RangedIndexMeta { index?: IRangedIndex<any>; indexTypeName?: string; comparatorName?: string; } interface Change { name: string; operation: string; obj: any; } interface Serialized { name: string; unindexedSortComparator: string; defaultLokiOperatorPackage: string; _dynamicViews: DynamicView[]; _nestedProperties: { name: string; path: string[]; }[]; uniqueNames: string[]; transforms: Dict<Transform[]>; rangedIndexes: RangedIndexOptions; _data: Doc<any>[]; idIndex: number[]; maxId: number; _dirty: boolean; transactional: boolean; asyncListeners: boolean; disableMeta: boolean; disableChangesApi: boolean; disableDeltaChangesApi: boolean; cloneObjects: boolean; cloneMethod: CloneMethod; changes: any; _fullTextSearch: FullTextSearch; } interface CheckIndexOptions { randomSampling?: boolean; randomSamplingFactor?: number; repair?: boolean; } type Transform<T extends object = object> = { type: "find"; value: ResultSet.Query<Doc<T>> | string; } | { type: "where"; value: ((obj: Doc<T>) => boolean) | string; } | { type: "simplesort"; property: keyof T; options?: boolean | ResultSet.SimpleSortOptions; } | { type: "compoundsort"; value: (keyof T | [keyof T, boolean])[]; } | { type: "sort"; value: (a: Doc<T>, b: Doc<T>) => number; } | { type: "sortByScoring"; desc?: boolean; } | { type: "limit"; value: number; } | { type: "offset"; value: number; } | { type: "map"; value: (obj: Doc<T>, index: number, array: Doc<T>[]) => any; dataOptions?: ResultSet.DataOptions; } | { type: "eqJoin"; joinData: Collection<any> | ResultSet<any>; leftJoinKey: string | ((obj: any) => string); rightJoinKey: string | ((obj: any) => string); mapFun?: (left: any, right: any) => any; dataOptions?: ResultSet.DataOptions; } | { type: "mapReduce"; mapFunction: (item: Doc<T>, index: number, array: Doc<T>[]) => any; reduceFunction: (array: any[]) => any; } | { type: "update"; value: (obj: Doc<T>) => any; } | { type: "remove"; }; interface TTL { age: number; ttlInterval: number; daemon: any; } }
the_stack
import { MinusCircleOutlined, QuestionCircleOutlined } from "@ant-design/icons"; import { AutoComplete, Button, Col, Divider, Form, Input, Modal, Row, Select, Tooltip } from "antd"; import React, { useEffect } from "react"; import { useState } from "react"; import { FormComponentProps } from "antd/lib/form"; import apis from "@/services"; import { SelectValue } from "antd/lib/select"; interface Props extends FormComponentProps { data: any; close: Function; save: Function; } const Save: React.FC<Props> = props => { const { form: { getFieldDecorator }, form } = props; const [bridgeConfigs, setBridgeConfigs] = useState<any>([]); const [accessConfig, setAccessConfig] = useState({}); const [productList, setProductList] = useState([]); const [protocolSupport, setProtocolSupport] = useState([]); const [productKeyList, setProductKeyList] = useState([]); const [deviceList, setDeviceList] = useState<any>([]); const [serveIdList, setServeIdList] = useState([]); const [regionIdList] = useState(['cn-qingdao', 'cn-beijing', 'cn-zhangjiakou', 'cn-huhehaote', 'cn-wulanchabu', 'cn-hangzhou', 'cn-shanghai', 'cn-shenzhen', 'cn-heyuan', 'cn-guangzhou', 'cn-chengdu']); useEffect(() => { setBridgeConfigs(props.data.bridgeConfigs || [ { serverId: "", bridgeProductKey: "", bridgeDeviceName: "", bridgeDeviceSecret: "", http2Endpoint: "" } ]); setAccessConfig(props.data?.accessConfig || { regionId: "", apiEndpoint: "", authEndpoint: "", accessKeyId: "", accessSecret: "", productKey: "" }); apis.aliyun.getNodesList().then(res => { if (res.status === 200) { setServeIdList(res.result) } }); apis.aliyun.productList({}).then(res => { if (res.status === 200) { setProductList(res.result) } }); apis.aliyun.protocolSupport().then(res => { if (res.status === 200) { setProtocolSupport(res.result) } }); if (props.data.accessConfig) { getBridge(props.data?.accessConfig); let item = props.data?.accessConfig; props.data.bridgeConfigs.map((i: any, index: number) => { let param = { regionId: item.regionId, accessSecret: item.accessSecret, apiEndpoint: item.apiEndpoint, authEndpoint: item.authEndpoint, accessKeyId: item.accessKeyId, productKey: i.bridgeProductKey }; apis.aliyun.getDevices(param).then(res => { if (res.status === 200) { deviceList[index] = res.result?.data || []; setDeviceList([...deviceList]) } }) }) } }, []); const saveData = () => { form.validateFields((err, fileValue) => { if (err) return; apis.aliyun.save(fileValue).then(res => { if (res.status === 200) { props.save(); } }) }) }; const getBridge = (params: any) => { if (params.regionId !== '' && params.accessSecret !== '' && params.apiEndpoint !== '' && params.authEndpoint !== '' && params.accessKeyId !== '') { let param = { regionId: params.regionId, accessSecret: params.accessSecret, apiEndpoint: params.apiEndpoint, authEndpoint: params.authEndpoint, accessKeyId: params.accessKeyId, }; apis.aliyun.getProducts(param).then(res => { if (res.status === 200) { setProductKeyList(res.result?.data || []) } }) } }; return ( <Modal width='60VW' title={props.data.id ? "编辑产品" : "添加产品"} visible okText="确定" cancelText="取消" onOk={() => { saveData() }} onCancel={() => props.close()} > <div> <Form layout="horizontal" labelCol={{ span: 6 }} wrapperCol={{ span: 18 }}> <Row justify="space-around" gutter={24}> <Col span={12}> <Form.Item label="产品ID" > {getFieldDecorator('id', { initialValue: props.data?.id, rules: [{ required: false, message: '请选择' }], })( <Select placeholder="请选择" allowClear> {productList && productList.map((i: any, index: number) => { return <Select.Option key={index} value={i.id}>{i.id}</Select.Option> })} </Select> )} </Form.Item> </Col> <Col span={12}> <Form.Item label="产品名称"> {getFieldDecorator('name', { initialValue: props.data?.name, rules: [{ required: true, message: '请输入名称' }], })(<Input placeholder="请输入名称" />)} </Form.Item> </Col> <Col span={12}> <Form.Item label="编解码协议"> {getFieldDecorator('codecProtocol', { initialValue: props.data?.codecProtocol, rules: [{ required: true, message: '请选择' }], })(<Select placeholder="请选择"> {protocolSupport && protocolSupport.map((i: any, index: number) => { return <Select.Option key={index} value={i.id}>{i.name}</Select.Option> })} </Select>)} </Form.Item> </Col> <Col span={12}> <Form.Item label="说明"> {getFieldDecorator('description', { initialValue: props.data?.description, rules: [{ required: false, message: '请输入' }], })(<Input placeholder="请输入" />)} </Form.Item> </Col> </Row> <Divider orientation="left" dashed><div style={{ fontWeight: 'bold' }}>认证信息配置</div></Divider> <Row justify="start" gutter={24}> <Col span={12}> <Form.Item label={ <span> 区域ID&nbsp; <Tooltip title="地域和可用区"> <QuestionCircleOutlined onClick={() => { window.open('https://help.aliyun.com/document_detail/40654.html') }} /> </Tooltip> </span> } > {getFieldDecorator('accessConfig.regionId', { initialValue: accessConfig?.regionId, rules: [{ required: true, message: '请选择' }], })( <AutoComplete placeholder="本地服务ID" dataSource={regionIdList} filterOption={(inputValue, option) => option?.props?.children?.toUpperCase()?.indexOf(inputValue.toUpperCase()) !== -1 } onBlur={(value) => { if (value) { let temp = form.getFieldValue('accessConfig.productKey'); form.setFieldsValue({ accessConfig: { apiEndpoint: `https://iot.${value}.aliyuncs.com`, authEndpoint: `https://iot-auth.${value}.aliyuncs.com/auth/bridge`, http2Endpoint: `https://${temp}.iot-as-http2.${value}.aliyuncs.com`, } }); let params = form.getFieldValue('accessConfig'); getBridge({ regionId: value, accessSecret: params.accessSecret, apiEndpoint: params.apiEndpoint, authEndpoint: params.authEndpoint, accessKeyId: params.accessKeyId, }) } }} > </AutoComplete> )} </Form.Item> </Col> <Col span={12}> <Form.Item label="API接口地址"> {getFieldDecorator('accessConfig.apiEndpoint', { //https://iot.cn-shanghai.aliyuncs.com initialValue: accessConfig?.apiEndpoint, rules: [{ required: true, message: '请输入' }], })(<Input placeholder="请输入" />)} </Form.Item> </Col> <Col span={12}> <Form.Item label="认证接口地址"> {getFieldDecorator('accessConfig.authEndpoint', { //https://iot-auth.cn-shanghai.aliyuncs.com/auth/bridge initialValue: accessConfig?.authEndpoint, rules: [{ required: true, message: '请输入' }], })(<Input placeholder="请输入" />)} </Form.Item> </Col> <Col span={12}> <Form.Item label="accessKey"> {getFieldDecorator('accessConfig.accessKeyId', { initialValue: accessConfig?.accessKeyId, rules: [{ required: true, message: '请输入' }], })(<Input placeholder="请输入" onBlur={(e) => { let params = form.getFieldValue('accessConfig'); getBridge({ regionId: params.regionId, accessSecret: params.accessSecret, apiEndpoint: params.apiEndpoint, authEndpoint: params.authEndpoint, accessKeyId: e.target.value, }) }} />)} </Form.Item> </Col> <Col span={12}> <Form.Item label="accessSecret"> {getFieldDecorator('accessConfig.accessSecret', { initialValue: accessConfig?.accessSecret, rules: [{ required: true, message: '请输入' }], })(<Input placeholder="请输入" onBlur={(e) => { let params = form.getFieldValue('accessConfig'); getBridge({ regionId: params.regionId, accessSecret: e.target.value, apiEndpoint: params.apiEndpoint, authEndpoint: params.authEndpoint, accessKeyId: params.accessKeyId, }) }} />)} </Form.Item> </Col> <Col span={12}> <Form.Item label="ProductKey"> {getFieldDecorator('accessConfig.productKey', { initialValue: accessConfig?.productKey, rules: [{ required: true, message: '请输入' }], })( <AutoComplete placeholder="请选择" allowClear> {productKeyList && productKeyList.map((i: any, index: number) => { return <AutoComplete.Option key={index} value={i.productKey}>{`${i.productKey}(${i.productName})`}</AutoComplete.Option> })} </AutoComplete> // <Select placeholder="请选择" allowClear> // {productKeyList && productKeyList.map((i: any, index: number) => { // return <Select.Option key={index} value={i.productKey}>{`${i.productKey}(${i.productName})`}</Select.Option> // })} // </Select> )} </Form.Item> </Col> </Row> <Divider orientation="left" dashed><div style={{ fontWeight: 'bold' }}>网桥配置</div></Divider> { bridgeConfigs.map((item: any, index: number) => { return ( <div key={index} style={{ backgroundColor: 'rgba(192,192,192,0.1)', marginBottom: '10px', paddingTop: '20px' }}> <div style={{ width: "90%", marginLeft: '5%' }}>网桥: {index + 1}</div> <div style={{ display: 'flex', justifyContent: 'center' }}> <div style={{ width: "90%" }}> <Row gutter={0} justify="start"> <Col span={12}> <Form.Item label="本地服务ID"> {getFieldDecorator(`bridgeConfigs[${index}].serverId`, { initialValue: item.serverId || undefined, rules: [{ required: true, message: '本地服务ID' }], })(<AutoComplete placeholder="本地服务ID"> {serveIdList && serveIdList.map((i: any, index: number) => { return <AutoComplete.Option key={index} value={i.id}>{i.id}</AutoComplete.Option> })} </AutoComplete>)} </Form.Item> </Col> <Col span={12}> <Form.Item label="ProductKey"> {getFieldDecorator(`bridgeConfigs[${index}].bridgeProductKey`, { initialValue: item.bridgeProductKey || undefined, rules: [{ required: true, message: '网桥ProductKey' }], })( <AutoComplete placeholder="请选择" allowClear onBlur={(value: SelectValue) => { let temp = form.getFieldValue('accessConfig.regionId'); let bridge = form.getFieldValue('bridgeConfigs'); bridge[index].http2Endpoint = `https://${value}.iot-as-http2.${temp}.aliyuncs.com`; form.setFieldsValue({ bridgeConfigs: bridge }); let config = form.getFieldValue('accessConfig'); if (config.regionId !== '' && config.apiEndpoint !== '' && config.authEndpoint !== '' && config.accessKeyId !== '' && config.accessSecret !== '' && value !== '') { apis.aliyun.getDevices({ regionId: config.regionId, accessSecret: config.accessSecret, apiEndpoint: config.apiEndpoint, productKey: value, authEndpoint: config.authEndpoint, accessKeyId: config.accessKeyId, }).then(res => { if (res.status === 200) { deviceList[index] = res.result?.data || []; setDeviceList([...deviceList]) } }) } }}> {productKeyList && productKeyList.map((i: any, index: number) => { return <AutoComplete.Option key={index} value={i.productKey}>{`${i.productKey}(${i.productName})`}</AutoComplete.Option> })} </AutoComplete> )} </Form.Item> </Col> <Col span={12}> <Form.Item label="DeviceName"> {getFieldDecorator(`bridgeConfigs[${index}].bridgeDeviceName`, { initialValue: item.bridgeDeviceName || undefined, rules: [{ required: true, message: '网桥DeviceName' }], })( <AutoComplete placeholder="网桥DeviceName" allowClear onBlur={(value: SelectValue) => { let secret = ''; if (value !== '' && value !== undefined) { let data: any[] = deviceList[index].filter((i: any) => { return i.deviceName === value }); if (data.length > 0) { secret = data[0].deviceSecret } } let bridge = form.getFieldValue('bridgeConfigs'); bridge[index].bridgeDeviceSecret = secret; form.setFieldsValue({ bridgeConfigs: bridge }) }}> {deviceList && deviceList.length > 0 && deviceList[index] && deviceList[index].length > 0 && deviceList[index].map((i: any, index: number) => { return <AutoComplete.Option key={index} value={i.deviceName}>{i.deviceName}</AutoComplete.Option> })} </AutoComplete> )} </Form.Item> </Col> <Col span={12}> <Form.Item label="DeviceSecret"> {getFieldDecorator(`bridgeConfigs[${index}].bridgeDeviceSecret`, { initialValue: item.bridgeDeviceSecret || undefined, rules: [{ required: true, message: '网桥DeviceSecret' }], })( <Input placeholder="请输入" readOnly /> )} </Form.Item> </Col> <Col span={12}> <Form.Item label="HTTP2接口地址"> {getFieldDecorator(`bridgeConfigs[${index}].http2Endpoint`, { //https://a1WEHOY5PU7.iot-as-http2.cn-shanghai.aliyuncs.com initialValue: item.http2Endpoint || undefined, rules: [{ required: true, message: '请输入' }], })(<Input placeholder="请输入" />)} </Form.Item> </Col> </Row> </div> <div style={{ width: "10%", display: 'flex', justifyContent: 'center', marginTop: '45px' }}> <Tooltip title="删除"> <MinusCircleOutlined onClick={() => { bridgeConfigs.splice(index, 1); setBridgeConfigs([...bridgeConfigs]); }} /> </Tooltip> </div> </div> </div> ) }) } <Button icon="plus" type="link" onClick={() => { setBridgeConfigs([...bridgeConfigs, { serverId: "", bridgeProductKey: "", bridgeDeviceName: "", bridgeDeviceSecret: "", http2Endpoint: "" }]); setDeviceList([...deviceList, {}]) }} >添加</Button> </Form> </div> </Modal> ) }; export default Form.create<Props>()(Save);
the_stack
import { TFolder, SliderComponent, normalizePath, PluginSettingTab, App, Setting, debounce, } from "obsidian"; import IW from "../main"; import { FileSuggest, FolderSuggest } from "./file-suggest"; import { LogTo } from "src/logger"; import { NaturalDateSuggest } from "./date-suggest"; export class IWSettingsTab extends PluginSettingTab { plugin: IW; inputPriorityMin: SliderComponent; inputPriorityMax: SliderComponent; constructor(app: App, plugin: IW) { super(app, plugin); this.plugin = plugin; } display(): void { const { containerEl } = this; const settings = this.plugin.settings; containerEl.empty(); containerEl.createEl("h3", { text: "Incremental Writing Settings" }); // // Queue Folder new Setting(containerEl) .setName("Queue Folder") .setDesc( "The path to the folder where new incremental writing queues should be created. Relative to the vault root." ) .addText((text) => { text.setPlaceholder("Example: folder1/folder2"); new FolderSuggest(this.app, text.inputEl); text.setValue(String(settings.queueFolderPath)).onChange((value) => { settings.queueFolderPath = normalizePath(String(value)); this.plugin.saveData(settings); }); }); // // Default Queue new Setting(containerEl) .setName("Default Queue") .setDesc( "The name of the default incremental writing queue file. Relative to the queue folder." ) .addText((text) => { new FileSuggest( this.plugin, text.inputEl, () => this.app.vault.getAbstractFileByPath( settings.queueFolderPath ) as TFolder ); text.setPlaceholder("Example: queue.md"); text.setValue(String(settings.queueFileName)).onChange((value) => { let str = String(value); if (!str) return; let file = normalizePath(String(value)); if (!file.endsWith(".md")) file += ".md"; settings.queueFileName = file; this.plugin.saveData(settings); }); }); // // Default Queue Type new Setting(containerEl) .setName("Default Scheduler") .setDesc("The default scheduler to use for newly created queues.") .addDropdown((comp) => { comp.addOption("afactor", "A-Factor Scheduler"); comp.addOption("simple", "Simple Scheduler"); comp.setValue(String(settings.defaultQueueType)).onChange((value) => { settings.defaultQueueType = String(value); this.plugin.saveData(settings); }); }); const nldates = (<any>this.plugin.app).plugins.getPlugin( "nldates-obsidian" ); const hasNlDates = nldates != null; // // Dropdown Dates new Setting(containerEl) .setName("Dropdown Date List") .setDesc( "Sets the default list of dropdown dates that show up in modals so you can quickly set repetition dates." ) .addTextArea((comp) => { comp.setPlaceholder("Example:\ntoday\ntomorrow\nnext week"); const currentValue = Object.keys( this.plugin.settings.dropdownNaturalDates ).join("\n"); comp.setValue(currentValue).onChange( debounce( (value) => { if (hasNlDates) { const inputDates = String(value) ?.split(/\r?\n/) ?.map((str) => [str, nldates.parseDate(str)]) || []; if (!inputDates || inputDates.length === 0) { LogTo.Debug("User inputted dates were null or empty"); settings.dropdownNaturalDates = {}; this.plugin.saveData(settings); return; } const validDates: string[] = inputDates .filter( ([_, date]: [string, any]) => date != null && date.date ) .map(([s, _]: [string, Date]) => s); if (inputDates.length !== validDates.length) { LogTo.Debug( `Ignoring ${ inputDates.length - validDates.length } invalid natural language date strings.` ); } const dateOptionsRecord: Record< string, string > = validDates.reduce((acc, x) => { acc[x] = x; return acc; }, {} as Record<string, string>); LogTo.Debug( "Setting dropdown date options to " + JSON.stringify(dateOptionsRecord) ); settings.dropdownNaturalDates = dateOptionsRecord; this.plugin.saveData(settings); } }, 500, true ) ); }); // // First Rep Date new Setting(containerEl) .setName("Default First Rep Date") .setDesc( "Sets the default first repetition date for new repetitions. Example: today, tomorrow, next week. **Requires that you have installed the Natural Language Dates plugin.**" ) .addText((comp) => { new NaturalDateSuggest(this.plugin, comp.inputEl); comp .setValue(String(settings.defaultFirstRepDate)) .setPlaceholder("1970-01-01") .onChange( debounce( (value) => { if (hasNlDates) { const dateString = String(value); const date = nldates.parseDate(dateString); if (date && date.date) { LogTo.Debug( "Setting default first rep date to " + dateString ); settings.defaultFirstRepDate = dateString; this.plugin.saveData(settings); } else { LogTo.Debug("Invalid natural language date string."); } } }, 500, true ) ); }); // // Ask for next repetition date new Setting(containerEl) .setName("Ask for Next Repetition Date?") .setDesc( "Do you want to be asked to give the next repetition date when you execute the next repetition command?" ) .addToggle((comp) => { comp.setValue(Boolean(settings.askForNextRepDate)).onChange((value) => { settings.askForNextRepDate = Boolean(value); this.plugin.saveData(settings); }); }); // // Queue Tags new Setting(containerEl) .setName("Queue Tags") .setDesc( "Mapping from queue names to tags. Tagging a note with these tags will add it to the corresponding queue." ) .addTextArea((textArea) => { textArea.setPlaceholder( "Example:\nIW-Queue=iw,writing\nTasks=tasks,todo" ); const currentValue = Object.entries(settings.queueTagMap) .map( ([queue, tags]: [string, string[]]) => `${queue}=${tags.join(",")}` ) .join("\n"); textArea.setValue(currentValue).onChange((value) => { const str = String(value).trim(); if (!str) { LogTo.Debug("Setting the queue tag map to empty."); settings.queueTagMap = {}; this.plugin.saveData(settings); return; } else if ( !str.split(/\r?\n/).every((line) => line.match(/(.+)=(.+,?)+/)) ) { LogTo.Debug("Invalid queue tag map. Not saving."); return; } const isEmpty = (s: string | any[]) => !s || s.length === 0; const split: [string, string[]][] = str .split(/\r?\n/) .map((line) => line.split("=")) .map(([queue, tags]: [string, string]) => [ queue, tags .split(",") .map((s) => s.trim()) .filter((s) => !isEmpty(s)), ]); let queueTagMap: Record<string, string[]> = {}; for (let [queue, tags] of split) { if (!isEmpty(queue) && !isEmpty(tags)) queueTagMap[queue] = tags; } settings.queueTagMap = queueTagMap; LogTo.Debug( "Updating queue tag map to: " + JSON.stringify(queueTagMap) ); this.plugin.saveData(settings); }); }); // // Skip New Note Dialog // new Setting(containerEl) // .setName("Skip Add Note Dialog?") // .setDesc("Skip the add note dialog and use the defaults?") // .addToggle((comp) => { // comp.setValue(Boolean(settings.skipAddNoteWindow)).onChange((value) => { // settings.skipAddNoteWindow = Boolean(value); // this.plugin.saveData(settings); // }) // }) // // Priority // Min new Setting(containerEl) .setName("Default Minimum Priority") .setDesc("Default minimum priority for new repetitions.") .addSlider((comp) => { this.inputPriorityMin = comp; comp.setDynamicTooltip(); comp.setValue(Number(settings.defaultPriorityMin)).onChange((value) => { if (this.inputPriorityMax) { let num = Number(value); if (!num.isValidPriority()) { return; } if (num > this.inputPriorityMax.getValue()) { this.inputPriorityMax.setValue(num); } settings.defaultPriorityMin = num; this.plugin.saveData(settings); } }); }); // Max new Setting(containerEl) .setName("Default Maximum Priority") .setDesc("Default maximum priority for new repetitions.") .addSlider((comp) => { this.inputPriorityMax = comp; comp.setDynamicTooltip(); comp.setValue(Number(settings.defaultPriorityMax)).onChange((value) => { if (this.inputPriorityMin) { let num = Number(value); if (!num.isValidPriority()) { return; } if (num < this.inputPriorityMin.getValue()) { this.inputPriorityMin.setValue(num); } settings.defaultPriorityMax = num; this.plugin.saveData(settings); } }); }); // Auto add new Setting(containerEl) .setName("Auto Add New Notes?") .setDesc("Automatically add new notes to the default queue?") .addToggle((comp) => { comp.setValue(settings.autoAddNewNotes).onChange((value) => { settings.autoAddNewNotes = value; this.plugin.saveData(settings); this.plugin.autoAddNewNotesOnCreate(); }); }); } }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { Automations } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { SecurityCenter } from "../securityCenter"; import { Automation, AutomationsListNextOptionalParams, AutomationsListOptionalParams, AutomationsListByResourceGroupNextOptionalParams, AutomationsListByResourceGroupOptionalParams, AutomationsListResponse, AutomationsListByResourceGroupResponse, AutomationsGetOptionalParams, AutomationsGetResponse, AutomationsCreateOrUpdateOptionalParams, AutomationsCreateOrUpdateResponse, AutomationsDeleteOptionalParams, AutomationsValidateOptionalParams, AutomationsValidateResponse, AutomationsListNextResponse, AutomationsListByResourceGroupNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing Automations operations. */ export class AutomationsImpl implements Automations { private readonly client: SecurityCenter; /** * Initialize a new instance of the class Automations class. * @param client Reference to the service client */ constructor(client: SecurityCenter) { this.client = client; } /** * Lists all the security automations in the specified subscription. Use the 'nextLink' property in the * response to get the next page of security automations for the specified subscription. * @param options The options parameters. */ public list( options?: AutomationsListOptionalParams ): PagedAsyncIterableIterator<Automation> { const iter = this.listPagingAll(options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(options); } }; } private async *listPagingPage( options?: AutomationsListOptionalParams ): AsyncIterableIterator<Automation[]> { let result = await this._list(options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext(continuationToken, options); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( options?: AutomationsListOptionalParams ): AsyncIterableIterator<Automation> { for await (const page of this.listPagingPage(options)) { yield* page; } } /** * Lists all the security automations in the specified resource group. Use the 'nextLink' property in * the response to get the next page of security automations for the specified resource group. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param options The options parameters. */ public listByResourceGroup( resourceGroupName: string, options?: AutomationsListByResourceGroupOptionalParams ): PagedAsyncIterableIterator<Automation> { const iter = this.listByResourceGroupPagingAll(resourceGroupName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByResourceGroupPagingPage(resourceGroupName, options); } }; } private async *listByResourceGroupPagingPage( resourceGroupName: string, options?: AutomationsListByResourceGroupOptionalParams ): AsyncIterableIterator<Automation[]> { let result = await this._listByResourceGroup(resourceGroupName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByResourceGroupNext( resourceGroupName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByResourceGroupPagingAll( resourceGroupName: string, options?: AutomationsListByResourceGroupOptionalParams ): AsyncIterableIterator<Automation> { for await (const page of this.listByResourceGroupPagingPage( resourceGroupName, options )) { yield* page; } } /** * Lists all the security automations in the specified subscription. Use the 'nextLink' property in the * response to get the next page of security automations for the specified subscription. * @param options The options parameters. */ private _list( options?: AutomationsListOptionalParams ): Promise<AutomationsListResponse> { return this.client.sendOperationRequest({ options }, listOperationSpec); } /** * Lists all the security automations in the specified resource group. Use the 'nextLink' property in * the response to get the next page of security automations for the specified resource group. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param options The options parameters. */ private _listByResourceGroup( resourceGroupName: string, options?: AutomationsListByResourceGroupOptionalParams ): Promise<AutomationsListByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listByResourceGroupOperationSpec ); } /** * Retrieves information about the model of a security automation. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param automationName The security automation name. * @param options The options parameters. */ get( resourceGroupName: string, automationName: string, options?: AutomationsGetOptionalParams ): Promise<AutomationsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, automationName, options }, getOperationSpec ); } /** * Creates or updates a security automation. If a security automation is already created and a * subsequent request is issued for the same automation id, then it will be updated. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param automationName The security automation name. * @param automation The security automation resource * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, automationName: string, automation: Automation, options?: AutomationsCreateOrUpdateOptionalParams ): Promise<AutomationsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, automationName, automation, options }, createOrUpdateOperationSpec ); } /** * Deletes a security automation. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param automationName The security automation name. * @param options The options parameters. */ delete( resourceGroupName: string, automationName: string, options?: AutomationsDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, automationName, options }, deleteOperationSpec ); } /** * Validates the security automation model before create or update. Any validation errors are returned * to the client. * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param automationName The security automation name. * @param automation The security automation resource * @param options The options parameters. */ validate( resourceGroupName: string, automationName: string, automation: Automation, options?: AutomationsValidateOptionalParams ): Promise<AutomationsValidateResponse> { return this.client.sendOperationRequest( { resourceGroupName, automationName, automation, options }, validateOperationSpec ); } /** * ListNext * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( nextLink: string, options?: AutomationsListNextOptionalParams ): Promise<AutomationsListNextResponse> { return this.client.sendOperationRequest( { nextLink, options }, listNextOperationSpec ); } /** * ListByResourceGroupNext * @param resourceGroupName The name of the resource group within the user's subscription. The name is * case insensitive. * @param nextLink The nextLink from the previous successful call to the ListByResourceGroup method. * @param options The options parameters. */ private _listByResourceGroupNext( resourceGroupName: string, nextLink: string, options?: AutomationsListByResourceGroupNextOptionalParams ): Promise<AutomationsListByResourceGroupNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, nextLink, options }, listByResourceGroupNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/providers/Microsoft.Security/automations", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AutomationList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion8], urlParameters: [Parameters.$host, Parameters.subscriptionId], headerParameters: [Parameters.accept], serializer }; const listByResourceGroupOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/automations", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AutomationList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion8], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/automations/{automationName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.Automation }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion8], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.automationName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/automations/{automationName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.Automation }, 201: { bodyMapper: Mappers.Automation }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.automation, queryParameters: [Parameters.apiVersion8], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.automationName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/automations/{automationName}", httpMethod: "DELETE", responses: { 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion8], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.automationName ], headerParameters: [Parameters.accept], serializer }; const validateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Security/automations/{automationName}/validate", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.AutomationValidationStatus }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.automation, queryParameters: [Parameters.apiVersion8], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.automationName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AutomationList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion8], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer }; const listByResourceGroupNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.AutomationList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion8], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer };
the_stack
import chitu = require('chitu'); import move = require('move'); class ScrollViewNode { private _scrollView: chitu.ScrollView; above: ScrollViewNode; below: ScrollViewNode; left: ScrollViewNode; right: ScrollViewNode; constructor(scrollView: chitu.ScrollView) { this._scrollView = scrollView; } get scrollView(): chitu.ScrollView { return this._scrollView; } } type Offset = { pullUp: number, pullDown: number, panLeft: number, panRight: number }; type Direction = 'left' | 'right' | 'up' | 'down' | 'none'; /** 通用手势切换 ScrollView */ class ScrollViewGesture { private active_item: chitu.ScrollView; private next_item: chitu.ScrollView; private prev_item: chitu.ScrollView; private above_item: chitu.ScrollView; private below_item: chitu.ScrollView; private scroll_args: chitu.ScrollArguments; private active_item_pos_x: number = 0; private active_item_pos_y: number = 0; private next_item_pos: number; private prev_item_pos: number; private container_width: number; private container_height: number; private moveType: 'none' | 'horizontal' | 'vertical' = 'none'; private _offset: Offset; /** 下拉执行 */ pullDownExecute: () => JQueryPromise<any> | void; /** 上拉执行 */ pullUpExecute: () => JQueryPromise<any> | void; /** 左拖动执行 */ panLeftExecute: () => JQueryPromise<any> | void; /** 右拖动执行 */ panRightExecute: () => JQueryPromise<any> | void; /** 上拉、下拉、或左右拖动释放时调用 * @returns 返回 true 时,执行操作,false 不执行。 */ on_release: (deltaX: number, deltaY: number) => boolean; /** 滚动视图改变时调用 */ viewChanged = chitu.Callbacks<ScrollViewGesture, { view: chitu.ScrollView, prev: chitu.ScrollView, direction: Direction }>(); constructor(scroll_view: chitu.ScrollView) { if (scroll_view == null) throw chitu.Errors.argumentNull('scroll_view'); scroll_view.load.add((sender: chitu.ScrollView, args) => this.on_scrollViewLoad(sender, args)); this.set_activeItem(scroll_view, 'none'); this._offset = { pullUp: -100, pullDown: 100, panLeft: -100, panRight: 100 } this.on_release = (deltaX: number, deltaY: number) => { let allowExecute = (deltaX < 0 && deltaX < this.offset.panLeft) || (deltaX > 0 && deltaX > this.offset.panRight) || (deltaY < 0 && deltaY < this.offset.pullUp) || (deltaY > 0 && deltaY > this.offset.pullDown); return allowExecute; }; this.pullDownExecute = () => { move(this.active_item.element).y(this.container_height).end(); move(this.above_item.element).y(0).end(); this.set_activeItem(this.above_item, 'down'); }; this.pullUpExecute = () => { move(this.active_item.element).y(0 - this.container_height).end(); move(this.below_item.element).y(0).end(); this.set_activeItem(this.below_item, 'up'); }; this.panLeftExecute = () => { move(this.active_item.element).x(this.prev_item_pos).end(); move(this.next_item.element).x(this.active_item_pos_x).end(); this.set_activeItem(this.next_item, 'left'); }; this.panRightExecute = () => { move(this.active_item.element).x(this.next_item_pos).end(); move(this.prev_item.element).x(this.active_item_pos_x).end(); this.set_activeItem(this.prev_item, 'right'); }; } showView(displayView: chitu.ScrollView, direction: Direction) { if (!displayView) throw chitu.Errors.argumentNull('displayView'); displayView.visible = true; if (direction == 'left') { move(displayView.element).x(this.next_item_pos).y(0).duration(0).end(); move(this.active_item.element).x(this.prev_item_pos).end(this.panLeftExecute); move(displayView.element).x(0).end(); } else if (direction == 'right') { move(displayView.element).x(this.prev_item_pos).y(0).duration(0).end(); move(this.active_item.element).x(this.next_item_pos).end(this.panRightExecute); move(displayView.element).x(0).end(); } else if (direction == 'up') { move(displayView.element).to(0, this.container_height).duration(0).end(); move(this.active_item.element).to(0, 0 - this.container_height).end(this.pullUpExecute); move(displayView.element).to(0, 0).end(); } else if (direction == 'down') { move(displayView.element).to(0, 0 - this.container_height).duration(0).end(); move(this.active_item.element).to(0, this.container_height).end(this.pullDownExecute); move(displayView.element).to(0, 0).end(); } } get offset(): Offset { return this._offset; } private on_scrollViewLoad(sender: chitu.ScrollView, args) { let page_container = (<chitu.Page>sender.parent).container; $(page_container.element).data('ScrollViewGesture', this); this.container_width = $(page_container.element).width(); this.container_height = $(page_container.element).height(); this.offset.panLeft = 0 - this.container_width / 2; this.offset.panRight = this.container_width / 2; this.next_item_pos = this.container_width; this.prev_item_pos = 0 - this.container_width; var pan = page_container.gesture.createPan(); pan.start = $.proxy(this.on_panStart, this); pan.left = $.proxy(this.on_panLeft, this); pan.right = $.proxy(this.on_panRight, this); pan.end = $.proxy(this.on_panEnd, this); } private on_panStart(e: Hammer.PanEvent) { let $active_item = $(this.active_item.element); //================================================== // 说明:计算角度,超过了水平滑动角度,则认为不是水平滑动。 let d = Math.atan(Math.abs(e.deltaY / e.deltaX)) / 3.14159265 * 180; if (d > 20 && d < 70) return false; //================================================== if ((e.direction & Hammer.DIRECTION_LEFT) == Hammer.DIRECTION_LEFT || (e.direction & Hammer.DIRECTION_RIGHT) == Hammer.DIRECTION_RIGHT) this.moveType = "horizontal"; else if ((e.direction & Hammer.DIRECTION_UP) == Hammer.DIRECTION_UP || (e.direction & Hammer.DIRECTION_DOWN) == Hammer.DIRECTION_DOWN) this.moveType = "vertical"; let started: boolean = (this.next_item != null && (e.direction & Hammer.DIRECTION_LEFT) == Hammer.DIRECTION_LEFT) || (this.prev_item != null && (e.direction & Hammer.DIRECTION_RIGHT) == Hammer.DIRECTION_RIGHT) || (this.below_item != null && (e.direction & Hammer.DIRECTION_UP) == Hammer.DIRECTION_UP) || (this.above_item != null && (e.direction & Hammer.DIRECTION_DOWN) == Hammer.DIRECTION_DOWN); if ((this.next_item != null && (e.direction & Hammer.DIRECTION_LEFT) == Hammer.DIRECTION_LEFT)) this.next_item.visible = true; if (this.prev_item != null && (e.direction & Hammer.DIRECTION_RIGHT) == Hammer.DIRECTION_RIGHT) this.prev_item.visible = true; if (this.below_item != null && (e.direction & Hammer.DIRECTION_UP) == Hammer.DIRECTION_UP) this.below_item.visible = true; if (this.above_item != null && (e.direction & Hammer.DIRECTION_DOWN) == Hammer.DIRECTION_DOWN) this.above_item.visible = true; return started; } private on_panLeft(e: Hammer.PanEvent) { if (this.moveType != "horizontal") return; let distanceX = this.ease(e.deltaX); move(this.active_item.element).x(this.active_item_pos_x + distanceX).duration(0).end(); if (this.next_item != null) move(this.next_item.element).x(this.next_item_pos + distanceX).duration(0).end(); if (this.prev_item != null) move(this.prev_item.element).x(this.prev_item_pos + distanceX).duration(0).end(); } private on_panRight(e: Hammer.PanEvent) { if (this.moveType != "horizontal") return; let distanceX = this.ease(e.deltaX); move(this.active_item.element).x(this.active_item_pos_x + distanceX).duration(0).end(); if (this.next_item != null) move(this.next_item.element).x(this.next_item_pos + distanceX).duration(0).end(); if (this.prev_item != null) move(this.prev_item.element).x(this.prev_item_pos + distanceX).duration(0).end(); } private on_panEnd(e: Hammer.PanEvent) { if (this.moveType == "horizontal") { let distanceX = this.ease(e.deltaX); this.processHorizontalMove(distanceX); } else if (this.moveType == "vertical" && this.scroll_args != null) { let deltaY: number; if (e.deltaY < 0) deltaY = (this.scroll_args.scrollTop + this.scroll_args.scrollHeight) - this.scroll_args.clientHeight; else deltaY = this.scroll_args.scrollTop; this.processVerticalMove(deltaY); } } private ease(x: number): number { let X_SCALE = 1.3; let distanceX = x * X_SCALE; return distanceX; } private processVerticalMove(deltaY: number) { let cancel = this.on_release(0, deltaY) == false; if (cancel) { return; } if (deltaY < 0 && this.below_item != null) { this.pullUpExecute(); } else if (deltaY > 0 && this.above_item != null) { this.pullDownExecute(); } } private processHorizontalMove(distanceX: number) { let cancel = this.on_release(distanceX, 0) == false; if (cancel) { move(this.active_item.element).x(this.active_item_pos_x).end(); if (this.next_item != null) move(this.next_item.element).x(this.next_item_pos).end(); if (this.prev_item != null) move(this.prev_item.element).x(this.prev_item_pos).end(); return; } if (distanceX < 0 && this.next_item != null && this.panLeftExecute != null) { // 向左移动 this.panLeftExecute(); } else if (distanceX > 0 && this.prev_item != null && this.panRightExecute != null) { // 向右移动 this.panRightExecute(); } } private on_scroll(sender: chitu.ScrollView, args: chitu.ScrollArguments) { var self = <ScrollViewGesture>$((<chitu.Page>sender.parent).container.element).data('ScrollViewGesture'); self.scroll_args = args; } private set_activeItem(active_item: chitu.ScrollView, direction: Direction) { if (active_item == null) throw chitu.Errors.argumentNull('active_item'); let prev_view = this.active_item; if (this.active_item != null) { this.active_item.scroll.remove(this.on_scroll); } this.active_item = active_item; this.active_item.scroll.add(this.on_scroll); chitu.fireCallback(this.viewChanged, this, { view: active_item, prev: prev_view, direction: direction }); var pos = $(this.active_item.element).position(); this.next_item_pos = this.container_width; this.prev_item_pos = 0 - this.next_item_pos; let $active_item = $(active_item.element); let next_name = $active_item.attr('next'); let prev_name = $active_item.attr('prev'); let above_name = $active_item.attr('above'); let below_name = $active_item.attr('below'); let page = <chitu.Page>active_item.parent; if (next_name) { this.next_item = page.findControl<chitu.ScrollView>(next_name); if (this.next_item == null) throw Errors.controlNotExists(next_name); } else { this.next_item = null; } if (prev_name) { this.prev_item = page.findControl<chitu.ScrollView>(prev_name); if (this.prev_item == null) throw Errors.controlNotExists(prev_name); } else { this.prev_item = null; } if (above_name) { this.above_item = page.findControl<chitu.ScrollView>(above_name); if (this.above_item == null) throw Errors.controlNotExists(above_name); } else { this.above_item = null; } if (below_name) { this.below_item = page.findControl<chitu.ScrollView>(below_name); if (this.below_item == null) throw Errors.controlNotExists(below_name); } else { this.below_item = null; } if (prev_view) { let animation_time = 200; window.setTimeout(() => prev_view.visible = false, animation_time); } } } class Errors { static controlNotExists(name) { let msg = chitu.Utility.format('Control named "{0}" is not exists.', name); return new Error(msg); } } export = ScrollViewGesture;
the_stack
import { parseScript } from 'meriyah'; import { ClassDeclaration, MethodDefinition, ExpressionStatement, FunctionDeclaration, FunctionExpression, Node } from 'estree'; import { ClassType, CustomMapper, JsonAliasOptions, JsonDecorator, JsonDecoratorOptions, JsonGetterOptions, JsonPropertyOptions, JsonSetterOptions, JsonStringifierParserCommonContext, } from './@types'; import 'reflect-metadata'; import { JacksonError } from './core/JacksonError'; import { DefaultContextGroup } from './core/DefaultContextGroup'; /** * @internal */ export interface MakeMetadataKeyWithContextOptions { prefix?: string; suffix?: string; contextGroup?: string; } /** * @internal */ export const makeMetadataKeyWithContext = (key: string, options: MakeMetadataKeyWithContextOptions = {}): string => { const regExp = /^[\w]+$/; if (options.contextGroup != null && !regExp.test(options.contextGroup)) { // eslint-disable-next-line max-len throw new JacksonError(`Invalid context group name "${options.contextGroup}" found! The context group name must match "/^[\\w]+$/" regular expression, that is a non-empty string which contains any alphanumeric character including the underscore.`); } return 'jackson:' + (options.contextGroup != null ? options.contextGroup : DefaultContextGroup) + ':' + (options.prefix != null ? options.prefix + ':' : '') + key + (options.suffix != null ? ':' + options.suffix : ''); }; /** * @internal */ export interface MakeMetadataKeysWithContextOptions { prefix?: string; suffix?: string; contextGroups?: string[]; } /** * @internal */ export const makeMetadataKeysWithContext = (key: string, options: MakeMetadataKeysWithContextOptions): string[] => (options.contextGroups != null && options.contextGroups.length > 0) ? options.contextGroups.map((contextGroup) => makeMetadataKeyWithContext(key, {prefix: options.prefix, suffix: options.suffix, contextGroup}) ) : [makeMetadataKeyWithContext(key, {prefix: options.prefix, suffix: options.suffix, contextGroup: null})]; /** * @internal */ export interface DefineMetadataOptions { prefix?: string; suffix?: string; } /** * @internal */ export const defineMetadata = (metadataKey: any, metadataValue: JsonDecoratorOptions, target: Record<string, any>, propertyKey: string | symbol = null, options: DefineMetadataOptions = {}) => { const makeMetadataKeysWithContextOptions: MakeMetadataKeysWithContextOptions = { contextGroups: metadataValue.contextGroups, ...options }; makeMetadataKeysWithContext(metadataKey, makeMetadataKeysWithContextOptions).forEach((metadataKeyWithContext) => { if (propertyKey == null) { Reflect.defineMetadata(metadataKeyWithContext, metadataValue, target); } else { Reflect.defineMetadata(metadataKeyWithContext, metadataValue, target, propertyKey); } }); }; /** * https://stackoverflow.com/a/43197340/4637638 * @internal */ export const isClass = (obj): boolean => { const isCtorClass = obj.constructor && obj.constructor.toString().substring(0, 5) === 'class'; if (obj.prototype === undefined) { return isCtorClass || !isFunction(obj); } const isPrototypeCtorClass = obj.prototype.constructor && obj.prototype.constructor.toString && obj.prototype.constructor.toString().substring(0, 5) === 'class'; return isCtorClass || isPrototypeCtorClass || !isFunction(obj); }; /** * https://stackoverflow.com/a/56035104/4637638 * @internal */ export const isFunction = (funcOrClass: any): boolean => { const propertyNames = Object.getOwnPropertyNames(funcOrClass); return (!propertyNames.includes('prototype') || propertyNames.includes('arguments')); }; /** * @internal */ export const makeDecorator = <T>( options: (...args: any[]) => JsonDecoratorOptions, decorator: JsonDecorator): any => { const DecoratorFactory = (...args: any[]): any => { const target: Record<string, any> = args[0]; const propertyKey: null | string | symbol = args[1]; const descriptorOrParamIndex: null | number | TypedPropertyDescriptor<any> = args[2]; if ((typeof target === 'function' || propertyKey != null || descriptorOrParamIndex != null) || descriptorOrParamIndex != null && typeof descriptorOrParamIndex === 'number') { return decorator(options(), target, propertyKey, descriptorOrParamIndex); } else { return <T>(targetDecorator: Record<string, any>, propertyKeyDecorator?: string | symbol, descriptor?: TypedPropertyDescriptor<T>): any => decorator(options(args[0]), targetDecorator, propertyKeyDecorator, descriptor); } }; return DecoratorFactory; }; /** * @internal */ export const makeJacksonDecorator = <T>( options: (...args: any[]) => JsonDecoratorOptions, decorator: JsonDecorator): any => makeDecorator<T>( options, (o: JsonDecoratorOptions, target, propertyKey, descriptorOrParamIndex) => { if (propertyKey != null) { o._propertyKey = propertyKey.toString(); } if (descriptorOrParamIndex != null && typeof descriptorOrParamIndex !== 'number') { o._descriptor = descriptorOrParamIndex; } const value = decorator(o, target, propertyKey, descriptorOrParamIndex); if (value != null) { return value; } if (typeof descriptorOrParamIndex !== 'number') { return descriptorOrParamIndex; } }); /** * https://github.com/rphansen91/es-arguments/blob/master/src/arguments.js#L3 * @internal */ const pluckPattern = (pattern): string => ['{', pattern.map(({ key }) => key.name).join(', '), '}'].join(' '); /** * https://github.com/rphansen91/es-arguments/blob/master/src/arguments.js#L9 * @internal */ const pluckParamName = (param): string => { if (param.name) {return param.name; } if (param.left) {return pluckParamName(param.left); } if (param.properties) {return pluckPattern(param.properties); } if (param.type === 'RestElement') {return '...' + pluckParamName(param.argument); } return; }; /** * @internal */ export interface GetClassPropertiesOptions { /** * Class properties with Getters method/property name. * * If {@link withGetterVirtualProperties} is `false`, then the * property the Getter is referencing will be deleted from the * Class properties. */ withGettersAsProperty?: boolean; withGetterVirtualProperties?: boolean; /** * Class properties with Setters method/property name. * * If {@link withSetterVirtualProperties} is `false`, then the * property the Setter is referencing will be deleted from the * Class properties. */ withSettersAsProperty?: boolean; withSetterVirtualProperties?: boolean; withJsonVirtualPropertyValues?: boolean; withJsonAliases?: boolean; } /** * @internal */ export const getClassProperties = (target: Record<string, any>, obj: any = null, context: JsonStringifierParserCommonContext<any>, options: GetClassPropertiesOptions = {}): string[] => { options = { withGettersAsProperty: false, withGetterVirtualProperties: false, withSettersAsProperty: false, withSetterVirtualProperties: false, withJsonVirtualPropertyValues: false, withJsonAliases: false, ...options }; const contextGroupsWithDefault = [ ...(context.withContextGroups ? context.withContextGroups : []), DefaultContextGroup ]; let objKeys = []; if (obj != null) { objKeys = Object.keys(obj); if (objKeys.includes('constructor') && typeof obj.constructor === 'function' && !obj.constructor.toString().endsWith('{ [native code] }') && obj.constructor.constructor.toString().endsWith('{ [native code] }')) { objKeys.splice(objKeys.indexOf('constructor'), 1); } } const keysToBeDeleted = new Set<string>(); const metadataKeys = Reflect.getMetadataKeys(target); let classProperties: Set<string> = new Set(objKeys); for (const metadataKey of metadataKeys) { if (metadataKey.startsWith('jackson:')) { const metadataKeyWithoutJacksonPrefix = metadataKey.replace('jackson:', ''); if (metadataKeyWithoutJacksonPrefix.includes(':JsonVirtualProperty:') || (metadataKeyWithoutJacksonPrefix.includes(':JsonAlias:') && options.withJsonAliases)) { let metadataKeyFoundInContext = false; for (const contextGroup of contextGroupsWithDefault) { const suffix = metadataKeyWithoutJacksonPrefix .split((metadataKeyWithoutJacksonPrefix.includes(':JsonVirtualProperty:')) ? ':JsonVirtualProperty:' : ':JsonAlias:')[1]; const metadataKeyWithContext = makeMetadataKeyWithContext( (metadataKeyWithoutJacksonPrefix.includes(':JsonVirtualProperty:')) ? 'JsonVirtualProperty' : 'JsonAlias', { contextGroup, suffix }); if (metadataKeyWithContext === metadataKey) { metadataKeyFoundInContext = true; break; } } if (!metadataKeyFoundInContext) { continue; } } if (metadataKeyWithoutJacksonPrefix.includes(':JsonVirtualProperty:')) { const jsonVirtualProperty: JsonPropertyOptions | JsonGetterOptions | JsonSetterOptions = Reflect.getMetadata(metadataKey, target); if (jsonVirtualProperty && jsonVirtualProperty._descriptor != null && typeof jsonVirtualProperty._descriptor.value === 'function') { if (jsonVirtualProperty._propertyKey.startsWith('get')) { if (options.withGetterVirtualProperties) { classProperties.add(jsonVirtualProperty.value); } if (!options.withGettersAsProperty) { continue; } else if (!options.withGetterVirtualProperties) { keysToBeDeleted.add(jsonVirtualProperty.value); } } if (jsonVirtualProperty._propertyKey.startsWith('set')) { if (options.withSetterVirtualProperties) { classProperties.add(jsonVirtualProperty.value); } if (!options.withSettersAsProperty) { continue; } else if (!options.withSetterVirtualProperties) { keysToBeDeleted.add(jsonVirtualProperty.value); } } } classProperties.add(jsonVirtualProperty._propertyKey); if (options.withJsonVirtualPropertyValues && jsonVirtualProperty.value != null) { classProperties.add(jsonVirtualProperty.value); } } else if (metadataKeyWithoutJacksonPrefix.includes(':JsonAlias:') && options.withJsonAliases) { const propertyKey = metadataKeyWithoutJacksonPrefix.split(':JsonAlias:')[1]; classProperties.add(propertyKey); const jsonAlias: JsonAliasOptions = Reflect.getMetadata(metadataKey, target); if (jsonAlias.values != null) { for (const alias of jsonAlias.values) { classProperties.add(alias); } } } } } classProperties = new Set([...classProperties].filter((key) => !keysToBeDeleted.has(key))); let parent = target; while (parent.name && parent !== Object) { const propertyDescriptors = Object.getOwnPropertyDescriptors(parent.prototype); // eslint-disable-next-line guard-for-in for (const property in propertyDescriptors) { const propertyDescriptor = propertyDescriptors[property]; if (propertyDescriptor.get != null || propertyDescriptor.set != null) { classProperties.add(property); } } parent = Object.getPrototypeOf(parent); } return [...classProperties]; }; /** * @internal */ export const classHasOwnProperty = (target: Record<string, any>, propertyKey: string, obj: any, context: JsonStringifierParserCommonContext<any>, options?: GetClassPropertiesOptions): boolean => { const classProperties = getClassProperties(target, obj, context, options); return classProperties.includes(propertyKey); }; /** * @internal */ export interface VirtualPropertiesToClassPropertiesMappingOptions { checkGetters?: boolean; checkSetters?: boolean; } /** * @internal */ export const mapVirtualPropertiesToClassProperties = (target: Record<string, any>, keys: string[], context: JsonStringifierParserCommonContext<any>, options: VirtualPropertiesToClassPropertiesMappingOptions): string[] => [...virtualPropertiesToClassPropertiesMapping(target, keys, context, options).values()]; /** * @internal */ export const virtualPropertiesToClassPropertiesMapping = (target: Record<string, any>, keys: string[], context: JsonStringifierParserCommonContext<any>, options: VirtualPropertiesToClassPropertiesMappingOptions): Map<string, string> => { options = { checkGetters: false, checkSetters: false, ...options }; const contextGroupsWithDefault = [ ...(context.withContextGroups ? context.withContextGroups : []), DefaultContextGroup ]; const metadataKeys = Reflect.getMetadataKeys(target); const propertiesMapping: Map<string, string> = new Map(); for (const key of keys) { let getterOrSetterFound = false; for (const metadataKey of metadataKeys) { if (metadataKey.startsWith('jackson:')) { const metadataKeyWithoutJacksonPrefix = metadataKey.replace('jackson:', ''); if (metadataKeyWithoutJacksonPrefix.includes(':JsonVirtualProperty:')) { let metadataKeyFoundInContext = false; for (const contextGroup of contextGroupsWithDefault) { const suffix = metadataKeyWithoutJacksonPrefix.split(':JsonVirtualProperty:')[1]; const metadataKeyWithContext = makeMetadataKeyWithContext('JsonVirtualProperty', { contextGroup, suffix }); if (metadataKeyWithContext === metadataKey) { metadataKeyFoundInContext = true; break; } } if (!metadataKeyFoundInContext) { continue; } const jsonVirtualProperty: JsonPropertyOptions | JsonGetterOptions | JsonSetterOptions = Reflect.getMetadata(metadataKey, target); if (jsonVirtualProperty.value !== key) { continue; } if (jsonVirtualProperty && jsonVirtualProperty._descriptor != null && typeof jsonVirtualProperty._descriptor.value === 'function') { if ((options.checkGetters && jsonVirtualProperty._propertyKey.startsWith('get')) || (options.checkSetters && jsonVirtualProperty._propertyKey.startsWith('set'))) { propertiesMapping.set(key, jsonVirtualProperty._propertyKey); getterOrSetterFound = true; break; } } } } } if (!getterOrSetterFound) { propertiesMapping.set(key, key); } } return propertiesMapping; }; /** * @internal */ export const mapVirtualPropertyToClassProperty = (target: Record<string, any>, key: string, context: JsonStringifierParserCommonContext<any>, options: VirtualPropertiesToClassPropertiesMappingOptions): string => mapVirtualPropertiesToClassProperties(target, [key], context, options)[0]; /** * @internal */ export const mapClassPropertiesToVirtualProperties = (target: Record<string, any>, classProperties: string[], context: JsonStringifierParserCommonContext<any>): string[] => [...classPropertiesToVirtualPropertiesMapping(target, classProperties, context).values()]; /** * @internal */ export const classPropertiesToVirtualPropertiesMapping = (target: Record<string, any>, classProperties: string[], context: JsonStringifierParserCommonContext<any>): Map<string, string> => { const contextGroupsWithDefault = [ ...(context.withContextGroups ? context.withContextGroups : []), DefaultContextGroup ]; const propertiesMapping: Map<string, string> = new Map(); for (const classProperty of classProperties) { let jsonVirtualProperty: JsonPropertyOptions | JsonGetterOptions | JsonSetterOptions = null; for (const contextGroup of contextGroupsWithDefault) { const metadataKeyWithContext = makeMetadataKeyWithContext('JsonVirtualProperty', { contextGroup, suffix: classProperty }); jsonVirtualProperty = Reflect.getMetadata(metadataKeyWithContext, target); if (jsonVirtualProperty != null) { break; } } if (jsonVirtualProperty) { propertiesMapping.set(classProperty, jsonVirtualProperty.value); } else { propertiesMapping.set(classProperty, classProperty); } } return propertiesMapping; }; /** * @internal */ export const mapClassPropertyToVirtualProperty = (target: Record<string, any>, key: string, context: JsonStringifierParserCommonContext<any>): string => mapClassPropertiesToVirtualProperties(target, [key], context)[0]; /** * @internal */ export const getArgumentNames = (method): string[] => { let code = method.toString().trim(); if (code.endsWith(' { [native code] }')) { return []; } if (code.startsWith('class extends')) { code = 'class JacksonClass ' + code.substring(6); } else if (code.startsWith('function (')) { code = 'function JacksonFunction ' + code.substring(9); } else if (!code.startsWith('class ') && !code.startsWith('function ')) { code = 'function ' + code; } const ast = parseScript(code, { next: true, webcompat: true, directives: true }); const body = ast.body; let nodes: Node[] = []; if (code.startsWith('class ')) { const classDeclarationNodes = (body[0] as ClassDeclaration).body.body; // find constructor for (const propertyOrMethod of classDeclarationNodes) { if (propertyOrMethod.kind === 'constructor') { nodes = [propertyOrMethod]; break; } } } else { nodes = [body[0] as FunctionDeclaration]; } return nodes.reduce((args, exp) => { if ((exp as FunctionDeclaration).params) { return args.concat((exp as FunctionDeclaration).params); } if ('value' in exp && exp.value != null && ((exp as MethodDefinition).value).params) { return args.concat((exp as MethodDefinition).value.params); } if ('expression' in exp && exp.expression != null && ((exp as ExpressionStatement).expression as FunctionExpression).params) { return args.concat(((exp as ExpressionStatement).expression as FunctionExpression).params); } return args; }, []).map(pluckParamName); }; /** * @internal */ export const isSameConstructor = (ctorOrCtorName, ctor2): boolean => (typeof ctorOrCtorName === 'string' && ctorOrCtorName === ctor2.name) || ctorOrCtorName === ctor2; /** * @internal */ export const isExtensionOf = (ctor, ctorExtensionOf): boolean => { if (typeof ctor === 'string') { let parent = Object.getPrototypeOf(ctorExtensionOf); while (parent.name) { if (parent.name === ctor) { return true; } // get parent class parent = Object.getPrototypeOf(parent); } } else { return ctor !== ctorExtensionOf && ctorExtensionOf.prototype instanceof ctor; } return false; }; /** * @internal */ export const isSameConstructorOrExtensionOf = (ctorOrCtorName, ctor2): boolean => (isSameConstructor(ctorOrCtorName, ctor2) || isExtensionOf(ctorOrCtorName, ctor2)); /** * @internal */ export const isSameConstructorOrExtensionOfNoObject = (ctorOrCtorName, ctor2): boolean => ctorOrCtorName !== Object && (isSameConstructor(ctorOrCtorName, ctor2) || isExtensionOf(ctorOrCtorName, ctor2)); /** * @internal */ export const hasIterationProtocol = (variable): boolean => variable !== null && Symbol.iterator in Object(variable); /** * @internal */ export const isIterableNoMapNoString = (variable): boolean => typeof variable !== 'string' && !(isSameConstructorOrExtensionOfNoObject(variable.constructor, Map)) && hasIterationProtocol(variable); /** * @internal */ export const isIterableNoString = (variable): boolean => typeof variable !== 'string' && hasIterationProtocol(variable); /** * @internal */ export const isClassIterableNoMap = (ctor: ClassType<any>): boolean => !(isSameConstructorOrExtensionOfNoObject(ctor, Map)) && hasIterationProtocol(ctor.prototype); /** * @internal */ export const isClassIterableNoMapNoString = (ctor: ClassType<any>): boolean => !(isSameConstructorOrExtensionOfNoObject(ctor, String)) && !(isSameConstructorOrExtensionOfNoObject(ctor, Map)) && hasIterationProtocol(ctor.prototype); /** * @internal */ export const isClassIterable = (ctor: ClassType<any>): boolean => hasIterationProtocol(ctor.prototype); /** * https://stackoverflow.com/a/1482209/4637638 * @internal */ export const isObjLiteral = (_obj: any): boolean => { let _test = _obj; return ( typeof _obj !== 'object' || _obj === null ? false : ( (() => { while (true) { if ( Object.getPrototypeOf( _test = Object.getPrototypeOf(_test) ) === null) { break; } } return Object.getPrototypeOf(_obj) === _test; })() ) ); }; /** * https://stackoverflow.com/a/3886106/4637638 * @internal */ export const isInt = (n: number) => Number(n) === n && n % 1 === 0; /** * https://stackoverflow.com/a/3886106/4637638 * @internal */ export const isFloat = (n: number) => Number(n) === n && n % 1 !== 0; /** * find metadata considering also _internalDecorators * @internal */ export const findMetadataByMetadataKeyWithContext = <T extends JsonDecoratorOptions>( metadataKeyWithContext: string, target: Record<string, any>, propertyKey: string | symbol = null, context: JsonStringifierParserCommonContext<any>): T => { let jsonDecoratorOptions: JsonDecoratorOptions = (propertyKey) ? Reflect.getMetadata(metadataKeyWithContext, target, propertyKey) : Reflect.getMetadata(metadataKeyWithContext, target); // search also on its prototype chain let parent = target; while (jsonDecoratorOptions == null && parent.name) { if (jsonDecoratorOptions == null && propertyKey == null && context != null && context._internalDecorators != null) { const map = context._internalDecorators.get(parent as ObjectConstructor); if (map != null && metadataKeyWithContext in map) { jsonDecoratorOptions = map[metadataKeyWithContext] as JsonDecoratorOptions; } } // get parent class parent = Object.getPrototypeOf(parent); } return jsonDecoratorOptions as T; }; /** * @internal */ export const findMetadata = <T extends JsonDecoratorOptions>(metadataKey: string, target: Record<string, any>, propertyKey: string | symbol = null, context: JsonStringifierParserCommonContext<any>): T => { let jsonDecoratorOptions: JsonDecoratorOptions = null; const contextGroupsWithDefault = [ ...(context.withContextGroups ? context.withContextGroups : []), DefaultContextGroup ]; for (const contextGroup of contextGroupsWithDefault) { const metadataKeyWithContext = makeMetadataKeyWithContext(metadataKey, {contextGroup}); jsonDecoratorOptions = findMetadataByMetadataKeyWithContext( metadataKeyWithContext, target, propertyKey, context ); if (jsonDecoratorOptions != null) { break; } } return jsonDecoratorOptions as T; }; /** * @internal */ export const getMetadata = <T extends JsonDecoratorOptions>(metadataKey: string, target: Record<string, any>, propertyKey: string | symbol = null, context: JsonStringifierParserCommonContext<any>): T => { const jsonjsonDecoratorOptions: JsonDecoratorOptions = (!metadataKey.startsWith('jackson:')) ? findMetadata(metadataKey, target, propertyKey, context) : findMetadataByMetadataKeyWithContext(metadataKey, target, propertyKey, context); if (jsonjsonDecoratorOptions != null && context != null && context.decoratorsEnabled != null) { const decoratorKeys = Object.keys(context.decoratorsEnabled); const decoratorKey = decoratorKeys.find((key) => (metadataKey.startsWith('jackson:')) ? metadataKey.replace('jackson:', '').includes(':' + key) : metadataKey.startsWith(key)); if (decoratorKey && typeof context.decoratorsEnabled[decoratorKey] === 'boolean') { jsonjsonDecoratorOptions.enabled = context.decoratorsEnabled[decoratorKey]; } } return jsonjsonDecoratorOptions != null && jsonjsonDecoratorOptions.enabled ? jsonjsonDecoratorOptions as T : undefined; }; /** * find all metadataKeys considering also _internalDecorators * @internal */ export const findMetadataKeys = <T extends JsonDecoratorOptions>(target: Record<string, any>, context: JsonStringifierParserCommonContext<any>): any[] => { const metadataKeys = new Set(Reflect.getMetadataKeys(target)); const contextGroupsWithDefault = [ ...(context.withContextGroups ? context.withContextGroups : []), DefaultContextGroup ]; if (context != null && context._internalDecorators != null) { // search also on its prototype chain let parent = target; while (parent.name) { const internalDecorators = context._internalDecorators.get(parent as ObjectConstructor); for (const key in internalDecorators) { if (key === 'depth') { continue; } metadataKeys.add(key); } // get parent class parent = Object.getPrototypeOf(parent); } } for (const metadataKey of metadataKeys) { let metadataKeyFoundInContext = false; for (const contextGroup of contextGroupsWithDefault) { if (metadataKey.startsWith('jackson:' + contextGroup + ':')) { metadataKeyFoundInContext = true; break; } } if (!metadataKeyFoundInContext || !metadataKey.startsWith('jackson:')) { metadataKeys.delete(metadataKey); } } return [...metadataKeys]; }; /** * @internal */ export const getMetadataKeys = <T extends JsonDecoratorOptions>(target: Record<string, any>, context: JsonStringifierParserCommonContext<any>): any[] => { let metadataKeys = findMetadataKeys(target, context); if (context != null && context.decoratorsEnabled != null) { const decoratorKeys = Object.keys(context.decoratorsEnabled); metadataKeys = metadataKeys.filter((metadataKey) => { const decoratorKey = decoratorKeys.find((key) => (metadataKey.startsWith('jackson:')) ? metadataKey.replace('jackson:', '').includes(':' + key) : metadataKey.startsWith(key)); return context.decoratorsEnabled[decoratorKey] == null || context.decoratorsEnabled[decoratorKey]; }); } return metadataKeys; }; /** * @internal */ export const hasMetadata = <T extends JsonDecoratorOptions>(metadataKey: string, target: Record<string, any>, propertyKey: string | symbol = null, context: JsonStringifierParserCommonContext<any>): boolean => { const option: JsonDecoratorOptions = getMetadata<T>(metadataKey, target, propertyKey, context); return option != null; }; /** * @internal */ export const isVariablePrimitiveType = (value: any): boolean => value != null && isConstructorPrimitiveType(value.constructor); /** * @internal */ export const isConstructorPrimitiveType = (ctor: any): boolean => ctor === Number || (BigInt && ctor === BigInt) || ctor === String || ctor === Boolean || (Symbol && ctor === Symbol); /** * @internal */ export const getDefaultPrimitiveTypeValue = (ctor: ClassType<any>): any | null => { switch (ctor) { case Number: return 0; case Boolean: return false; case String: return ''; default: if (BigInt && ctor === BigInt) { return BigInt(0); } } return null; }; /** * @internal */ export const getDefaultValue = (value: any): any | null => { if (value != null) { return getDefaultPrimitiveTypeValue(value.constructor); } return null; }; /** * @internal */ export const isValueEmpty = (value: any): boolean => value == null || ( (value instanceof Set || value instanceof Map) && value.size === 0 ) || ( !(value instanceof Set || value instanceof Map) && (typeof value === 'object' || typeof value === 'string') && Object.keys(value).length === 0 ); /** * @internal */ export const getDeepestClass = (array: Array<any>): any | null => { if (array == null || array.length === 0) { return null; } if (!(array[array.length - 1] instanceof Array)) { return array[array.length - 1]; } return getDeepestClass(array[array.length - 1]); }; /** * @internal */ export const getObjectKeysWithPropertyDescriptorNames = (obj: any, ctor: any, context: JsonStringifierParserCommonContext<any>, options?: GetClassPropertiesOptions): string[] => { if (obj == null) { return []; } const keys = Object.keys(obj); const classProperties = getClassProperties(ctor != null ? ctor : obj.constructor, null, context, options); if (keys.includes('constructor') && typeof obj.constructor === 'function' && !obj.constructor.toString().endsWith('{ [native code] }') && obj.constructor.constructor.toString().endsWith('{ [native code] }')) { keys.splice(keys.indexOf('constructor'), 1); } return [...new Set([...keys, ...classProperties])]; }; /** * @internal */ export const objectHasOwnPropertyWithPropertyDescriptorNames = (obj: any, ctor: any, key: string, context: JsonStringifierParserCommonContext<any>, options?: GetClassPropertiesOptions): boolean => { if (obj == null || key == null) { return false; } return getObjectKeysWithPropertyDescriptorNames(obj, ctor, context, options).includes(key); }; /** * @internal */ export const castObjLiteral = (target: any, value: any): any => { if (isObjLiteral(value) && target !== Object) { let parent = target; while (parent.name && parent !== Object) { const propertyDescriptors = Object.getOwnPropertyDescriptors(parent.prototype); // eslint-disable-next-line guard-for-in for (const property in propertyDescriptors) { if (!Object.hasOwnProperty.call(value, property)) { const jsonPropertyMetadataKey = Reflect.getMetadataKeys(target, property) .find((metadataKey: string) => metadataKey.endsWith(':JsonProperty')); if (jsonPropertyMetadataKey != null) { const jsonPropertyOptions: JsonPropertyOptions = Reflect.getMetadata(jsonPropertyMetadataKey, target, property); if (jsonPropertyOptions && jsonPropertyOptions._descriptor == null) { continue; } } const ownPropertyDescriptor = { ...propertyDescriptors[property] }; ownPropertyDescriptor.enumerable = false; Object.defineProperty(value, property, ownPropertyDescriptor); } } parent = Object.getPrototypeOf(parent); } } return value; }; /** * Sort custom user-defined serializers/deserializers by its order. * * @param mappers * @internal */ export const sortMappersByOrder = <T>(mappers: CustomMapper<T>[]): CustomMapper<T>[] => mappers.sort((a, b) => a.order - b.order > 0 ? 1 : -1);
the_stack
module TDev.RT { //? Contains binary data //@ stem("buf") export class Buffer extends RTValue { public buffer:Uint8Array; // this may also be CanvasPixelData public imageData:ImageData; static fromString(s:string, encoding:string) { function bin(b:string) { if (b == null) return undefined; return Buffer.fromTypedArray(Util.stringToUint8Array(b)) } function hex(s: string) { var prev = -1 var buf: Uint8Array = null; var len = 0; for (var iter = 0; iter < 2; ++iter) { for (var i = 0; i < s.length; ++i) { var c = s.charCodeAt(i); var v = 0; if (48 <= c && c <= 57) v = c - 48; else if (97 <= c && c <= 102) v = c - 97 + 10; else if (65 <= c && c <= 70) v = c - 65 + 10; else if (/^[\s\r\n-,.=]$/.test(s.charAt(i))) continue; else return undefined; if (prev == -1) prev = v * 16; else { prev += v; if (buf) buf[len++] = prev; else len++; prev = -1; } } if (buf) return Buffer.fromTypedArray(buf) prev = -1; buf = new Uint8Array(len); len = 0; } } switch (encoding) { case "base64": return bin(Util.base64Decode(s)) case "hex": return hex(s); case "binary": return bin(s); case "utf8": return bin(Util.toUTF8(s)) case "utf16le": return bin(Util.toUTF16LE(s)) default: return undefined; } } static fromImageData(id:ImageData) { var r = Buffer.fromTypedArray(<any>id.data) r.imageData = id return r; } static fromTypedArray(a:Uint8Array) { var r = new (<any> Buffer)(); //TS9 r.buffer = a; return r; } static mk(size:number) { return this.fromTypedArray(new Uint8Array(size)); } private needSubarray() { // IE doesn't support subarray() method on CanvasPixelData // Node.js doesn't have it on Buffer if (this.buffer.subarray) return; var newBuf = new Uint8Array(this.buffer.length) for (var i = 0; i < newBuf.length; ++i) newBuf[i] = this.buffer[i]; this.buffer = newBuf this.imageData = null } //? Read a binary number at `offset` //@ [format].deflStrings("int8", "uint8", "int16", "uint16", "int32", "uint32") //@ [endian].deflStrings("le", "be") public read_number(offset:number, format:string, endian:string) : number { var v = 0; var b = this.buffer var max = 0 var size = 1 if (endian == "le") { switch (format) { case "int8": max = 127 case "uint8": v = b[offset]; break; case "int16": max = 32767 case "uint16": size = 2 v = (b[offset + 1] << 8) + b[offset]; break; case "int32": max = 2147483647 case "uint32": size = 4 v = b[offset + 3] * (1 << 24) + (b[offset + 2] << 16) + (b[offset + 1] << 8) + b[offset]; break; default: Util.userError(lf("unknown number format: {0}", format)); } } else if (endian == "be") { switch (format) { case "int8": max = 127 case "uint8": v = b[offset]; break; case "int16": max = 32767 case "uint16": size = 2 v = (b[offset] << 8) + b[offset + 1]; break; case "int32": max = 2147483647 case "uint32": size = 4 v = b[offset] * (1 << 24) + (b[offset + 1] << 16) + (b[offset + 2] << 8) + b[offset + 3]; break; default: Util.userError(lf("unknown number format: {0}", format)); } } else { Util.userError(lf("unknown number endian: {0}", endian)); } if (offset < 0 || offset + size > b.length) Util.userError(lf("offset outside of range: {0} (buffer length {1})", offset, b.length)) if (v === undefined || isNaN(v)) return undefined if (max && v > max) v = v - max * 2 - 2; return v } //? Write a binary number `value` at `offset` //@ [format].deflStrings("int8", "uint8", "int16", "uint16", "int32", "uint32") //@ [endian].deflStrings("le", "be") public write_number(value:number, offset:number, format:string, endian:string) { var v = value var b = this.buffer var min = 0 var max = 0 var size = 0; if (Math.floor(v) != v) Util.userError(lf("number {0} is fractional", v)) switch (format) { case "int8": size = 1; min = -0x80; max = 0x7f; break; case "uint8": size = 1; max = 0xff; break; case "int16": size = 2; min = -0x8000; max = 0x7fff; break; case "uint16": size = 2; max = 0xffff; break; case "int32": size = 4; min = -0x80000000; max = 0x7fffffff; break; case "uint32": size = 4; max = 0xffffffff; break; default: Util.userError(lf("unknown number format: {0}", format)); } if (v < min || v > max) Util.userError(lf("number {0} is outside range of {1}", v, format)) v |= 0; if (endian == "be") { for (var i = size - 1; i >= 0; i--) { b[offset + i] = (v & 0xff) v >>= 8; } } else if (endian == "le") { for (var i = 0; i < size; ++i) { b[offset + i] = (v & 0xff) v >>= 8; } } else { Util.userError(lf("unknown number endian: {0}", endian)); } } //? Set byte at `index` to `value` //@ writesMutable public set(index:number, value:number):void { this.buffer[index] = value; } //? Get byte at `index` //@ readsMutable public at(index:number):number { return this.buffer[index]; } //? Return the number of bytes in the buffer //@ robust public count():number { return this.buffer.length; } //? Return the SHA-256 hash of the buffer encoded as lowercase hex //@ betaOnly public sha256():string { return Random.sha256buffer(this.buffer) } //? Return a new buffer consiting of the current and `other` in sequence public concat(other:Buffer) : Buffer { var r = Buffer.mk(this.count() + other.count()) r.copy_from(0, this) r.copy_from(this.count(), other) return r } //? Creates a read-write view of the current buffer. //@ writesMutable public sub_buffer(start:number, length:number) : Buffer { var len = this.count() start = Util.intBetween(0, start, len) length = Util.intBetween(0, length, len - start) if (start == 0 && length == len) return this; this.needSubarray(); return Buffer.fromTypedArray(this.buffer.subarray(start, start + length)); } //? Fills the buffer with random values //@ writesMutable public fill_random() { Random.bytes(this.buffer); } //? Sets all bytes in buffer to `value` //@ writesMutable public fill(value:number) { var buf = this.buffer for (var i = 0; i < buf.length; ++i) buf[i] = value; } //? Copies all bytes from `source` to current buffer at `offset` //@ writesMutable public copy_from(target_offset:number, source:Buffer) { var dst = this.buffer; var src = source.buffer; var len = Math.min(src.length, this.count() - target_offset) if (target_offset == 0) for (var i = 0; i < len; ++i) dst[i] = src[i]; else for (var i = 0; i < len; ++i) dst[target_offset + i] = src[i]; } //? Copies all bytes from `source` to current buffer at `offset` //@ readsMutable public clone(): Buffer { var res = Buffer.mk(this.count()) res.copy_from(0, this) return res; } //? Convert the buffer to a string //@ [encoding].deflStrings("base64", "hex", "binary", "utf8", "utf16le") //@ readsMutable public to_string(encoding:string):string { function hex(inp:Uint8Array) { var hexDigits = "0123456789abcdef"; var len = inp.length; var res = ""; for (var i = 0; i < len; ++i) { var v = inp[i] res += hexDigits[(v>>4)&0xf] + hexDigits[v&0xf]; } return res; } function utf16(inp:Uint8Array) { if (inp.length & 1) return undefined; var len = inp.length var res = "" for (var i = 0; i < len; i += 2) res += String.fromCharCode(inp[i] | (inp[i+1]<<8)); return res; } switch (encoding) { case "base64": return Util.base64EncodeBytes(<any>this.buffer); case "hex": return hex(this.buffer); case "binary": return Util.uint8ArrayToString(this.buffer); case "utf8": return Util.fromUTF8Bytes(this.buffer); case "utf16le": return utf16(this.buffer); default: return undefined; } } } }
the_stack
import '../../../i18n/config'; import { useTheme } from '@material-ui/core'; import Box from '@material-ui/core/Box'; import Button from '@material-ui/core/Button'; import Dialog, { DialogProps } from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogTitle from '@material-ui/core/DialogTitle'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import FormGroup from '@material-ui/core/FormGroup'; import Grid from '@material-ui/core/Grid'; import { makeStyles } from '@material-ui/core/styles'; import Switch from '@material-ui/core/Switch'; import Typography from '@material-ui/core/Typography'; import useMediaQuery from '@material-ui/core/useMediaQuery'; import Editor, { loader } from '@monaco-editor/react'; import * as yaml from 'js-yaml'; import React from 'react'; import { useTranslation } from 'react-i18next'; import { KubeObjectInterface } from '../../../lib/k8s/cluster'; import { getThemeName } from '../../../lib/themes'; import ConfirmButton from '../ConfirmButton'; import Loader from '../Loader'; import Tabs from '../Tabs'; import DocsViewer from './DocsViewer'; import SimpleEditor from './SimpleEditor'; const useStyle = makeStyles(theme => ({ dialogContent: { height: '80%', // minHeight: '600px', overflowY: 'hidden', }, terminalCode: { color: theme.palette.common.white, }, terminal: { backgroundColor: theme.palette.common.black, height: '500px', width: '100%', overflow: 'scroll', marginTop: theme.spacing(3), }, containerFormControl: { minWidth: '11rem', }, scrollable: { overflowY: 'auto', overflowX: 'hidden', }, })); type KubeObjectIsh = Partial<KubeObjectInterface>; interface EditorDialogProps extends DialogProps { item: KubeObjectIsh | null; onClose: () => void; onSave: ((...args: any[]) => void) | null; onEditorChanged?: ((newValue: string) => void) | null; saveLabel?: string; errorMessage?: string; title?: string; } export default function EditorDialog(props: EditorDialogProps) { const { item, onClose, onSave, onEditorChanged, saveLabel, errorMessage, title, ...other } = props; const editorOptions = { selectOnLineNumbers: true, readOnly: isReadOnly(), }; const classes = useStyle(); const theme = useTheme(); const fullScreen = useMediaQuery(theme.breakpoints.down('sm')); const [originalCode, setOriginalCode] = React.useState(''); const [code, setCode] = React.useState(originalCode); const [previousVersion, setPreviousVersion] = React.useState(''); const [error, setError] = React.useState(''); const [docSpecs, setDocSpecs] = React.useState({}); const { t } = useTranslation('resource'); const [useSimpleEditor, setUseSimpleEditorState] = React.useState(() => { const localData = localStorage.getItem('useSimpleEditor'); return localData ? JSON.parse(localData) : false; }); function setUseSimpleEditor(data: boolean) { localStorage.setItem('useSimpleEditor', JSON.stringify(data)); setUseSimpleEditorState(data); } React.useEffect(() => { if (!item) { return; } const itemCode = yaml.dump(item); if (itemCode !== originalCode) { setOriginalCode(itemCode); } if (!item.metadata) { return; } // Only change if the code hasn't been touched. if (previousVersion !== item.metadata!.resourceVersion || code === originalCode) { setCode(itemCode); if (previousVersion !== item.metadata!.resourceVersion) { setPreviousVersion(item!.metadata!.resourceVersion); } } }, [item, previousVersion, originalCode, code]); function isReadOnly() { return onSave === null; } function onChange(value: string | undefined): void { setCode(value as string); if (error && getObjectFromCode(value as string)) { setError(''); } if (onEditorChanged) { onEditorChanged(value as string); } } function getObjectFromCode(code: string): KubeObjectInterface | null { try { const codeObj = yaml.load(code); return codeObj as KubeObjectInterface; } catch (e) { return null; } } function handleTabChange(tabIndex: number) { // Check if the docs tab has been selected. if (tabIndex !== 1) { return; } const codeObj = getObjectFromCode(code); const { kind, apiVersion } = (codeObj || {}) as KubeObjectInterface; if (codeObj === null || (!!kind && !!apiVersion)) { setDocSpecs({ error: codeObj === null, kind, apiVersion, }); } } function onUndo() { setCode(originalCode); } function handleSave() { // Verify the YAML even means anything before trying to use it. if (!getObjectFromCode(code)) { setError(t("Error parsing the code. Please verify it's valid YAML!")); return; } onSave!(getObjectFromCode(code)); } function makeEditor() { const { i18n } = useTranslation(); const [lang, setLang] = React.useState(i18n.language); const themeName = getThemeName(); React.useEffect(() => { i18n.on('languageChanged', setLang); return () => { i18n.off('languageChanged', setLang); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // @todo: monaco editor does not support pt, ta, hi amongst various other langs. if (['de', 'es', 'fr', 'it', 'ja', 'ko', 'ru', 'zh-cn', 'zh-tw'].includes(lang)) { loader.config({ 'vs/nls': { availableLanguages: { '*': lang } } }); } return useSimpleEditor ? ( <Box paddingTop={2} height="100%"> <SimpleEditor language="yaml" value={code} onChange={onChange} /> </Box> ) : ( <Box paddingTop={2} height="100%"> <Editor language="yaml" theme={themeName === 'dark' ? 'vs-dark' : 'light'} value={code} options={editorOptions} onChange={onChange} height="600px" /> </Box> ); } const errorLabel = error || errorMessage; let dialogTitle = title; if (!dialogTitle && item) { const itemName = item.metadata?.name || t('New Object'); dialogTitle = isReadOnly() ? t('resource|View: {{ itemName }}', { itemName }) : t('resource|Edit: {{ itemName }}', { itemName }); } const focusedRef = React.useCallback(node => { if (node !== null) { node.setAttribute('tabindex', '-1'); node.focus(); } }, []); return ( <Dialog aria-busy={!item} maxWidth="lg" scroll="paper" fullWidth fullScreen={fullScreen} onBackdropClick={onClose} {...other} aria-labelledby="editor-dialog-title" > {!item ? ( <Loader title={t('Loading editor')} /> ) : ( <React.Fragment> <Grid container spacing={0}> <Grid item xs={6}> <DialogTitle id="editor-dialog-title" ref={focusedRef}> {dialogTitle} </DialogTitle> </Grid> <Grid xs={6} item> <Box display="flex" flexDirection="row-reverse"> <Box p={1}> <FormGroup row> <FormControlLabel control={ <Switch checked={useSimpleEditor} onChange={() => setUseSimpleEditor(!useSimpleEditor)} name="useSimpleEditor" /> } label="Use minimal editor" /> </FormGroup> </Box> </Box> </Grid> </Grid> <DialogContent className={classes.dialogContent}> {isReadOnly() ? ( makeEditor() ) : ( <Tabs onTabChanged={handleTabChange} tabProps={{ centered: true, }} tabs={[ { label: t('frequent|Editor'), component: makeEditor(), }, { label: t('frequent|Documentation'), component: ( <Box p={2} className={classes.scrollable} height="600px"> <DocsViewer docSpecs={docSpecs} /> </Box> ), }, ]} /> )} </DialogContent> <DialogActions> {!isReadOnly() && ( <ConfirmButton disabled={originalCode === code} color="secondary" aria-label={t('frequent|Undo')} onConfirm={onUndo} confirmTitle={t('frequent|Are you sure?')} confirmDescription={t( 'This will discard your changes in the editor. Do you want to proceed?' )} // @todo: aria-controls should point to the textarea id > {t('frequent|Undo Changes')} </ConfirmButton> )} <div style={{ flex: '1 0 0' }} /> {errorLabel && <Typography color="error">{errorLabel}</Typography>} <div style={{ flex: '1 0 0' }} /> <Button onClick={onClose} color="primary"> {t('frequent|Close')} </Button> {!isReadOnly() && ( <Button onClick={handleSave} color="primary" disabled={originalCode === code || !!error} // @todo: aria-controls should point to the textarea id > {saveLabel || t('frequent|Save & Apply')} </Button> )} </DialogActions> </React.Fragment> )} </Dialog> ); } export function ViewDialog(props: Omit<EditorDialogProps, 'onSave'>) { return <EditorDialog {...props} onSave={null} />; }
the_stack
import { ProjectConfig } from '../project_config'; import { DEFAULT_OPERATOR_TYPES } from '../condition_tree_evaluator'; import { Audience, Experiment, FeatureVariable, OptimizelyAttribute, OptimizelyAudience, OptimizelyEvent, OptimizelyExperiment, OptimizelyExperimentsMap, OptimizelyFeaturesMap, OptimizelyVariable, OptimizelyVariablesMap, OptimizelyVariation, Rollout, Variation, VariationVariable, } from '../../shared_types'; interface FeatureVariablesMap { [key: string]: FeatureVariable[]; } /** * The OptimizelyConfig class * @param {ProjectConfig} configObj * @param {string} datafile */ export class OptimizelyConfig { public environmentKey: string; public sdkKey: string; public revision: string; /** * This experimentsMap is for experiments of legacy projects only. * For flag projects, experiment keys are not guaranteed to be unique * across multiple flags, so this map may not include all experiments * when keys conflict. */ public experimentsMap: OptimizelyExperimentsMap; public featuresMap: OptimizelyFeaturesMap; public attributes: OptimizelyAttribute[]; public audiences: OptimizelyAudience[]; public events: OptimizelyEvent[]; private datafile: string; constructor(configObj: ProjectConfig, datafile: string) { this.sdkKey = configObj.sdkKey ?? ''; this.environmentKey = configObj.environmentKey ?? ''; this.attributes = configObj.attributes; this.audiences = OptimizelyConfig.getAudiences(configObj); this.events = configObj.events; this.revision = configObj.revision; const featureIdVariablesMap = (configObj.featureFlags || []).reduce((resultMap: FeatureVariablesMap, feature) => { resultMap[feature.id] = feature.variables; return resultMap; }, {}); const experimentsMapById = OptimizelyConfig.getExperimentsMapById(configObj, featureIdVariablesMap); this.experimentsMap = OptimizelyConfig.getExperimentsKeyMap(experimentsMapById); this.featuresMap = OptimizelyConfig.getFeaturesMap(configObj, featureIdVariablesMap, experimentsMapById); this.datafile = datafile; } /** * Get the datafile * @returns {string} JSON string representation of the datafile that was used to create the current config object */ getDatafile(): string { return this.datafile; } /** * Get Unique audiences list with typedAudiences as priority * @param {ProjectConfig} configObj * @returns {OptimizelyAudience[]} Array of unique audiences */ static getAudiences(configObj: ProjectConfig): OptimizelyAudience[] { const audiences: OptimizelyAudience[] = []; const typedAudienceIds: string[] = []; (configObj.typedAudiences || []).forEach((typedAudience) => { audiences.push({ id: typedAudience.id, conditions: JSON.stringify(typedAudience.conditions), name: typedAudience.name, }); typedAudienceIds.push(typedAudience.id); }); (configObj.audiences || []).forEach((audience) => { if (typedAudienceIds.indexOf(audience.id) === -1 && audience.id != '$opt_dummy_audience') { audiences.push({ id: audience.id, conditions: JSON.stringify(audience.conditions), name: audience.name, }); } }); return audiences; } /** * Converts list of audience conditions to serialized audiences used in experiment * for examples: * 1. Input: ["or", "1", "2"] * Output: "\"us\" OR \"female\"" * 2. Input: ["not", "1"] * Output: "NOT \"us\"" * 3. Input: ["or", "1"] * Output: "\"us\"" * 4. Input: ["and", ["or", "1", ["and", "2", "3"]], ["and", "11", ["or", "12", "13"]]] * Output: "(\"us\" OR (\"female\" AND \"adult\")) AND (\"fr\" AND (\"male\" OR \"kid\"))" * @param {Array<string | string[]>} conditions * @param {[id: string]: Audience} audiencesById * @returns {string} Serialized audiences condition string */ static getSerializedAudiences( conditions: Array<string | string[]>, audiencesById: { [id: string]: Audience } ): string { let serializedAudience = ''; if (conditions) { let cond = ''; conditions.forEach((item) => { let subAudience = ''; // Checks if item is list of conditions means it is sub audience if (item instanceof Array) { subAudience = OptimizelyConfig.getSerializedAudiences(item, audiencesById); subAudience = `(${subAudience})`; } else if (DEFAULT_OPERATOR_TYPES.indexOf(item) > -1) { cond = item.toUpperCase(); } else { // Checks if item is audience id const audienceName = audiencesById[item] ? audiencesById[item].name : item; // if audience condition is "NOT" then add "NOT" at start. Otherwise check if there is already audience id in serializedAudience then append condition between serializedAudience and item if (serializedAudience || cond === 'NOT') { cond = cond === '' ? 'OR' : cond; if (serializedAudience === '') { serializedAudience = `${cond} "${audiencesById[item].name}"`; } else { serializedAudience = serializedAudience.concat(` ${cond} "${audienceName}"`); } } else { serializedAudience = `"${audienceName}"`; } } // Checks if sub audience is empty or not if (subAudience !== '') { if (serializedAudience !== '' || cond === 'NOT') { cond = cond === '' ? 'OR' : cond; if (serializedAudience === '') { serializedAudience = `${cond} ${subAudience}`; } else { serializedAudience = serializedAudience.concat(` ${cond} ${subAudience}`); } } else { serializedAudience = serializedAudience.concat(subAudience); } } }); } return serializedAudience; } /** * Get serialized audience condition string for experiment * @param {Experiment} experiment * @param {ProjectConfig} configObj * @returns {string} Serialized audiences condition string */ static getExperimentAudiences(experiment: Experiment, configObj: ProjectConfig): string { if (!experiment.audienceConditions) { return ''; } return OptimizelyConfig.getSerializedAudiences(experiment.audienceConditions, configObj.audiencesById); } /** * Make map of featureVariable which are associated with given feature experiment * @param {FeatureVariablesMap} featureIdVariableMap * @param {[id: string]: FeatureVariable} variableIdMap * @param {string} featureId * @param {VariationVariable[] | undefined} featureVariableUsages * @param {boolean | undefined} isFeatureEnabled * @returns {OptimizelyVariablesMap} FeatureVariables mapped by key */ static mergeFeatureVariables( featureIdVariableMap: FeatureVariablesMap, variableIdMap: { [id: string]: FeatureVariable }, featureId: string, featureVariableUsages: VariationVariable[] | undefined, isFeatureEnabled: boolean | undefined ): OptimizelyVariablesMap { const variablesMap = (featureIdVariableMap[featureId] || []).reduce( (optlyVariablesMap: OptimizelyVariablesMap, featureVariable) => { optlyVariablesMap[featureVariable.key] = { id: featureVariable.id, key: featureVariable.key, type: featureVariable.type, value: featureVariable.defaultValue, }; return optlyVariablesMap; }, {} ); (featureVariableUsages || []).forEach((featureVariableUsage) => { const defaultVariable = variableIdMap[featureVariableUsage.id]; const optimizelyVariable: OptimizelyVariable = { id: featureVariableUsage.id, key: defaultVariable.key, type: defaultVariable.type, value: isFeatureEnabled ? featureVariableUsage.value : defaultVariable.defaultValue, }; variablesMap[defaultVariable.key] = optimizelyVariable; }); return variablesMap; } /** * Gets Map of all experiment variations and variables including rollouts * @param {Variation[]} variations * @param {FeatureVariablesMap} featureIdVariableMap * @param {[id: string]: FeatureVariable} variableIdMap * @param {string} featureId * @returns {[key: string]: Variation} Variations mapped by key */ static getVariationsMap( variations: Variation[], featureIdVariableMap: FeatureVariablesMap, variableIdMap: { [id: string]: FeatureVariable }, featureId: string ): { [key: string]: Variation } { let variationsMap: { [key: string]: OptimizelyVariation } = {}; variationsMap = variations.reduce((optlyVariationsMap: { [key: string]: OptimizelyVariation }, variation) => { const variablesMap = OptimizelyConfig.mergeFeatureVariables( featureIdVariableMap, variableIdMap, featureId, variation.variables, variation.featureEnabled ); optlyVariationsMap[variation.key] = { id: variation.id, key: variation.key, featureEnabled: variation.featureEnabled, variablesMap: variablesMap, }; return optlyVariationsMap; }, {}); return variationsMap; } /** * Gets Map of FeatureVariable with respect to featureVariableId * @param {ProjectConfig} configObj * @returns {[id: string]: FeatureVariable} FeatureVariables mapped by id */ static getVariableIdMap(configObj: ProjectConfig): { [id: string]: FeatureVariable } { let variablesIdMap: { [id: string]: FeatureVariable } = {}; variablesIdMap = (configObj.featureFlags || []).reduce((resultMap: { [id: string]: FeatureVariable }, feature) => { feature.variables.forEach((variable) => { resultMap[variable.id] = variable; }); return resultMap; }, {}); return variablesIdMap; } /** * Gets list of rollout experiments * @param {ProjectConfig} configObj * @param {FeatureVariablesMap} featureVariableIdMap * @param {string} featureId * @param {Experiment[]} experiments * @returns {OptimizelyExperiment[]} List of Optimizely rollout experiments */ static getDeliveryRules( configObj: ProjectConfig, featureVariableIdMap: FeatureVariablesMap, featureId: string, experiments: Experiment[] ): OptimizelyExperiment[] { const variableIdMap = OptimizelyConfig.getVariableIdMap(configObj); return experiments.map((experiment) => { return { id: experiment.id, key: experiment.key, audiences: OptimizelyConfig.getExperimentAudiences(experiment, configObj), variationsMap: OptimizelyConfig.getVariationsMap( experiment.variations, featureVariableIdMap, variableIdMap, featureId ), }; }); } /** * Get Experiment Ids which are part of rollout * @param {Rollout[]} rollouts * @returns {string[]} Array of experiment Ids */ static getRolloutExperimentIds(rollouts: Rollout[]): string[] { const experimentIds: string[] = []; (rollouts || []).forEach((rollout) => { rollout.experiments.forEach((e) => { experimentIds.push(e.id); }); }); return experimentIds; } /** * Get experiments mapped by their id's which are not part of a rollout * @param {ProjectConfig} configObj * @param {FeatureVariablesMap} featureIdVariableMap * @returns {[id: string]: OptimizelyExperiment} Experiments mapped by id */ static getExperimentsMapById( configObj: ProjectConfig, featureIdVariableMap: FeatureVariablesMap ): { [id: string]: OptimizelyExperiment } { const variableIdMap = OptimizelyConfig.getVariableIdMap(configObj); const rolloutExperimentIds = this.getRolloutExperimentIds(configObj.rollouts); const experiments = configObj.experiments; return (experiments || []).reduce((experimentsMap: { [id: string]: OptimizelyExperiment }, experiment) => { if (rolloutExperimentIds.indexOf(experiment.id) === -1) { const featureIds = configObj.experimentFeatureMap[experiment.id]; let featureId = ''; if (featureIds && featureIds.length > 0) { featureId = featureIds[0]; } const variationsMap = OptimizelyConfig.getVariationsMap( experiment.variations, featureIdVariableMap, variableIdMap, featureId.toString() ); experimentsMap[experiment.id] = { id: experiment.id, key: experiment.key, audiences: OptimizelyConfig.getExperimentAudiences(experiment, configObj), variationsMap: variationsMap, }; } return experimentsMap; }, {}); } /** * Get experiments mapped by their keys * @param {OptimizelyExperimentsMap} experimentsMapById * @returns {OptimizelyExperimentsMap} Experiments mapped by key */ static getExperimentsKeyMap(experimentsMapById: OptimizelyExperimentsMap): OptimizelyExperimentsMap { const experimentKeysMap: OptimizelyExperimentsMap = {}; for (const id in experimentsMapById) { const experiment = experimentsMapById[id]; experimentKeysMap[experiment.key] = experiment; } return experimentKeysMap; } /** * Gets Map of all FeatureFlags and associated experiment map inside it * @param {ProjectConfig} configObj * @param {FeatureVariablesMap} featureVariableIdMap * @param {OptimizelyExperimentsMap} experimentsMapById * @returns {OptimizelyFeaturesMap} OptimizelyFeature mapped by key */ static getFeaturesMap( configObj: ProjectConfig, featureVariableIdMap: FeatureVariablesMap, experimentsMapById: OptimizelyExperimentsMap ): OptimizelyFeaturesMap { const featuresMap: OptimizelyFeaturesMap = {}; configObj.featureFlags.forEach((featureFlag) => { const featureExperimentMap: OptimizelyExperimentsMap = {}; const experimentRules: OptimizelyExperiment[] = []; featureFlag.experimentIds.forEach(experimentId => { const experiment = experimentsMapById[experimentId]; if (experiment) { featureExperimentMap[experiment.key] = experiment; } experimentRules.push(experimentsMapById[experimentId]); }); const featureVariableMap = (featureFlag.variables || []).reduce((variables: OptimizelyVariablesMap, variable) => { variables[variable.key] = { id: variable.id, key: variable.key, type: variable.type, value: variable.defaultValue, }; return variables; }, {}); let deliveryRules: OptimizelyExperiment[] = []; const rollout = configObj.rolloutIdMap[featureFlag.rolloutId]; if (rollout) { deliveryRules = OptimizelyConfig.getDeliveryRules( configObj, featureVariableIdMap, featureFlag.id, rollout.experiments ); } featuresMap[featureFlag.key] = { id: featureFlag.id, key: featureFlag.key, experimentRules: experimentRules, deliveryRules: deliveryRules, experimentsMap: featureExperimentMap, variablesMap: featureVariableMap, }; }); return featuresMap; } } /** * Create an instance of OptimizelyConfig * @param {ProjectConfig} configObj * @param {string} datafile * @returns {OptimizelyConfig} An instance of OptimizelyConfig */ export function createOptimizelyConfig(configObj: ProjectConfig, datafile: string): OptimizelyConfig { return new OptimizelyConfig(configObj, datafile); }
the_stack
import { IField } from "@esri/arcgis-rest-types"; export const cvdServiceFields: IField[] = [ { name: "objectid", type: "esriFieldTypeOID", alias: "OBJECTID", domain: null, editable: false, nullable: false }, { name: "requestid", type: "esriFieldTypeString", alias: "Service Request ID", domain: null, editable: true, nullable: true, length: 25 }, { name: "requesttype", type: "esriFieldTypeString", alias: "Problem", domain: { type: "codedValue", name: "ServiceRequestType", description: "The type of service request submitted by general public", codedValues: [ { name: "Blight", code: 0 }, { name: "Bridge Impassible", code: 1 }, { name: "Business Closed", code: 2 } ], mergePolicy: "esriMPTDefaultValue", splitPolicy: "esriSPTDefaultValue" }, editable: true, nullable: true, length: 100 }, { name: "name", type: "esriFieldTypeString", alias: "Name", domain: null, editable: true, nullable: true, length: 150 }, { name: "phone", type: "esriFieldTypeString", alias: "Phone Number", domain: null, editable: true, nullable: true, length: 12 }, { name: "email", type: "esriFieldTypeString", alias: "Email Address", domain: null, editable: true, nullable: true, length: 100 }, { name: "requestdate", type: "esriFieldTypeDate", alias: "Date Submitted", domain: null, editable: true, nullable: true, length: 8 }, { name: "status", type: "esriFieldTypeString", alias: "Status", domain: { type: "codedValue", name: "ServiceRequestStatus", description: "The status of the resolution of a service request", codedValues: [ { name: "Unassigned", code: "Unassigned" }, { name: "Assigned", code: "Assigned" }, { name: "Closed", code: "Closed" } ], mergePolicy: "esriMPTDefaultValue", splitPolicy: "esriSPTDefaultValue" }, editable: true, nullable: true, length: 50 }, { name: "globalid", type: "esriFieldTypeGlobalID", alias: "GlobalID", domain: null, editable: false, nullable: false, length: 38 }, { name: "building", type: "esriFieldTypeString", alias: "Building Name", domain: null, editable: true, nullable: true, length: 25 }, { name: "floor", type: "esriFieldTypeString", alias: "Floor Number", domain: null, editable: true, nullable: true, length: 5 } ]; export const serviceFields: IField[] = [ { name: "FID", type: "esriFieldTypeOID", // "actualType" : "int", alias: "FID", // "sqlType" : "sqlTypeInteger", nullable: false, editable: false, domain: null, defaultValue: null }, { name: "Tree_ID", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "Tree_ID", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Collected", type: "esriFieldTypeDate", // "actualType" : "datetime2", alias: "Collected", // "sqlType" : "sqlTypeTimestamp2", length: 8, nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Crew", type: "esriFieldTypeString", // "actualType" : "nvarchar", alias: "Crew", // "sqlType" : "sqlTypeNVarchar", length: 254, nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Status", type: "esriFieldTypeString", // "actualType" : "nvarchar", alias: "Status", // "sqlType" : "sqlTypeNVarchar", length: 254, nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Spp_Code", type: "esriFieldTypeString", // "actualType" : "nvarchar", alias: "Spp_Code", // "sqlType" : "sqlTypeNVarchar", length: 254, nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Land_Use", type: "esriFieldTypeString", // "actualType" : "nvarchar", alias: "Land_Use", // "sqlType" : "sqlTypeNVarchar", length: 254, nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Ht_DBH_ft", type: "esriFieldTypeDouble", // "actualType" : "float", alias: "Ht_DBH_ft", // "sqlType" : "sqlTypeFloat", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "DBH1", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "DBH1", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "DBH2", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "DBH2", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "DBH3", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "DBH3", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "DBH4", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "DBH4", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "DBH5", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "DBH5", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "DBH6", type: "esriFieldTypeString", // "actualType" : "nvarchar", alias: "DBH6", // "sqlType" : "sqlTypeNVarchar", length: 254, nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Height", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "Height", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Live_Top", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "Live_Top", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Crown_Base", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "Crown_Base", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Width_NS", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "Width_NS", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Width_EW", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "Width_EW", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Cn_Missing", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "Cn_Missing", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Cn_DieBack", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "Cn_DieBack", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "CLE", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "CLE", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Tree_Site", type: "esriFieldTypeString", // "actualType" : "nvarchar", alias: "Tree_Site", // "sqlType" : "sqlTypeNVarchar", length: 254, nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Tree_Age", type: "esriFieldTypeString", // "actualType" : "nvarchar", alias: "Tree_Age", // "sqlType" : "sqlTypeNVarchar", length: 254, nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Notes", type: "esriFieldTypeString", // "actualType" : "nvarchar", alias: "Notes", // "sqlType" : "sqlTypeNVarchar", length: 254, nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Cmn_Name", type: "esriFieldTypeString", // "actualType" : "nvarchar", alias: "Cmn_Name", // "sqlType" : "sqlTypeNVarchar", length: 254, nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Sci_Name", type: "esriFieldTypeString", // "actualType" : "nvarchar", alias: "Sci_Name", // "sqlType" : "sqlTypeNVarchar", length: 254, nullable: true, editable: true, domain: null, defaultValue: null }, { name: "GroundArea", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "GroundArea", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Condition", type: "esriFieldTypeString", // "actualType" : "nvarchar", alias: "Condition", // "sqlType" : "sqlTypeNVarchar", length: 254, nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Leaf_Area", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "Leaf_Area", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Leaf_Bmass", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "Leaf_Bmass", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "LAI", type: "esriFieldTypeDouble", // "actualType" : "float", alias: "LAI", // "sqlType" : "sqlTypeFloat", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "C_Storage", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "C_Storage", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "C_Seq", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "C_Seq", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "S_Value", type: "esriFieldTypeString", // "actualType" : "nvarchar", alias: "S_Value", // "sqlType" : "sqlTypeNVarchar", length: 254, nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Street", type: "esriFieldTypeString", // "actualType" : "nvarchar", alias: "Street", // "sqlType" : "sqlTypeNVarchar", length: 254, nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Native", type: "esriFieldTypeString", // "actualType" : "nvarchar", alias: "Native", // "sqlType" : "sqlTypeNVarchar", length: 254, nullable: true, editable: true, domain: null, defaultValue: null }, { name: "CO_Rmvd", type: "esriFieldTypeDouble", // "actualType" : "float", alias: "CO_Rmvd", // "sqlType" : "sqlTypeFloat", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "O3_Rmvd", type: "esriFieldTypeDouble", // "actualType" : "float", alias: "O3_Rmvd", // "sqlType" : "sqlTypeFloat", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "NO2_Rmvd", type: "esriFieldTypeDouble", // "actualType" : "float", alias: "NO2_Rmvd", // "sqlType" : "sqlTypeFloat", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "PM10_Rmvd", type: "esriFieldTypeDouble", // "actualType" : "float", alias: "PM10_Rmvd", // "sqlType" : "sqlTypeFloat", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "SO2_Rmvd", type: "esriFieldTypeDouble", // "actualType" : "float", alias: "SO2_Rmvd", // "sqlType" : "sqlTypeFloat", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "PM2p5_Rmvd", type: "esriFieldTypeDouble", // "actualType" : "float", alias: "PM2p5_Rmvd", // "sqlType" : "sqlTypeFloat", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "CO_RVlu", type: "esriFieldTypeDouble", // "actualType" : "float", alias: "CO_RVlu", // "sqlType" : "sqlTypeFloat", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "O3_Rvlu", type: "esriFieldTypeDouble", // "actualType" : "float", alias: "O3_Rvlu", // "sqlType" : "sqlTypeFloat", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "NO2_Rvlu", type: "esriFieldTypeDouble", // "actualType" : "float", alias: "NO2_Rvlu", // "sqlType" : "sqlTypeFloat", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "PM10_Rvlu", type: "esriFieldTypeDouble", // "actualType" : "float", alias: "PM10_Rvlu", // "sqlType" : "sqlTypeFloat", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "SO2_Rvlu", type: "esriFieldTypeInteger", // "actualType" : "int", alias: "SO2_Rvlu", // "sqlType" : "sqlTypeInteger", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "PM2p5_RVlu", type: "esriFieldTypeDouble", // "actualType" : "float", alias: "PM2p5_RVlu", // "sqlType" : "sqlTypeFloat", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Isoprene_E", type: "esriFieldTypeDouble", // "actualType" : "float", alias: "Isoprene_E", // "sqlType" : "sqlTypeFloat", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Monoterp_E", type: "esriFieldTypeDouble", // "actualType" : "float", alias: "Monoterp_E", // "sqlType" : "sqlTypeFloat", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Vocs_E", type: "esriFieldTypeDouble", // "actualType" : "float", alias: "Vocs_E", // "sqlType" : "sqlTypeFloat", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Dedication", type: "esriFieldTypeString", // "actualType" : "nvarchar", alias: "Dedication", // "sqlType" : "sqlTypeNVarchar", length: 254, nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Longitude", type: "esriFieldTypeDouble", // "actualType" : "float", alias: "Longitude", // "sqlType" : "sqlTypeFloat", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Latitude", type: "esriFieldTypeDouble", // "actualType" : "float", alias: "Latitude", // "sqlType" : "sqlTypeFloat", nullable: true, editable: true, domain: null, defaultValue: null }, { name: "Crown_Height", type: "esriFieldTypeDouble", alias: "", // "sqlType" : "sqlTypeOther", nullable: true, editable: true, domain: null, defaultValue: null } ];
the_stack
import * as fs from 'fs-extra'; import * as http from 'http'; import { commandLineOptions } from '../src/command-line.ts'; import { start, stop, clients, wsServer } from '../src/zwitterion.ts'; import * as WebSocket from 'ws'; import * as fc from 'fast-check'; import * as uuid from 'uuid'; import { exec } from 'child_process'; (async () => { await start({ httpPort: commandLineOptions.httpPort, wsPort: commandLineOptions.wsPort, watchFiles: commandLineOptions.watchFiles, disableSpa: commandLineOptions.disableSpa, customHTTPHeadersFilePath: commandLineOptions.customHTTPHeadersFilePath, ascOptionsFilePath: commandLineOptions.ascOptionsFilePath, tscOptionsFilePath: commandLineOptions.tscOptionsFilePath }); const testDescriptions: ReadonlyArray<TestDescription> = [ ...prepareJavaScriptTestDescriptions(), ...prepareTypeScriptTestDescriptions(), ...prepareJSONTestDescriptions(), ...prepareJSXTestDescriptions(), ...prepareTSXTestDescriptions(), ...prepareAssemblyScriptTestDescriptions(), ...(process.env.CI === 'true' ? [] : prepareRustTestDescriptions()), // TODO no remote tests until we can install rustc with npm ...(process.env.CI === 'true' ? [] : prepareCTestDescriptions()), // TODO no remote tests until we can install emscripten with npm ...(process.env.CI === 'true' ? [] : prepareCPPTestDescriptions()), // TODO no remote tests until we can install emscripten with npm ...prepareWatTestDescriptions() ]; const topLevelTestDescriptions: ReadonlyArray<TestDescription> = testDescriptions.filter((testDescription: Readonly<TestDescription>) => { return testDescription.topLevel === true; }); const indexFileContents: string = ` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <script type="module"> if (self.ZWITTERION_SOCKET.readyState !== 1) { self.ZWITTERION_SOCKET.addEventListener('open', () => { self.ZWITTERION_SOCKET.send('STARTING_TESTS'); }); } else { self.ZWITTERION_SOCKET.send('STARTING_TESTS'); } ${topLevelTestDescriptions.map((testDescription: Readonly<TestDescription>) => { return `import * as ${testDescription.id} from './${testDescription.moduleName}';\n`; }).join('')} (async () => { ${topLevelTestDescriptions.map((testDescription: Readonly<TestDescription>) => { return `await ${testDescription.id}.resultPromise();\n`; }).join('')} if (self.ZWITTERION_SOCKET.readyState !== 1) { self.ZWITTERION_SOCKET.addEventListener('open', () => { sendMessage(); }); } else { sendMessage(); } function sendMessage() { self.ZWITTERION_SOCKET.send('ALL_TESTS_PASSED'); console.log('ALL_TESTS_PASSED'); } })(); </script> </body> </html> `; fs.writeFileSync('./index.html', indexFileContents); testDescriptions.forEach((testDescription: Readonly<TestDescription>) => { fs.writeFileSync(`./${testDescription.moduleName}`, testDescription.moduleContents); }); const browserCommands: { [key: string]: { [key: string]: string; }; } = { 'chrome': { 'ubuntu-latest': `google-chrome --headless --disable-gpu --remote-debugging-port=7777 http://localhost:${commandLineOptions.httpPort}`, 'macos-latest': `/Applications/Google\\ Chrome.app/Contents/MacOS/Google\\ Chrome --headless --disable-gpu --remote-debugging-port=7777 http://localhost:${commandLineOptions.httpPort}`, 'windows-latest': `start chrome --headless --disable-gpu --remote-debugging-port=7777 http://localhost:${commandLineOptions.httpPort}` }, 'firefox': { 'ubuntu-latest': `firefox --headless http://localhost:${commandLineOptions.httpPort}`, 'macos-latest': `/Applications/Firefox.app/Contents/MacOS/firefox --headless http://localhost:${commandLineOptions.httpPort}`, 'windows-latest': `start firefox --headless http://localhost:${commandLineOptions.httpPort}` } }; if ( process.env.CI === 'true' && process.env.OS === undefined ) { throw new Error('process.env.OS is not defined'); } if ( process.env.CI === 'true' && process.env.BROWSER === undefined ) { throw new Error('process.env.BROWSER is not defined'); } const childProcess = process.env.CI === 'true' ? exec(browserCommands[process.env.BROWSER || ''][process.env.OS || '']) : { kill: () => {}, stdout: { on: () => {} }, stderr: { on: () => {} } }; childProcess.stdout?.on('data', (data) => { console.log(data); }); childProcess.stderr?.on('data', (data) => { console.log(data); }); const timeoutId: NodeJS.Timeout = setTimeout(() => { console.log('timeout reached'); process.exit(1); }, 60000); if (wsServer !== 'NOT_CREATED') { wsServer.on('connection', (client: Readonly<WebSocket>, request: Readonly<http.IncomingMessage>) => { if (request.connection.remoteAddress !== undefined) { client.on('message', (data: Readonly<WebSocket.Data>) => { console.log('data', data); if (data.toString().includes('ALL_TESTS_PASSED')) { clearTimeout(timeoutId); testDescriptions.forEach((testDescription: Readonly<TestDescription>) => { fs.removeSync(testDescription.moduleName); }); fs.removeSync('./index.html'); if (process.env.CI === 'true') { childProcess.kill('SIGINT'); process.exit(0); } } }); } }); } })(); type TestDescription = { readonly id: string; readonly topLevel: boolean; readonly moduleName: string; readonly moduleContents: string; }; function prepareJavaScriptTestDescriptions(): ReadonlyArray<TestDescription> { return [ { id: getRandomId(), topLevel: true, moduleName: 'test-module.js', moduleContents: ` const arbNumber = 5; console.log(arbNumber); export const resultPromise = async () => { }; ` } ]; } function prepareTypeScriptTestDescriptions(): ReadonlyArray<TestDescription> { return [ { id: getRandomId(), topLevel: true, moduleName: 'test-module.ts', moduleContents: ` const arbNumber: number = 5; console.log(arbNumber); export const resultPromise = async () => { }; ` } ]; } function prepareJSONTestDescriptions(): ReadonlyArray<TestDescription> { return [ { id: getRandomId(), topLevel: true, moduleName: 'test-json-module.js', moduleContents: ` import helloWorld from './test-module.json' export const resultPromise = async () => { console.log(helloWorld); }; ` }, { id: getRandomId(), topLevel: false, moduleName: 'test-module.json', moduleContents: ` { "hello": "world" } ` } ]; } function prepareJSXTestDescriptions(): ReadonlyArray<TestDescription> { return [ { id: getRandomId(), topLevel: true, moduleName: 'test-module.jsx', moduleContents: ` const arbNumber = 5; console.log(arbNumber); const React = { createElement: () => {} }; <div /> export const resultPromise = async () => { }; ` } ]; } function prepareTSXTestDescriptions(): ReadonlyArray<TestDescription> { return [ { id: getRandomId(), topLevel: true, moduleName: 'test-module.tsx', moduleContents: ` const arbNumber: number = 5; console.log(arbNumber); const React = { createElement: () => {} }; <div /> export const resultPromise = async () => { }; ` } ]; } function prepareAssemblyScriptTestDescriptions(): ReadonlyArray<TestDescription> { return [ { id: getRandomId(), topLevel: true, moduleName: `test-as-module.ts`, moduleContents: ` import testModuleInit from './test-module.as'; export const resultPromise = async () => { const testModule = await testModuleInit(); console.log(testModule.add(1, 1)); }; ` }, { id: getRandomId(), topLevel: false, moduleName: 'test-module.as', moduleContents: ` export function add(x: i32, y: i32): i32 { return x + y; } ` } ]; } function prepareRustTestDescriptions(): ReadonlyArray<TestDescription> { return [ { id: getRandomId(), topLevel: true, moduleName: `test-rs-module.ts`, moduleContents: ` import testModuleInit from './test-module.rs'; export const resultPromise = async () => { const testModule = await testModuleInit(); console.log(testModule.add(1, 1)); }; ` }, { id: getRandomId(), topLevel: false, moduleName: 'test-module.rs', moduleContents: ` #![no_main] #[no_mangle] fn add(x: i32, y: i32) -> i32 { return x + y; } ` } ]; } function prepareCTestDescriptions(): ReadonlyArray<TestDescription> { return [ { id: getRandomId(), topLevel: true, moduleName: `test-c-module.ts`, moduleContents: ` import testModuleInit from './test-module.c'; export const resultPromise = async () => { const testModule = await testModuleInit(); console.log(testModule.add(1, 1)); }; ` }, { id: getRandomId(), topLevel: false, moduleName: 'test-module.c', moduleContents: ` int add(int x, int y) { return x + y; } ` } ]; } function prepareCPPTestDescriptions(): ReadonlyArray<TestDescription> { return [ { id: getRandomId(), topLevel: true, moduleName: `test-cpp-module.ts`, moduleContents: ` import testModule1Init from './test-module.cpp'; import testModule2Init from './test-module.c++'; import testModule3Init from './test-module.cc'; export const resultPromise = async () => { const testModule1 = await testModule1Init(); const testModule2 = await testModule2Init(); const testModule3 = await testModule3Init(); console.log(testModule1.add(1, 1)); console.log(testModule2.add(1, 1)); console.log(testModule3.add(1, 1)); }; ` }, { id: getRandomId(), topLevel: false, moduleName: 'test-module.cpp', moduleContents: ` extern "C" { int add(int x, int y) { return x + y; } } ` }, { id: getRandomId(), topLevel: false, moduleName: 'test-module.c++', moduleContents: ` extern "C" { int add(int x, int y) { return x + y; } } ` }, { id: getRandomId(), topLevel: false, moduleName: 'test-module.cc', moduleContents: ` extern "C" { int add(int x, int y) { return x + y; } } ` } ]; } function prepareWatTestDescriptions(): ReadonlyArray<TestDescription> { return [ { id: getRandomId(), topLevel: true, moduleName: `test-wat-module.ts`, moduleContents: ` import testModuleInit from './test-module.wat'; export const resultPromise = async () => { const testModule = await testModuleInit(); console.log(testModule.add(1, 1)); }; ` }, { id: getRandomId(), topLevel: false, moduleName: 'test-module.wat', moduleContents: ` (module (func $add (param $x i32) (param $y i32) (result i32) (i32.add (get_local $x) (get_local $y)) ) (export "add" (func $add)) ) ` } ]; } function getRandomId(): string { return `module${uuid.v1().replace(/-/g, '')}`; }
the_stack
import React from "react"; import {render, fireEvent, waitForElement} from "@testing-library/react"; import {entitySearch, entityPropertyDefinitions, selectedPropertyDefinitions, entityDefArray, entitySearchAllEntities} from "../../assets/mock-data/explore/entity-search"; import ResultsTabularView from "./results-tabular-view"; import {BrowserRouter as Router} from "react-router-dom"; import {validateTableRow} from "../../util/test-utils"; import moment from "moment"; describe("Results Table view component", () => { test("Results table with data renders", async () => { const {getByText, getByTestId} = render( <Router> <ResultsTabularView data={entitySearch.results} entityPropertyDefinitions={entityPropertyDefinitions} selectedPropertyDefinitions={selectedPropertyDefinitions} entityDefArray={entityDefArray} columns={[]} hasStructured={false} selectedEntities={["Customer"]} /> </Router> ); // Check table column headers are rendered expect(getByText("customerId")).toBeInTheDocument(); expect(getByText("name")).toBeInTheDocument(); expect(getByText("nicknames")).toBeInTheDocument(); expect(getByText("shipping")).toBeInTheDocument(); expect(getByText("billing")).toBeInTheDocument(); expect(getByText("Detail View")).toBeInTheDocument(); //check table data is rendered correctly expect(getByText("101")).toBeInTheDocument(); expect(getByText("Carmella Hardin")).toBeInTheDocument(); expect(getByText("Whitwell Place")).toBeInTheDocument(); expect(getByText("Whitwell Place2")).toBeInTheDocument(); expect(getByText("Ellerslie")).toBeInTheDocument(); expect(getByText("Ellerslie2")).toBeInTheDocument(); expect(getByTestId("101-detailOnSeparatePage")).toBeInTheDocument(); expect(getByTestId("101-sourceOnSeparatePage")).toBeInTheDocument(); expect(getByText("\"\"")).toBeInTheDocument(); expect(getByText("null")).toBeInTheDocument(); //Check if the tooltip on 'Detail on separate page' icon works fine. fireEvent.mouseOver(getByTestId("101-detailOnSeparatePage")); await(waitForElement(() => (getByText("Show the processed data")))); //Check if the tooltip on 'source on separate page' icon works fine. fireEvent.mouseOver(getByTestId("101-sourceOnSeparatePage")); await(waitForElement(() => (getByText("Show the complete JSON")))); }); test("Result table with no data renders", () => { const {getByText} = render( <Router> <ResultsTabularView data={[]} entityPropertyDefinitions={[]} selectedPropertyDefinitions={[]} entityDefArray={[]} columns={[]} hasStructured={false} /> </Router> ); // Check for Empty Table expect(getByText(/No Data/i)).toBeInTheDocument(); }); test("Array data renders properly", () => { const {getByText, queryByText} = render( <Router> <ResultsTabularView data={entitySearch.results} entityPropertyDefinitions={entityPropertyDefinitions} selectedPropertyDefinitions={selectedPropertyDefinitions} columns={[]} hasStructured={false} selectedEntities={["Customer"]} entityDefArray={entityDefArray} /> </Router> ); expect(queryByText("Carmdin")).toBeNull(); expect(queryByText("Carm din")).toBeNull(); expect(getByText("Carm")).toBeInTheDocument(); expect(getByText("din")).toBeInTheDocument(); expect(getByText("Carm")).toContainHTML("class=\"ml-tooltip-container\""); expect(getByText("Carm")).toContainHTML("style=\"text-overflow: ellipsis; overflow: hidden;\""); expect(getByText("din")).toContainHTML("class=\"ml-tooltip-container\""); expect(getByText("din")).toContainHTML("style=\"text-overflow: ellipsis; overflow: hidden;\""); expect(getByText("Carm").closest("td")).toEqual(getByText("din").closest("td")); expect(getByText("Carm").closest("td")).toEqual(getByText("din").closest("td")); }); test("Results table with data renders when All Entities option is selected", async () => { const {getByText, getByTestId} = render( <Router> <ResultsTabularView data={entitySearchAllEntities.results} entityPropertyDefinitions={[]} selectedPropertyDefinitions={[]} entityDefArray={entityDefArray} columns={[]} hasStructured={false} selectedEntities={[]} /> </Router> ); // Check table column headers are rendered expect(getByText("Identifier")).toBeInTheDocument(); expect(getByText("Entity Type")).toBeInTheDocument(); expect(getByText("Record Type")).toBeInTheDocument(); expect(getByText("Created")).toBeInTheDocument(); expect(getByText("Detail View")).toBeInTheDocument(); //check table data is rendered correctly expect(getByText("101")).toBeInTheDocument(); expect(getByTestId("Customer-101")).toBeInTheDocument(); expect(getByTestId("json-101")).toBeInTheDocument(); let ts: string = entitySearchAllEntities.results[0].createdOn; // "2020-06-21T23:44:46.225063-07:00" let tsExpected: string = moment(ts).format("YYYY-MM-DD HH:mm"); expect(getByText(tsExpected)).toBeInTheDocument(); // "2020-06-21 23:44" expect(getByTestId("101-detailOnSeparatePage")).toBeInTheDocument(); expect(getByTestId("101-sourceOnSeparatePage")).toBeInTheDocument(); //Check if the tooltip on 'Detail on separate page' icon works fine. fireEvent.mouseOver(getByTestId("101-detailOnSeparatePage")); await(waitForElement(() => (getByText("Show the processed data")))); //Check if the tooltip on 'source on separate page' icon works fine. fireEvent.mouseOver(getByTestId("101-sourceOnSeparatePage")); await(waitForElement(() => (getByText("Show the complete JSON")))); }); test("Sorting in results table with data renders properly", async () => { const {getByText, getByTestId} = render( <Router> <ResultsTabularView data={entitySearch.results} entityPropertyDefinitions={entityPropertyDefinitions} selectedPropertyDefinitions={selectedPropertyDefinitions} entityDefArray={entityDefArray} columns={[]} hasStructured={false} selectedEntities={["Customer"]} /> </Router> ); // Check table column headers are rendered expect(getByText("customerId")).toBeInTheDocument(); expect(getByText("name")).toBeInTheDocument(); expect(getByText("nicknames")).toBeInTheDocument(); expect(getByText("shipping")).toBeInTheDocument(); expect(getByText("billing")).toBeInTheDocument(); expect(getByText("Detail View")).toBeInTheDocument(); const customerIdColumnSort = getByTestId("resultsTableColumn-customerId"); // For name column sorting const nameColumnSort = getByTestId("resultsTableColumn-name"); // For value column sorting const nickNamesColumnSort = getByTestId("resultsTableColumn-nicknames"); // For nicknames column sorting //Sorted document uris based on name,customerId and nicknames columns to be used later const urisDefault = ["/Customer/Cust1.json", "/Customer/Cust2.json", "/Customer/Cust3.json", "/Customer/Cust4.json", "/Customer/Cust5.json"]; const urisBasedOnDescendingCustomerId = ["/Customer/Cust5.json", "/Customer/Cust2.json", "/Customer/Cust3.json", "/Customer/Cust4.json", "/Customer/Cust5.json"]; const urisBasedOnAscendingName = ["/Customer/Cust2.json", "/Customer/Cust3.json", "/Customer/Cust1.json", "/Customer/Cust5.json", "/Customer/Cust4.json"]; const urisBasedOnDescendingName = ["/Customer/Cust4.json", "/Customer/Cust5.json", "/Customer/Cust1.json", "/Customer/Cust3.json", "/Customer/Cust2.json"]; const urisBasedOnAscendingNickNames = ["/Customer/Cust2.json", "/Customer/Cust3.json", "/Customer/Cust1.json", "/Customer/Cust5.json", "/Customer/Cust4.json"]; const urisBasedOnDescendingNickNames = ["/Customer/Cust4.json", "/Customer/Cust5.json", "/Customer/Cust1.json", "/Customer/Cust2.json", "/Customer/Cust3.json"]; /* Validate sorting on name column in results*/ //Check the sort order of Name column rows before enforcing sort order let resultsTable: any = document.querySelectorAll(".ant-table-row ant-table-row-level-0"); validateTableRow(resultsTable, urisDefault); //Click on the Name column to sort the rows by Ascending order fireEvent.click(nameColumnSort); resultsTable = document.querySelectorAll(".ant-table-row ant-table-row-level-0"); validateTableRow(resultsTable, urisBasedOnAscendingName); //Click on the Name column to sort the rows by Descending order fireEvent.click(nameColumnSort); resultsTable = document.querySelectorAll(".ant-table-row ant-table-row-level-0"); validateTableRow(resultsTable, urisBasedOnDescendingName); /* Validate sorting on customerId column in results*/ //Click on the CustomerId column to sort the rows by Ascending order fireEvent.click(customerIdColumnSort); resultsTable = document.querySelectorAll(".ant-table-row ant-table-row-level-0"); validateTableRow(resultsTable, urisDefault); //Click on the CustomerId column to sort the rows by Descending order fireEvent.click(customerIdColumnSort); resultsTable = document.querySelectorAll(".ant-table-row ant-table-row-level-0"); validateTableRow(resultsTable, urisBasedOnDescendingCustomerId); /* Validate sorting on nicknames column in results*/ //Click on the nicknames column to sort the rows by Ascending order fireEvent.click(nickNamesColumnSort); resultsTable = document.querySelectorAll(".ant-table-row ant-table-row-level-0"); validateTableRow(resultsTable, urisBasedOnAscendingNickNames); //Click on the nicknames column to sort the rows by Descending order fireEvent.click(nickNamesColumnSort); resultsTable = document.querySelectorAll(".ant-table-row ant-table-row-level-0"); validateTableRow(resultsTable, urisBasedOnDescendingNickNames); }); test("Results table with no data renders when All Entities option is selected but no entities are available", async () => { const {getByText} = render( <Router> <ResultsTabularView data={[]} entityPropertyDefinitions={[]} selectedPropertyDefinitions={[]} entityDefArray={[]} columns={[]} hasStructured={false} selectedEntities={[]} /> </Router> ); // Check table column headers are rendered expect(getByText("Identifier")).toBeInTheDocument(); expect(getByText("Entity Type")).toBeInTheDocument(); expect(getByText("Record Type")).toBeInTheDocument(); expect(getByText("Created")).toBeInTheDocument(); expect(getByText("Detail View")).toBeInTheDocument(); // Check for Empty Table expect(getByText(/No Data/i)).toBeInTheDocument(); }); });
the_stack
// WARNING THIS FILE IS AUTOGENERATED! DO NOT EDIT! // Developer note: these files are treated as templates and called from prebuild.js // They shouldn't be imported and used directly. import React from 'react'; import { Link } from 'gatsby'; import onChangeGenerator from '../../commons/onChangeGenerator'; import P from '@govtnz/ds/build/react-ts/P'; import '../../commons/styles/ds/themed-P.scss'; import H2 from '@govtnz/ds/build/react-ts/H2'; import '../../commons/styles/ds/themed-H2.scss'; import Ul from '@govtnz/ds/build/react-ts/Ul'; import '../../commons/styles/ds/themed-Ul.scss'; import Li from '@govtnz/ds/build/react-ts/Li'; import '../../commons/styles/ds/themed-Li.scss'; import A from '@govtnz/ds/build/react-ts/A'; import '../../commons/styles/ds/themed-A.scss'; import components__Alerts from '../../commons/examples/components__Alerts'; // Indirect relative import because this template is output to src/pages/components so it needs to step back to `commons`. import ComponentPage from '../../commons/component-page'; import ComponentCode from '../../commons/component-code'; import Example from '../../commons/Example'; import ExampleContainer from '../../commons/ExampleContainer'; import ExampleHeading from '../../commons/ExampleHeading'; import ExampleSection from '../../commons/ExampleSection'; import MainNavMobileMenuContext from '../../commons/MainNavMobileMenuContext'; import '../../commons/styles/ds/themed-Button.scss'; import '../../commons/styles/ds/themed-CaptionL.scss'; const PageContent = (props) => <React.Fragment><P styleSize="large">Page alerts attract users’ attention to important information or changes on a page.</P> <H2 styleSize="large" id="when-to-use-it">When to use it</H2> <P>Use the page alerts component to inform users of:</P> <Ul> <Li>important information</Li> <Li>changes on a page</Li> <Li>successful or unsuccessful completion of a task.</Li> </Ul> <P>They should be relevant and as minimally disruptive as possible.</P> <h2 id="when-not-to-use-it">When not to use it</h2> <P>Page alerts should be used sparingly. If used too frequently, they can create a disruptive experience for users. Overuse may also lead to users becoming desensitised to the alerts and missing or ignoring important information.</P> <P>The page alerts component should not be used for site or system-wide alerts. Its role is to notify users on important information or changes on a page, rather than site or system-wide changes.</P> <P>Site and system-wide alerts will be developed as part of the banner component during the Design System’s beta phase.</P> <h2 id="how-it-works">How it works</h2> <P>All alerts use a colour and icon that corresponds with their message intent. The alert type — information, warning, success, or error — is communicated to all users by:</P> <Ul> <Li>the visual appearance, including the icon and colour</Li> <Li>the first word of the alert&#39;s heading, for example, ‘Warning’.</Li> </Ul> <P>Changing the word at the start of the alert heading, or removing it, could make the alert less understandable, and therefore less accessible, to some users. If the type or strength of the alert is not indicated in text or in some other way for assistive technology users, it will also fail the <A className="g-link" href="https://www.digital.govt.nz/web-accessibility-standard/">NZ Government Web Accessibility Standard</A>.</P> <P>Success and error summary alert messages appear at the top of a page following a submit action. They should give users clear, descriptive next steps.</P> <P>Information and warning alert messages can appear at the top of the page or in the body of the content. If used in the body, alert messages should appear next to the content they relate to.</P> <h3 id="static-alerts">Static alerts</h3> <P>Static alerts are added as part of a new page or view after a <A className="g-link" href="https://www.w3.org/TR/WCAG21/#dfn-change-of-context">change of context</A>, such as following a link or submitting a form. These are considered static because they remain unchanged unless there is another change of context.</P> <P>Information and warning alerts can be used in a wide range of scenarios. Success and error summary alerts are only ever used following a form submission, which is a change of context for the user. These alerts will always be static and part of a new page or view when it is loaded.</P> <P>Additionally, when the new page or view is first loaded, the Design System user must ensure that focus is moved to the success or error summary alert. This will cause it to be announced automatically by screen reader software, letting the user know the status of their form submission and what, if anything, they need to do to continue.</P> <P>The Design System user should also update the <code>title</code> element to start with &quot;Success:&quot; or &quot;Error:&quot; so that the feedback is provided in the page’s name.</P> <h3 id="live-alerts">Live alerts</h3> <P>Live alerts are dynamically inserted into an existing page or view as an immediate response to a user’s action, such as checking a checkbox. They’re used where the change to the page’s content is not significant enough to constitute a change of context.</P> <P>When implemented as a live alert, the alert container needs to be empty and present in the document object model (DOM) when the page or view is first loaded. The actual alert message is then dynamically inserted into the container following whatever user action triggers the alert.</P> <P>To ensure that screen reader users are notified of a live alert, the alert container is marked up as a <A className="g-link" href="https://w3c.github.io/aria/#dfn-live-region">live region</A>. When content is dynamically inserted in a live region container, that content is automatically announced to the user by the screen reader.</P> <P>Success and error summary alerts are not intended to be used as live alerts. Since they always follow form submission, which is a change of context, they are always static. However, if they are used as live alerts, they should be tested for accessibility. Also, as live alerts are already announced automatically to screen reader users, the alert should not receive focus.</P> <h2 id="information">Information</h2> <P>Use information alerts to inform users of important information or changes on a page only. They should be used sparingly.</P> <ExampleContainer> <ExampleHeading level={3}>Information alert: Static</ExampleHeading> <Example code={components__Alerts[0]} iframeProps={{ id:"iframe_componentsAlerts0", className: "example__iframe", src:"/components/Alerts__example0.html", title:"Example title: Info alert: Static", height: 246 }}></Example> </ExampleContainer> <ExampleContainer> <ExampleHeading level={3}>Information alert: Live</ExampleHeading> <Example code={components__Alerts[1]} iframeProps={{ id:"iframe_componentsAlerts1", className: "example__iframe", src:"/components/Alerts__example1.html", title:"Example title: Information alert: Live", height: 167 }}></Example> </ExampleContainer> <h2 id="warning">Warning</h2> <P>Use warning alerts to tell users something urgent. Only use this alert if the information will help users avoid a problem.</P> <ExampleContainer> <ExampleHeading level={3}>Warning alert: Static</ExampleHeading> <Example code={components__Alerts[2]} iframeProps={{ id:"iframe_componentsAlerts2", className: "example__iframe", src:"/components/Alerts__example2.html", title:"Example title: Warning alert: Static", height: 214 }}></Example> </ExampleContainer> <ExampleContainer> <ExampleHeading level={3}>Warning alert: Live</ExampleHeading> <Example code={components__Alerts[3]} iframeProps={{ id:"iframe_componentsAlerts3", className: "example__iframe", src:"/components/Alerts__example3.html", title:"Example title: Warning alert: Live", height: 167 }}></Example> </ExampleContainer> <h2 id="success">Success</h2> <P>Use success alerts to notify users that a form submission has completed successfully.</P> <P>Success alerts are always static, as they are included as part of a new page or view, and remain unchanged until the user initiates a change of context.</P> <P>To orient screen reader users and others to the alert, the Design System user must ensure that when the page or view first loads:</P> <Ul> <Li>focus is moved to the alert (the alert container is preset with <code>tabindex=”-1”</code> to make it programmatically focusable)</Li> <Li>the document’s <code>title</code> starts with &quot;Success:&quot;.</Li> </Ul> <ExampleContainer> <ExampleHeading level={3}>Success alert</ExampleHeading> <Example code={components__Alerts[4]} iframeProps={{ id:"iframe_componentsAlerts4", className: "example__iframe", src:"/components/Alerts__example4.html", title:"Example: Alerts (static)", height: 214 }}></Example> </ExampleContainer> <h2 id="error-summary">Error summary</h2> <P>Use the error summary alert to inform users of every error they need to correct in a form before they can move on to the next step or complete their task.</P> <P>Form errors must be presented using:</P> <Ul> <Li>the error summary alert</Li> <Li>individual error messages next to each form field with an error.</Li> </Ul> <P>The error summary should be added at the top of the page above the form and link to each form field that has an error.</P> <P>Error summary alerts are always static, as they are included as part of a new page or view, and remain unchanged until the user initiates a change of context.</P> <P>To orient screen reader users and others to the alert, the Design System user must ensure that when the page or view first loads:</P> <Ul> <Li>focus is moved to the alert (the alert container is preset with <code>tabindex=”-1”</code> to make it programmatically focusable)</Li> <Li>the document’s <code>title</code> starts with &quot;Error:&quot;.</Li> </Ul> <ExampleContainer> <ExampleHeading level={3}>Error summary alert</ExampleHeading> <Example code={components__Alerts[5]} iframeProps={{ id:"iframe_componentsAlerts5", className: "example__iframe", src:"/components/Alerts__example5.html", title:"Example title: Error summary alert", height: 350 }}></Example> </ExampleContainer> <h2 id="error-messages">Error messages</h2> <P>Specific error messages must be provided for specific error states. Style error messages as shown in the ‘Error messages’ sections of the guidance for the following form components:</P> <Ul> <Li><A className="g-link" href="https://design-system-alpha.digital.govt.nz/components/Input/">Text input</A></Li> <Li><A className="g-link" href="https://design-system-alpha.digital.govt.nz/components/Radios/">Radio buttons</A></Li> <Li><A className="g-link" href="https://design-system-alpha.digital.govt.nz/components/Date/">Date input</A></Li> </Ul> <h2 id="credit">Credit</h2> <P>Guidance, original HTML and CSS derived from <A className="g-link" href="https://github.com/alphagov/govuk-frontend">GOV.UK Design System</A>.</P> <P>Guidance for the page alerts component derived from the <A className="g-link" href="https://designsystem.gov.au/components/page-alerts/">Australian Government Design System</A>.</P> </React.Fragment> export default function Code(props) { return ( <ComponentPage title={"Alerts"} id={"Alerts"} pageProps={props} PageContent={PageContent} /> ); }
the_stack
import { XmlGetComplexTypeRefNoMetaOptionalParams, XmlGetComplexTypeRefNoMetaResponse, RootWithRefAndNoMeta, XmlPutComplexTypeRefNoMetaOptionalParams, XmlGetComplexTypeRefWithMetaOptionalParams, XmlGetComplexTypeRefWithMetaResponse, RootWithRefAndMeta, XmlPutComplexTypeRefWithMetaOptionalParams, XmlGetSimpleOptionalParams, XmlGetSimpleResponse, Slideshow, XmlPutSimpleOptionalParams, XmlGetWrappedListsOptionalParams, XmlGetWrappedListsResponse, AppleBarrel, XmlPutWrappedListsOptionalParams, XmlGetHeadersOptionalParams, XmlGetHeadersResponse, XmlGetEmptyListOptionalParams, XmlGetEmptyListResponse, XmlPutEmptyListOptionalParams, XmlGetEmptyWrappedListsOptionalParams, XmlGetEmptyWrappedListsResponse, XmlPutEmptyWrappedListsOptionalParams, XmlGetRootListOptionalParams, XmlGetRootListResponse, Banana, XmlPutRootListOptionalParams, XmlGetRootListSingleItemOptionalParams, XmlGetRootListSingleItemResponse, XmlPutRootListSingleItemOptionalParams, XmlGetEmptyRootListOptionalParams, XmlGetEmptyRootListResponse, XmlPutEmptyRootListOptionalParams, XmlGetEmptyChildElementOptionalParams, XmlGetEmptyChildElementResponse, XmlPutEmptyChildElementOptionalParams, XmlListContainersOptionalParams, XmlListContainersResponse, XmlGetServicePropertiesOptionalParams, XmlGetServicePropertiesResponse, StorageServiceProperties, XmlPutServicePropertiesOptionalParams, XmlGetAclsOptionalParams, XmlGetAclsResponse, SignedIdentifier, XmlPutAclsOptionalParams, XmlListBlobsOptionalParams, XmlListBlobsResponse, JsonInput, XmlJsonInputOptionalParams, XmlJsonOutputOptionalParams, XmlJsonOutputResponse, XmlGetXMsTextOptionalParams, XmlGetXMsTextResponse, XmlGetBytesOptionalParams, XmlGetBytesResponse, ModelWithByteProperty, XmlPutBinaryOptionalParams, XmlGetUriOptionalParams, XmlGetUriResponse, ModelWithUrlProperty, XmlPutUriOptionalParams } from "../models"; /** Interface representing a Xml. */ export interface Xml { /** * Get a complex type that has a ref to a complex type with no XML node * @param options The options parameters. */ getComplexTypeRefNoMeta( options?: XmlGetComplexTypeRefNoMetaOptionalParams ): Promise<XmlGetComplexTypeRefNoMetaResponse>; /** * Puts a complex type that has a ref to a complex type with no XML node * @param model I am root, and I ref a model with no meta * @param options The options parameters. */ putComplexTypeRefNoMeta( model: RootWithRefAndNoMeta, options?: XmlPutComplexTypeRefNoMetaOptionalParams ): Promise<void>; /** * Get a complex type that has a ref to a complex type with XML node * @param options The options parameters. */ getComplexTypeRefWithMeta( options?: XmlGetComplexTypeRefWithMetaOptionalParams ): Promise<XmlGetComplexTypeRefWithMetaResponse>; /** * Puts a complex type that has a ref to a complex type with XML node * @param model I am root, and I ref a model WITH meta * @param options The options parameters. */ putComplexTypeRefWithMeta( model: RootWithRefAndMeta, options?: XmlPutComplexTypeRefWithMetaOptionalParams ): Promise<void>; /** * Get a simple XML document * @param options The options parameters. */ getSimple( options?: XmlGetSimpleOptionalParams ): Promise<XmlGetSimpleResponse>; /** * Put a simple XML document * @param slideshow Data about a slideshow * @param options The options parameters. */ putSimple( slideshow: Slideshow, options?: XmlPutSimpleOptionalParams ): Promise<void>; /** * Get an XML document with multiple wrapped lists * @param options The options parameters. */ getWrappedLists( options?: XmlGetWrappedListsOptionalParams ): Promise<XmlGetWrappedListsResponse>; /** * Put an XML document with multiple wrapped lists * @param wrappedLists A barrel of apples. * @param options The options parameters. */ putWrappedLists( wrappedLists: AppleBarrel, options?: XmlPutWrappedListsOptionalParams ): Promise<void>; /** * Get strongly-typed response headers. * @param options The options parameters. */ getHeaders( options?: XmlGetHeadersOptionalParams ): Promise<XmlGetHeadersResponse>; /** * Get an empty list. * @param options The options parameters. */ getEmptyList( options?: XmlGetEmptyListOptionalParams ): Promise<XmlGetEmptyListResponse>; /** * Puts an empty list. * @param slideshow Data about a slideshow * @param options The options parameters. */ putEmptyList( slideshow: Slideshow, options?: XmlPutEmptyListOptionalParams ): Promise<void>; /** * Gets some empty wrapped lists. * @param options The options parameters. */ getEmptyWrappedLists( options?: XmlGetEmptyWrappedListsOptionalParams ): Promise<XmlGetEmptyWrappedListsResponse>; /** * Puts some empty wrapped lists. * @param appleBarrel A barrel of apples. * @param options The options parameters. */ putEmptyWrappedLists( appleBarrel: AppleBarrel, options?: XmlPutEmptyWrappedListsOptionalParams ): Promise<void>; /** * Gets a list as the root element. * @param options The options parameters. */ getRootList( options?: XmlGetRootListOptionalParams ): Promise<XmlGetRootListResponse>; /** * Puts a list as the root element. * @param bananas Array of Banana * @param options The options parameters. */ putRootList( bananas: Banana[], options?: XmlPutRootListOptionalParams ): Promise<void>; /** * Gets a list with a single item. * @param options The options parameters. */ getRootListSingleItem( options?: XmlGetRootListSingleItemOptionalParams ): Promise<XmlGetRootListSingleItemResponse>; /** * Puts a list with a single item. * @param bananas Array of Banana * @param options The options parameters. */ putRootListSingleItem( bananas: Banana[], options?: XmlPutRootListSingleItemOptionalParams ): Promise<void>; /** * Gets an empty list as the root element. * @param options The options parameters. */ getEmptyRootList( options?: XmlGetEmptyRootListOptionalParams ): Promise<XmlGetEmptyRootListResponse>; /** * Puts an empty list as the root element. * @param bananas Array of Banana * @param options The options parameters. */ putEmptyRootList( bananas: Banana[], options?: XmlPutEmptyRootListOptionalParams ): Promise<void>; /** * Gets an XML document with an empty child element. * @param options The options parameters. */ getEmptyChildElement( options?: XmlGetEmptyChildElementOptionalParams ): Promise<XmlGetEmptyChildElementResponse>; /** * Puts a value with an empty child element. * @param banana A banana. * @param options The options parameters. */ putEmptyChildElement( banana: Banana, options?: XmlPutEmptyChildElementOptionalParams ): Promise<void>; /** * Lists containers in a storage account. * @param options The options parameters. */ listContainers( options?: XmlListContainersOptionalParams ): Promise<XmlListContainersResponse>; /** * Gets storage service properties. * @param options The options parameters. */ getServiceProperties( options?: XmlGetServicePropertiesOptionalParams ): Promise<XmlGetServicePropertiesResponse>; /** * Puts storage service properties. * @param properties Storage Service Properties. * @param options The options parameters. */ putServiceProperties( properties: StorageServiceProperties, options?: XmlPutServicePropertiesOptionalParams ): Promise<void>; /** * Gets storage ACLs for a container. * @param options The options parameters. */ getAcls(options?: XmlGetAclsOptionalParams): Promise<XmlGetAclsResponse>; /** * Puts storage ACLs for a container. * @param properties a collection of signed identifiers * @param options The options parameters. */ putAcls( properties: SignedIdentifier[], options?: XmlPutAclsOptionalParams ): Promise<void>; /** * Lists blobs in a storage container. * @param options The options parameters. */ listBlobs( options?: XmlListBlobsOptionalParams ): Promise<XmlListBlobsResponse>; /** * A Swagger with XML that has one operation that takes JSON as input. You need to send the ID number * 42 * @param properties * @param options The options parameters. */ jsonInput( properties: JsonInput, options?: XmlJsonInputOptionalParams ): Promise<void>; /** * A Swagger with XML that has one operation that returns JSON. ID number 42 * @param options The options parameters. */ jsonOutput( options?: XmlJsonOutputOptionalParams ): Promise<XmlJsonOutputResponse>; /** * Get back an XML object with an x-ms-text property, which should translate to the returned object's * 'language' property being 'english' and its 'content' property being 'I am text' * @param options The options parameters. */ getXMsText( options?: XmlGetXMsTextOptionalParams ): Promise<XmlGetXMsTextResponse>; /** * Get an XML document with binary property * @param options The options parameters. */ getBytes(options?: XmlGetBytesOptionalParams): Promise<XmlGetBytesResponse>; /** * Put an XML document with binary property * @param slideshow * @param options The options parameters. */ putBinary( slideshow: ModelWithByteProperty, options?: XmlPutBinaryOptionalParams ): Promise<void>; /** * Get an XML document with uri property * @param options The options parameters. */ getUri(options?: XmlGetUriOptionalParams): Promise<XmlGetUriResponse>; /** * Put an XML document with uri property * @param model * @param options The options parameters. */ putUri( model: ModelWithUrlProperty, options?: XmlPutUriOptionalParams ): Promise<void>; }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * An Anthos cluster running on Azure. * * For more information, see: * * [Multicloud overview](https://cloud.google.com/anthos/clusters/docs/multi-cloud) * ## Example Usage * ### Basic_azure_cluster * A basic example of a containerazure azure cluster * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const versions = pulumi.output(gcp.container.getAzureVersions({ * location: "us-west1", * project: "my-project-name", * })); * const basic = new gcp.container.AzureClient("basic", { * applicationId: "12345678-1234-1234-1234-123456789111", * location: "us-west1", * project: "my-project-name", * tenantId: "12345678-1234-1234-1234-123456789111", * }); * const primary = new gcp.container.AzureCluster("primary", { * authorization: { * adminUsers: [{ * username: "mmv2@google.com", * }], * }, * azureRegion: "westus2", * client: pulumi.interpolate`projects/my-project-number/locations/us-west1/azureClients/${basic.name}`, * controlPlane: { * sshConfig: { * authorizedKey: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC8yaayO6lnb2v+SedxUMa2c8vtIEzCzBjM3EJJsv8Vm9zUDWR7dXWKoNGARUb2mNGXASvI6mFIDXTIlkQ0poDEPpMaXR0g2cb5xT8jAAJq7fqXL3+0rcJhY/uigQ+MrT6s+ub0BFVbsmGHNrMQttXX9gtmwkeAEvj3mra9e5pkNf90qlKnZz6U0SVArxVsLx07vHPHDIYrl0OPG4zUREF52igbBPiNrHJFDQJT/4YlDMJmo/QT/A1D6n9ocemvZSzhRx15/Arjowhr+VVKSbaxzPtEfY0oIg2SrqJnnr/l3Du5qIefwh5VmCZe4xopPUaDDoOIEFriZ88sB+3zz8ib8sk8zJJQCgeP78tQvXCgS+4e5W3TUg9mxjB6KjXTyHIVhDZqhqde0OI3Fy1UuVzRUwnBaLjBnAwP5EoFQGRmDYk/rEYe7HTmovLeEBUDQocBQKT4Ripm/xJkkWY7B07K/tfo56dGUCkvyIVXKBInCh+dLK7gZapnd4UWkY0xBYcwo1geMLRq58iFTLA2j/JmpmHXp7m0l7jJii7d44uD3tTIFYThn7NlOnvhLim/YcBK07GMGIN7XwrrKZKmxXaspw6KBWVhzuw1UPxctxshYEaMLfFg/bwOw8HvMPr9VtrElpSB7oiOh91PDIPdPBgHCi7N2QgQ5l/ZDBHieSpNrQ== thomasrodgers", * }, * subnetId: "/subscriptions/12345678-1234-1234-1234-123456789111/resourceGroups/my--dev-byo/providers/Microsoft.Network/virtualNetworks/my--dev-vnet/subnets/default", * version: versions.apply(versions => versions.validVersions[0]), * }, * fleet: { * project: "my-project-number", * }, * location: "us-west1", * networking: { * podAddressCidrBlocks: ["10.200.0.0/16"], * serviceAddressCidrBlocks: ["10.32.0.0/24"], * virtualNetworkId: "/subscriptions/12345678-1234-1234-1234-123456789111/resourceGroups/my--dev-byo/providers/Microsoft.Network/virtualNetworks/my--dev-vnet", * }, * project: "my-project-name", * resourceGroupId: "/subscriptions/12345678-1234-1234-1234-123456789111/resourceGroups/my--dev-cluster", * }); * ``` * * ## Import * * Cluster can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:container/azureCluster:AzureCluster default projects/{{project}}/locations/{{location}}/azureClusters/{{name}} * ``` * * ```sh * $ pulumi import gcp:container/azureCluster:AzureCluster default {{project}}/{{location}}/{{name}} * ``` * * ```sh * $ pulumi import gcp:container/azureCluster:AzureCluster default {{location}}/{{name}} * ``` */ export class AzureCluster extends pulumi.CustomResource { /** * Get an existing AzureCluster 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?: AzureClusterState, opts?: pulumi.CustomResourceOptions): AzureCluster { return new AzureCluster(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:container/azureCluster:AzureCluster'; /** * Returns true if the given object is an instance of AzureCluster. 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 AzureCluster { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === AzureCluster.__pulumiType; } /** * Optional. Annotations on the cluster. This field has the same restrictions as Kubernetes annotations. The total size of all keys and values combined is limited to 256k. Keys can have 2 segments: prefix (optional) and name (required), separated by a slash (/). Prefix must be a DNS subdomain. Name must be 63 characters or less, begin and end with alphanumerics, with dashes (-), underscores (_), dots (.), and alphanumerics between. */ public readonly annotations!: pulumi.Output<{[key: string]: string} | undefined>; /** * Required. Configuration related to the cluster RBAC settings. */ public readonly authorization!: pulumi.Output<outputs.container.AzureClusterAuthorization>; /** * Required. The Azure region where the cluster runs. Each Google Cloud region supports a subset of nearby Azure regions. You can call to list all supported Azure regions within a given Google Cloud region. */ public readonly azureRegion!: pulumi.Output<string>; /** * Required. Name of the AzureClient. The `AzureClient` resource must reside on the same GCP project and region as the `AzureCluster`. `AzureClient` names are formatted as `projects/<project-number>/locations/<region>/azureClients/<client-id>`. See Resource Names (https:cloud.google.com/apis/design/resource_names) for more details on Google Cloud resource names. */ public readonly client!: pulumi.Output<string>; /** * Required. Configuration related to the cluster control plane. */ public readonly controlPlane!: pulumi.Output<outputs.container.AzureClusterControlPlane>; /** * Output only. The time at which this cluster was created. */ public /*out*/ readonly createTime!: pulumi.Output<string>; /** * Optional. A human readable description of this cluster. Cannot be longer than 255 UTF-8 encoded bytes. */ public readonly description!: pulumi.Output<string | undefined>; /** * Output only. The endpoint of the cluster's API server. */ public /*out*/ readonly endpoint!: pulumi.Output<string>; /** * Allows clients to perform consistent read-modify-writes through optimistic concurrency control. May be sent on update * and delete requests to ensure the client has an up-to-date value before proceeding. */ public /*out*/ readonly etag!: pulumi.Output<string>; /** * Fleet configuration. */ public readonly fleet!: pulumi.Output<outputs.container.AzureClusterFleet>; /** * The location for the resource */ public readonly location!: pulumi.Output<string>; /** * The name of this resource. */ public readonly name!: pulumi.Output<string>; /** * Required. Cluster-wide networking configuration. */ public readonly networking!: pulumi.Output<outputs.container.AzureClusterNetworking>; /** * The project for the resource */ public readonly project!: pulumi.Output<string>; /** * Output only. If set, there are currently changes in flight to the cluster. */ public /*out*/ readonly reconciling!: pulumi.Output<boolean>; /** * The ARM ID the of the resource group containing proxy keyvault. Resource group ids are formatted as `/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>` */ public readonly resourceGroupId!: pulumi.Output<string>; /** * Output only. The current state of the cluster. Possible values: STATE_UNSPECIFIED, PROVISIONING, RUNNING, RECONCILING, * STOPPING, ERROR, DEGRADED */ public /*out*/ readonly state!: pulumi.Output<string>; /** * Output only. A globally unique identifier for the cluster. */ public /*out*/ readonly uid!: pulumi.Output<string>; /** * Output only. The time at which this cluster was last updated. */ public /*out*/ readonly updateTime!: pulumi.Output<string>; /** * Output only. Workload Identity settings. */ public /*out*/ readonly workloadIdentityConfigs!: pulumi.Output<outputs.container.AzureClusterWorkloadIdentityConfig[]>; /** * Create a AzureCluster 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: AzureClusterArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: AzureClusterArgs | AzureClusterState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as AzureClusterState | undefined; inputs["annotations"] = state ? state.annotations : undefined; inputs["authorization"] = state ? state.authorization : undefined; inputs["azureRegion"] = state ? state.azureRegion : undefined; inputs["client"] = state ? state.client : undefined; inputs["controlPlane"] = state ? state.controlPlane : undefined; inputs["createTime"] = state ? state.createTime : undefined; inputs["description"] = state ? state.description : undefined; inputs["endpoint"] = state ? state.endpoint : undefined; inputs["etag"] = state ? state.etag : undefined; inputs["fleet"] = state ? state.fleet : undefined; inputs["location"] = state ? state.location : undefined; inputs["name"] = state ? state.name : undefined; inputs["networking"] = state ? state.networking : undefined; inputs["project"] = state ? state.project : undefined; inputs["reconciling"] = state ? state.reconciling : undefined; inputs["resourceGroupId"] = state ? state.resourceGroupId : undefined; inputs["state"] = state ? state.state : undefined; inputs["uid"] = state ? state.uid : undefined; inputs["updateTime"] = state ? state.updateTime : undefined; inputs["workloadIdentityConfigs"] = state ? state.workloadIdentityConfigs : undefined; } else { const args = argsOrState as AzureClusterArgs | undefined; if ((!args || args.authorization === undefined) && !opts.urn) { throw new Error("Missing required property 'authorization'"); } if ((!args || args.azureRegion === undefined) && !opts.urn) { throw new Error("Missing required property 'azureRegion'"); } if ((!args || args.client === undefined) && !opts.urn) { throw new Error("Missing required property 'client'"); } if ((!args || args.controlPlane === undefined) && !opts.urn) { throw new Error("Missing required property 'controlPlane'"); } if ((!args || args.fleet === undefined) && !opts.urn) { throw new Error("Missing required property 'fleet'"); } if ((!args || args.location === undefined) && !opts.urn) { throw new Error("Missing required property 'location'"); } if ((!args || args.networking === undefined) && !opts.urn) { throw new Error("Missing required property 'networking'"); } if ((!args || args.resourceGroupId === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupId'"); } inputs["annotations"] = args ? args.annotations : undefined; inputs["authorization"] = args ? args.authorization : undefined; inputs["azureRegion"] = args ? args.azureRegion : undefined; inputs["client"] = args ? args.client : undefined; inputs["controlPlane"] = args ? args.controlPlane : undefined; inputs["description"] = args ? args.description : undefined; inputs["fleet"] = args ? args.fleet : undefined; inputs["location"] = args ? args.location : undefined; inputs["name"] = args ? args.name : undefined; inputs["networking"] = args ? args.networking : undefined; inputs["project"] = args ? args.project : undefined; inputs["resourceGroupId"] = args ? args.resourceGroupId : undefined; inputs["createTime"] = undefined /*out*/; inputs["endpoint"] = undefined /*out*/; inputs["etag"] = undefined /*out*/; inputs["reconciling"] = undefined /*out*/; inputs["state"] = undefined /*out*/; inputs["uid"] = undefined /*out*/; inputs["updateTime"] = undefined /*out*/; inputs["workloadIdentityConfigs"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(AzureCluster.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering AzureCluster resources. */ export interface AzureClusterState { /** * Optional. Annotations on the cluster. This field has the same restrictions as Kubernetes annotations. The total size of all keys and values combined is limited to 256k. Keys can have 2 segments: prefix (optional) and name (required), separated by a slash (/). Prefix must be a DNS subdomain. Name must be 63 characters or less, begin and end with alphanumerics, with dashes (-), underscores (_), dots (.), and alphanumerics between. */ annotations?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Required. Configuration related to the cluster RBAC settings. */ authorization?: pulumi.Input<inputs.container.AzureClusterAuthorization>; /** * Required. The Azure region where the cluster runs. Each Google Cloud region supports a subset of nearby Azure regions. You can call to list all supported Azure regions within a given Google Cloud region. */ azureRegion?: pulumi.Input<string>; /** * Required. Name of the AzureClient. The `AzureClient` resource must reside on the same GCP project and region as the `AzureCluster`. `AzureClient` names are formatted as `projects/<project-number>/locations/<region>/azureClients/<client-id>`. See Resource Names (https:cloud.google.com/apis/design/resource_names) for more details on Google Cloud resource names. */ client?: pulumi.Input<string>; /** * Required. Configuration related to the cluster control plane. */ controlPlane?: pulumi.Input<inputs.container.AzureClusterControlPlane>; /** * Output only. The time at which this cluster was created. */ createTime?: pulumi.Input<string>; /** * Optional. A human readable description of this cluster. Cannot be longer than 255 UTF-8 encoded bytes. */ description?: pulumi.Input<string>; /** * Output only. The endpoint of the cluster's API server. */ endpoint?: pulumi.Input<string>; /** * Allows clients to perform consistent read-modify-writes through optimistic concurrency control. May be sent on update * and delete requests to ensure the client has an up-to-date value before proceeding. */ etag?: pulumi.Input<string>; /** * Fleet configuration. */ fleet?: pulumi.Input<inputs.container.AzureClusterFleet>; /** * The location for the resource */ location?: pulumi.Input<string>; /** * The name of this resource. */ name?: pulumi.Input<string>; /** * Required. Cluster-wide networking configuration. */ networking?: pulumi.Input<inputs.container.AzureClusterNetworking>; /** * The project for the resource */ project?: pulumi.Input<string>; /** * Output only. If set, there are currently changes in flight to the cluster. */ reconciling?: pulumi.Input<boolean>; /** * The ARM ID the of the resource group containing proxy keyvault. Resource group ids are formatted as `/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>` */ resourceGroupId?: pulumi.Input<string>; /** * Output only. The current state of the cluster. Possible values: STATE_UNSPECIFIED, PROVISIONING, RUNNING, RECONCILING, * STOPPING, ERROR, DEGRADED */ state?: pulumi.Input<string>; /** * Output only. A globally unique identifier for the cluster. */ uid?: pulumi.Input<string>; /** * Output only. The time at which this cluster was last updated. */ updateTime?: pulumi.Input<string>; /** * Output only. Workload Identity settings. */ workloadIdentityConfigs?: pulumi.Input<pulumi.Input<inputs.container.AzureClusterWorkloadIdentityConfig>[]>; } /** * The set of arguments for constructing a AzureCluster resource. */ export interface AzureClusterArgs { /** * Optional. Annotations on the cluster. This field has the same restrictions as Kubernetes annotations. The total size of all keys and values combined is limited to 256k. Keys can have 2 segments: prefix (optional) and name (required), separated by a slash (/). Prefix must be a DNS subdomain. Name must be 63 characters or less, begin and end with alphanumerics, with dashes (-), underscores (_), dots (.), and alphanumerics between. */ annotations?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * Required. Configuration related to the cluster RBAC settings. */ authorization: pulumi.Input<inputs.container.AzureClusterAuthorization>; /** * Required. The Azure region where the cluster runs. Each Google Cloud region supports a subset of nearby Azure regions. You can call to list all supported Azure regions within a given Google Cloud region. */ azureRegion: pulumi.Input<string>; /** * Required. Name of the AzureClient. The `AzureClient` resource must reside on the same GCP project and region as the `AzureCluster`. `AzureClient` names are formatted as `projects/<project-number>/locations/<region>/azureClients/<client-id>`. See Resource Names (https:cloud.google.com/apis/design/resource_names) for more details on Google Cloud resource names. */ client: pulumi.Input<string>; /** * Required. Configuration related to the cluster control plane. */ controlPlane: pulumi.Input<inputs.container.AzureClusterControlPlane>; /** * Optional. A human readable description of this cluster. Cannot be longer than 255 UTF-8 encoded bytes. */ description?: pulumi.Input<string>; /** * Fleet configuration. */ fleet: pulumi.Input<inputs.container.AzureClusterFleet>; /** * The location for the resource */ location: pulumi.Input<string>; /** * The name of this resource. */ name?: pulumi.Input<string>; /** * Required. Cluster-wide networking configuration. */ networking: pulumi.Input<inputs.container.AzureClusterNetworking>; /** * The project for the resource */ project?: pulumi.Input<string>; /** * The ARM ID the of the resource group containing proxy keyvault. Resource group ids are formatted as `/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>` */ resourceGroupId: pulumi.Input<string>; }
the_stack
import { ObjectDictionary } from "@opticss/util"; import * as debugGenerator from "debug"; import { postcss } from "opticss"; import * as path from "path"; import { Block } from "../BlockTree"; import { Options, ResolvedConfiguration } from "../configuration"; import { CssBlockError } from "../errors"; import { FileIdentifier, ImportedCompiledCssFile, ImportedFile } from "../importing"; import { BlockFactoryBase, sourceMapFromProcessedFile } from "./BlockFactoryBase"; import { BlockParser, ParsedSource } from "./BlockParser"; import { PreprocessorSync, PreprocessorsSync, ProcessedFile, Syntax, annotateCssContentWithSourceMap, syntaxName } from "./preprocessing"; const debug = debugGenerator("css-blocks:BlockFactorySync"); interface ErrorWithErrNum { code?: string; message: string; } // DEVELOPER NOTE: There's currently a lot of duplication between this file ane // BlockFactory.ts. It's very likely that any change you're making here has to // also be made over there. Please keep these files in sync. /** * This factory ensures that instances of a block are re-used when blocks are * going to be compiled/optimized together. Multiple instances of the same * block will result in analysis and optimization bugs. * * This also ensures that importers and preprocessors are correctly used when loading a block file. */ export class BlockFactorySync extends BlockFactoryBase { parser: BlockParser; preprocessors: PreprocessorsSync; private blocks: ObjectDictionary<Block>; private paths: ObjectDictionary<string>; get isSync(): true { return true; } constructor(options: Options, postcssImpl = postcss, faultTolerant = false) { super(options, postcssImpl, faultTolerant); this.preprocessors = this.configuration.preprocessorsSync; this.parser = new BlockParser(options, this); this.blocks = {}; this.paths = {}; this.faultTolerant = faultTolerant; } /** * Toss out any caches in this BlockFactory. Any future requests for a block * or block path will be loaded fresh from persistent storage. */ reset() { super.reset(); this.blocks = {}; this.paths = {}; } /** * Parse a `postcss.Root` into a Block object. Use parseRoot if we need to * catch errors. * * This function is referenced only in tests. * @param root The postcss.Root to parse. * @param identifier A unique identifier for this Block file. * @param name Default name for the block. * @param isDfnFile Whether to treat this as a definition file. * @returns The Block object. */ parseRootFaultTolerant(root: postcss.Root, identifier: string, name: string, isDfnFile = false, expectedGuid?: string): Block { return this.parser.parseSync(root, identifier, name, isDfnFile, expectedGuid); } /** * Parse a `postcss.Root` into a Block object. Also assert that the block is * valid so that we can catch any errors that the block contains. * * This function is only used in tests * @param root The postcss.Root to parse. * @param identifier A unique identifier for this Block file. * @param name Default name for the block. * @param isDfnFile Whether to treat this as a definition file. * @returns The Block object. */ parseRoot(root: postcss.Root, identifier: string, name: string, isDfnFile = false, expectedGuid?: string): Block { const block = this.parseRootFaultTolerant(root, identifier, name, isDfnFile, expectedGuid); return this._surfaceBlockErrors(block); } /** * This method doesn't do anything, but it's provided for parity with * `BlockFactory`. */ prepareForExit(): void { } /** * Given a file path (or other data path reference), load data from storage and parse it * into a CSS Block. * * @param filePath - The path to the file or data in persistent storage. The Importer that you've * configured to use will resolve this to a location in the storage system. * @returns The parsed block. */ getBlockFromPath(filePath: string): Block { if (!path.isAbsolute(filePath)) { throw new Error(`An absolute path is required. Got: ${filePath}.`); } filePath = path.resolve(filePath); let identifier: FileIdentifier = this.paths[filePath] || this.importer.identifier(null, filePath, this.configuration); return this.getBlock(identifier); } /** * Given a FileIdentifier that points to block data on storage, load the data and parse it * into a CSS Block. In most cases, you'll likely want to use getBlockFromPath() instead. * * If the block for the given identifier has already been loaded and parsed, * the cached block will be returned instead. * * @param identifier - An identifier that points at a data file or blob in persistent storage. * These identifiers are created by the Importer that you've configured * to use. * @returns The parsed block. */ getBlock(identifier: FileIdentifier): Block { if (this.blocks[identifier]) { return this.blocks[identifier]; } return this._getBlock(identifier); } /** * Loads and parses a CSS Block data file. We load the data here, using the * Importer, then defer to another method to actually parse the data file * into a Block. * * @param identifier - An identifier that points at a data file or blob in persistent storage. * @returns The parsed block. */ private _getBlock(identifier: FileIdentifier): Block { let file = this.importer.importSync(identifier, this.configuration); let block: Block; if (file.type === "ImportedCompiledCssFile") { block = this._reconstituteCompiledCssSource(file); } else { block = this._importAndPreprocessBlock(file); } debug(`Finalizing Block object for "${block.identifier}"`); // last check to make sure we don't return a new instance if (this.blocks[block.identifier]) { return this.blocks[block.identifier]; } // Ensure this block name is unique. const uniqueName = this.getUniqueBlockName(block.name, block.identifier, file.type === "ImportedCompiledCssFile"); if (uniqueName === null) { // For ImportedCompiledCssFiles, leave the name alone and add an error. block.addError( new CssBlockError(`Block uses a name that has already been used by ${this.blockNames[block.name]}`, { filename: block.identifier, }), ); block.setName(block.name); } else { block.setName(uniqueName); } // We only register guids from blocks that don't have errors because those will get re-parsed. if (block.isValid()) { // Ensure the GUID is unique. const guidRegResult = this.registerGuid(block.guid); if (!guidRegResult) { block.addError( new CssBlockError("Block uses a GUID that has already been used! Check dependencies for conflicting GUIDs and/or increase the number of significant characters used to generate GUIDs.", { filename: block.identifier, }, ), ); } } // if the block has any errors, surface them here unless we're in fault tolerant mode. this._surfaceBlockErrors(block); this.blocks[block.identifier] = block; return block; } /** * Parse the file into a `Block`. Specifically, this method runs the data through any related * preprocessor (such as a SASS or LESS compiler), parses the CSS into an AST using PostCSS, then * hands the AST off to the Block parser to validate the CSS and transform it into the Block * class used by CSS Blocks. * * Notably, this method expects that any related file data has already been loaded from memory * using the Importer. * * @param file - The file information that has been previously imported by the Importer, for * a single block identifier. * @returns A parsed block. **/ private _importAndPreprocessBlock(file: ImportedFile): Block { // If the file identifier maps back to a real filename, ensure it is actually unique. let realFilename = this.importer.filesystemPath(file.identifier, this.configuration); if (realFilename) { if (this.paths[realFilename] && this.paths[realFilename] !== file.identifier) { throw new Error(`The same block file was returned with different identifiers: ${this.paths[realFilename]} and ${file.identifier}`); } else { this.paths[realFilename] = file.identifier; } } // Skip preprocessing if we can. if (this.blocks[file.identifier]) { debug(`Using pre-compiled Block for "${file.identifier}"`); return this.blocks[file.identifier]; } // Preprocess the file. let filename: string = realFilename || this.importer.debugIdentifier(file.identifier, this.configuration); let preprocessor = this.preprocessor(file); debug(`Preprocessing "${filename}"`); let preprocessResult = preprocessor(filename, file.contents, this.configuration); debug(`Generating PostCSS AST for "${filename}"`); let sourceMap = sourceMapFromProcessedFile(preprocessResult); let content = preprocessResult.content; if (sourceMap) { content = annotateCssContentWithSourceMap(this.configuration, filename, content, sourceMap); } let root = this.postcssImpl.parse(content, { from: filename }); // Skip parsing if we can. if (this.blocks[file.identifier]) { return this.blocks[file.identifier]; } debug(`Parsing Block object for "${filename}"`); let source: ParsedSource = { identifier: file.identifier, defaultName: file.defaultName, parseResult: root, originalSource: file.contents, originalSyntax: file.syntax, dependencies: preprocessResult.dependencies || [], }; return this.parser.parseSourceSync(source); } private _reconstituteCompiledCssSource(file: ImportedCompiledCssFile): Block { // Maybe we already have this block in cache? if (this.blocks[file.identifier]) { debug(`Using pre-compiled Block for "${file.identifier}"`); return this.blocks[file.identifier]; } const { definitionAst, cssContentsAst } = this._prepareDefinitionASTs(file); // Construct a Block out of the definition file. const block = this.parser.parseDefinitionSourceSync(definitionAst, file.identifier, file.blockId, file.defaultName); // Merge the rules from the CSS contents into the Block. block.precompiledStylesheet = cssContentsAst; block.precompiledStylesheetUnedited = file.rawCssContents; this._mergeCssRulesIntoDefinitionBlock(block, cssContentsAst, file); // And we're done! return block; } /** * Similar to getBlock(), this imports and parses a block data file. However, this * method parses a block relative to another block. * * @param fromIdentifier - The FileIdentifier that references the base location that the * import path is relative to. * @param importPath - The relative import path for the file to import. * @returns The parsed block. */ getBlockRelative(fromIdentifier: FileIdentifier, importPath: string): Block { let importer = this.importer; let fromPath = importer.debugIdentifier(fromIdentifier, this.configuration); let identifier = importer.identifier(fromIdentifier, importPath, this.configuration); try { return this.getBlock(identifier); } catch (err) { if ((<ErrorWithErrNum>err).code === "ENOENT") { err.message = `From ${fromPath}: ${err.message}`; } throw err; } } preprocessor(file: ImportedFile): PreprocessorSync { let syntax = file.syntax; let firstPreprocessor: PreprocessorSync | undefined = this.preprocessors[syntax]; let preprocessor: PreprocessorSync | null = null; if (firstPreprocessor) { if (syntax !== Syntax.css && this.preprocessors.css && !this.configuration.disablePreprocessChaining) { let cssProcessor = this.preprocessors.css; preprocessor = (fullPath: string, content: string, configuration: ResolvedConfiguration): ProcessedFile => { let result = firstPreprocessor!(fullPath, content, configuration); let content2 = result.content.toString(); let result2 = cssProcessor(fullPath, content2, configuration, sourceMapFromProcessedFile(result)); return { content: result2.content, sourceMap: sourceMapFromProcessedFile(result2), dependencies: (result.dependencies || []).concat(result2.dependencies || []), }; }; } else { preprocessor = firstPreprocessor; } } else if (syntax !== Syntax.css) { throw new Error(`No preprocessor provided for ${syntaxName(syntax)}.`); } else { preprocessor = (_fullPath: string, content: string, _options: ResolvedConfiguration): ProcessedFile => { return { content, }; }; } return preprocessor; } }
the_stack
import React from 'react'; import { Alert, Text, View } from 'react-native'; import renderer from 'react-test-renderer'; import { Autolink } from '../Autolink'; import { CustomMatch } from '../CustomMatch'; import { IntlPhoneMatcher, LatLngMatcher } from '../matchers'; describe('<Autolink />', () => { test('renders a Text node', () => { const tree = renderer.create(<Autolink text="" />).toJSON(); expect(tree).toMatchSnapshot(); }); test('renders a string when nothing to link', () => { const tree = renderer.create(<Autolink text="Testing" />).toJSON(); expect(tree).toMatchSnapshot(); }); test('renders a custom container node', () => { const tree = renderer.create(<Autolink component={View} text="Testing" />).toJSON(); expect(tree).toMatchSnapshot(); }); test('wraps an email address with a link Text node when email prop enabled', () => { const tree = renderer.create(<Autolink text="josh@example.com" email />).toJSON(); expect(tree).toMatchSnapshot(); }); test('does not wrap an email address in a link Text node when email prop disabled', () => { const tree = renderer.create(<Autolink text="josh@example.com" email={false} />).toJSON(); expect(tree).toMatchSnapshot(); }); test('wraps a hashtag in a link Text node when hashtag prop enabled', () => { const tree = renderer.create(<Autolink text="#awesome" hashtag="instagram" />).toJSON(); expect(tree).toMatchSnapshot(); }); test('does not wrap a hashtag in a link Text node when hashtag prop disabled', () => { const tree = renderer.create(<Autolink text="#awesome" hashtag={false} />).toJSON(); expect(tree).toMatchSnapshot(); }); test('wraps a mention/handle in a link Text node when mention prop enabled', () => { const tree = renderer.create(<Autolink text="@twitter" mention="twitter" />).toJSON(); expect(tree).toMatchSnapshot(); }); test('does not wrap a mention/handle in a link Text node when mention prop disabled', () => { const tree = renderer.create(<Autolink text="@twitter" mention={false} />).toJSON(); expect(tree).toMatchSnapshot(); }); test('wraps a phone number in a link Text node when phone prop enabled', () => { const tree = renderer.create(<Autolink text="415-555-5555" phone />).toJSON(); expect(tree).toMatchSnapshot(); }); test('does not wrap a phone number in a link Text node when phone prop disabled', () => { const tree = renderer.create(<Autolink text="415-555-5555" phone={false} />).toJSON(); expect(tree).toMatchSnapshot(); }); test('wraps a url in a link Text node when url prop enabled', () => { const tree = renderer .create(<Autolink text="https://github.com/joshswan/react-native-autolink" url />) .toJSON(); expect(tree).toMatchSnapshot(); }); test('matches top-level domain url when wwwMatches enabled', () => { const tree = renderer .create(<Autolink text="github.com" url={{ tldMatches: true }} />) .toJSON(); expect(tree).toMatchSnapshot(); }); test('does not match top-level domain url when wwwMatches disabled', () => { const tree = renderer .create(<Autolink text="github.com" url={{ tldMatches: false }} />) .toJSON(); expect(tree).toMatchSnapshot(); }); test('does not match www-containing url when wwwMatches disabled', () => { const tree = renderer .create(<Autolink text="www.github.com" url={{ wwwMatches: false }} />) .toJSON(); expect(tree).toMatchSnapshot(); }); test('does not match scheme-containing url when schemeMatches disabled', () => { const tree = renderer .create(<Autolink text="http://github.com" url={{ schemeMatches: false }} />) .toJSON(); expect(tree).toMatchSnapshot(); }); test('does not wrap a url in a link Text node when url prop disabled', () => { const tree = renderer .create(<Autolink text="https://github.com/joshswan/react-native-autolink" url={false} />) .toJSON(); expect(tree).toMatchSnapshot(); }); test('links multiple elements individually', () => { const tree = renderer .create( <Autolink text="Hi @josh (josh@example.com or 415-555-5555), check out https://github.com/joshswan/react-native-autolink. It's #awesome!" email hashtag="instagram" mention="twitter" phone url />, ) .toJSON(); expect(tree).toMatchSnapshot(); }); test('removes url prefixes when stripPrefix prop enabled', () => { const tree = renderer.create(<Autolink text="https://github.com" stripPrefix />).toJSON(); expect(tree).toMatchSnapshot(); }); test('does not remove url prefixes when stripPrefix prop disabled', () => { const tree = renderer .create(<Autolink text="https://github.com" stripPrefix={false} />) .toJSON(); expect(tree).toMatchSnapshot(); }); test('removes url trailing slashes when stripTrailingSlash prop enabled', () => { const tree = renderer.create(<Autolink text="github.com/" stripTrailingSlash />).toJSON(); expect(tree).toMatchSnapshot(); }); test('does not remove url trailing slashes when stripTrailingSlash prop disabled', () => { const tree = renderer .create(<Autolink text="github.com/joshswan/" stripTrailingSlash={false} />) .toJSON(); expect(tree).toMatchSnapshot(); }); test('truncates urls to length specified in truncate prop', () => { const tree = renderer .create(<Autolink text="github.com/joshswan/react-native-autolink" truncate={32} />) .toJSON(); expect(tree).toMatchSnapshot(); }); test('replaces removed protion of truncated url with truncateChars prop value', () => { const tree = renderer .create( <Autolink text="github.com/joshswan/react-native-autolink" truncate={32} truncateChars="__" />, ) .toJSON(); expect(tree).toMatchSnapshot(); }); test('truncates urls at the end when specified in truncateLocation prop', () => { const tree = renderer .create( <Autolink stripPrefix={false} text="https://github.com/joshswan/react-native-autolink" truncate={32} truncateLocation="end" />, ) .toJSON(); expect(tree).toMatchSnapshot(); }); test('truncates urls in the middle when specified in truncateLocation prop', () => { const tree = renderer .create( <Autolink stripPrefix={false} text="https://github.com/joshswan/react-native-autolink" truncate={32} truncateLocation="middle" />, ) .toJSON(); expect(tree).toMatchSnapshot(); }); test('renders links using renderLink prop if provided', () => { const renderLink = (text, match, index) => <Text>{`${text}:${index}`}</Text>; const tree = renderer .create(<Autolink text="josh@example.com" renderLink={renderLink} />) .toJSON(); expect(tree).toMatchSnapshot(); }); test('renders text using renderText prop if provided', () => { const renderText = (text) => ( <View> <Text>{text}</Text> </View> ); const tree = renderer .create(<Autolink component={View} text="Testing" renderText={renderText} />) .toJSON(); expect(tree).toMatchSnapshot(); }); test('calls onPress handler prop when link clicked', () => { const onPress = jest.fn(); const tree = renderer.create(<Autolink text="josh@example.com" onPress={onPress} />); tree.root.findAllByType(Text)[1].props.onPress(); expect(onPress.mock.calls.length).toBe(1); expect(onPress.mock.calls[0][0]).toBe('mailto:josh%40example.com'); }); test('calls onLongPress handler prop when link long pressed', () => { const onLongPress = jest.fn(); const tree = renderer.create(<Autolink text="josh@example.com" onLongPress={onLongPress} />); tree.root.findAllByType(Text)[1].props.onLongPress(); expect(onLongPress.mock.calls.length).toBe(1); expect(onLongPress.mock.calls[0][0]).toBe('mailto:josh%40example.com'); }); describe('alert', () => { test('displays alert before linking when showAlert prop enabled', () => { const spy = jest.spyOn(Alert, 'alert').mockImplementationOnce(() => {}); const tree = renderer.create(<Autolink text="#awesome" hashtag="instagram" showAlert />); tree.root.findAllByType(Text)[1].props.onPress(); expect(spy).toBeCalledTimes(1); expect(spy).toBeCalledWith('Leaving App', 'Do you want to continue?', expect.any(Array)); }); }); describe('urls', () => { test('uses hashtag url when pressing linked hashtag', () => { const onPress = jest.fn(); const tree = renderer.create( <Autolink text="#awesome" hashtag="instagram" onPress={onPress} />, ); tree.root.findAllByType(Text)[1].props.onPress(); expect(onPress.mock.calls.length).toBe(1); expect(onPress.mock.calls[0][0]).toBe('https://www.instagram.com/explore/tags/awesome/'); }); test('uses mention url when pressing linked mention', () => { const onPress = jest.fn(); const tree = renderer.create( <Autolink text="@twitter" mention="twitter" onPress={onPress} />, ); tree.root.findAllByType(Text)[1].props.onPress(); expect(onPress.mock.calls.length).toBe(1); expect(onPress.mock.calls[0][0]).toBe('https://twitter.com/twitter'); }); test('uses native scheme for mention url when enabled', () => { const onPress = jest.fn(); const tree = renderer.create( <Autolink text="@twitter" mention="twitter" onPress={onPress} useNativeSchemes />, ); tree.root.findAllByType(Text)[1].props.onPress(); expect(onPress.mock.calls.length).toBe(1); expect(onPress.mock.calls[0][0]).toBe('twitter://user?screen_name=twitter'); }); test('uses phone url when pressing linked phone number', () => { const onPress = jest.fn(); const tree = renderer.create(<Autolink text="415-555-5555" phone onPress={onPress} />); tree.root.findAllByType(Text)[1].props.onPress(); expect(onPress.mock.calls.length).toBe(1); expect(onPress.mock.calls[0][0]).toBe('tel:4155555555'); }); }); /** * Custom matchers */ describe('matchers', () => { test('wraps text based on supplied custom matchers', () => { const tree = renderer .create(<Autolink text="34.0522, -118.2437" matchers={[LatLngMatcher]} />) .toJSON(); expect(tree).toMatchSnapshot(); }); test('calls custom onPress handlers', () => { const onPress = jest.fn(); const tree = renderer.create( <Autolink text="+14085550123" matchers={[{ ...IntlPhoneMatcher, onPress }]} />, ); tree.root.findAllByType(Text)[1].props.onPress(); expect(onPress.mock.calls.length).toBe(1); expect(onPress.mock.calls[0][0]).toBeInstanceOf(CustomMatch); }); test('calls custom onLongPress handlers', () => { const onLongPress = jest.fn(); const tree = renderer.create( <Autolink text="+14085550123" matchers={[{ ...IntlPhoneMatcher, onLongPress }]} />, ); tree.root.findAllByType(Text)[1].props.onLongPress(); expect(onLongPress.mock.calls.length).toBe(1); expect(onLongPress.mock.calls[0][0]).toBeInstanceOf(CustomMatch); }); test('uses getLinkText when rendering link', () => { const tree = renderer .create( <Autolink text="+14085550123" matchers={[{ ...IntlPhoneMatcher, getLinkText: () => '__LINK_TEXT__' }]} />, ) .toJSON(); expect(tree).toMatchSnapshot(); }); test('uses getLinkUrl when using default onPress handler', () => { const onPress = jest.fn(); const tree = renderer.create( <Autolink text="+14085550123" onPress={onPress} matchers={[{ ...IntlPhoneMatcher, getLinkUrl: () => '__LINK_URL__' }]} />, ); tree.root.findAllByType(Text)[1].props.onPress(); expect(onPress.mock.calls.length).toBe(1); expect(onPress.mock.calls[0][0]).toBe('__LINK_URL__'); expect(onPress.mock.calls[0][1]).toBeInstanceOf(CustomMatch); }); }); });
the_stack
import { Enabled } from '../src/enums'; import forward from '../src/forward'; beforeEach(() => { forward.config = {}; }); describe('no rules', () => { test('no forward when no rules', () => { expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'g.alicdn.com', requestId: 1 }) ).toEqual({}); expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com??a.js,b.js,c.js', requestId: 2 }) ).toEqual({}); expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com??a.js,b.js,c.js', requestId: 2 }) ).toEqual({}); }); }); describe('rule[1] is not string', () => { test('no forward when no rule[1]', () => { forward.config.proxy = [['g.alicdn.com']]; expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'g.alicdn.com', requestId: 1 }) ).toEqual({}); expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com??a.js,b.js,c.js', requestId: 2 }) ).toEqual({}); }); test('no forward when rule[1] is not string', () => { // @ts-ignore forward.config.proxy = [['g.alicdn.com', ['a', 'b']]]; expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'g.alicdn.com', requestId: 1 }) ).toEqual({}); expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com??a.js,b.js,c.js', requestId: 2 }) ).toEqual({}); }); test('no forward when rule[1] is not string', () => { // @ts-ignore forward.config.proxy = [['g.alicdn.com', {}]]; expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'g.alicdn.com', requestId: 1 }) ).toEqual({}); expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com??a.js,b.js,c.js', requestId: 2 }) ).toEqual({}); }); }); describe('chrome-extension://', () => { test('should not forward', () => { forward.config.proxy = [['(.*).js', '$1..js']]; expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'chrome-extension://xxxxx/a.js', requestId: 1 }) ).toEqual({}); }); test('should not forward', () => { forward.config.proxy = [['xxxxx', 'xxxx']]; expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'chrome-extension://xxxxx/a.js', requestId: 2 }) ).toEqual({}); }); }); describe('same request id should not forward', () => { test('no forward', () => { expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'g.alicdn.com', requestId: 1 }) ).toEqual({}); expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com??a.js,b.js,c.js', requestId: 1 }) ).toEqual({}); }); }); describe('string urls', () => { test('should forward normal url without query', () => { forward.config.proxy = [['g.alicdn.com', 'g.alicdn.com?t=2']]; expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com', requestId: 1 }).redirectUrl ).toEqual('https://g.alicdn.com?t=2'); expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com#aaaa', requestId: 2 }) ).toEqual({ redirectUrl: 'https://g.alicdn.com?t=2#aaaa' }); expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com/??a.js,b.js,c.js', requestId: 3 }).redirectUrl ).toEqual('https://g.alicdn.com?t=2/??a.js,b.js,c.js'); }); test('should forward normal url with query', () => { forward.config.proxy = [ ['https://g.alicdn.com?t=1', 'https://g.alicdn.com?t=2'] ]; expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com?t=1&k=2', requestId: 1 }).redirectUrl ).toEqual('https://g.alicdn.com?t=2&k=2'); expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com#aaaa', requestId: 2 }).redirectUrl ).toBeFalsy(); expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com?t=1#aaaa', requestId: 3 }).redirectUrl ).toEqual('https://g.alicdn.com?t=2#aaaa'); }); test('should forward url with ?? ', () => { forward.config.proxy = [ ['https://a.com/??a.js,b.js', 'https://b.com/??a.js,b.js'] ]; expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://a.com/??a.js,b.js', requestId: 1 }).redirectUrl ).toEqual('https://b.com/??a.js,b.js'); expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com/#aaaa', requestId: 2 }).redirectUrl ).toBeFalsy(); expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://a.com/??a.js,b.js?t=1#aaa', requestId: 3 }).redirectUrl ).toEqual('https://b.com/??a.js,b.js?t=1#aaa'); }); }); describe('reg urls', () => { test('should forward reg url without query', () => { forward.config.proxy = [['g.(\\w+).com', 'g.alicdn.com?t=2']]; expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g1.alicdn.com', requestId: 1 }).redirectUrl ).toBeFalsy(); expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com', requestId: 2 }).redirectUrl ).toEqual('https://g.alicdn.com?t=2'); expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com#aaaa', requestId: 3 }).redirectUrl ).toEqual('https://g.alicdn.com?t=2#aaaa'); expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com/??a.js,b.js,c.js', requestId: 4 }).redirectUrl ).toEqual('https://g.alicdn.com?t=2/??a.js,b.js,c.js'); }); test('should forward reg url with query', () => { forward.config.proxy = [ ['(.*)g.(.*).com\\?t=1', 'https://g.alicdn.com?t=2'] ]; expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com?t=1&k=2', requestId: 1 }).redirectUrl ).toEqual('https://g.alicdn.com?t=2&k=2'); expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com#aaaa', requestId: 2 }).redirectUrl ).toBeFalsy(); expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com?t=1#aaaa', requestId: 3 }).redirectUrl ).toEqual('https://g.alicdn.com?t=2#aaaa'); }); test('should forward reg url with ??', () => { forward.config.proxy = [ ['(.*)g.alicdn.com/\\?\\?(.*)', '$1alinw.alicdn.com/??$2'] ]; expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com/??a.js,b.js?t=1', requestId: 1 }).redirectUrl ).toEqual('https://alinw.alicdn.com/??a.js,b.js?t=1'); expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com/#aaaa', requestId: 2 }).redirectUrl ).toBeFalsy(); expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com/??a.js,b.js?t=1#aaa', requestId: 3 }).redirectUrl ).toEqual('https://alinw.alicdn.com/??a.js,b.js?t=1#aaa'); }); }); describe('multiple rules', () => { test('should support multiple rules', () => { forward.config.proxy = [ [ '//g.alicdn.com/platform/daily-test/(.*).js$', '//g.alicdn.com/platform/daily-test/$1.json' ], ['g.alicdn.com', 'alinw.alicdn.com'] ]; expect( // @ts-ignore forward.redirectToMatchingRule({ url: 'https://g.alicdn.com/platform/daily-test/isDaily.js', requestId: 1 }).redirectUrl ).toEqual('https://alinw.alicdn.com/platform/daily-test/isDaily.json'); }); }); describe('CORS without access-control-allow-origin', () => { test('should support cors', () => { forward.config.proxy = [ ['http://dev-a.b.com/(.*).json', 'http://dev-c.d.com/$1.json'] ]; forward.config.cors = ['dev-c.d.com']; const testheaderDetails = { frameId: 0, initiator: 'http://dev-a.b.com', method: 'GET', parentFrameId: -1, requestId: '265010', responseHeaders: [ { name: 'Date', value: 'Wed, 11 Jul 2018 12:38:45 GMT' }, { name: 'Content-Type', value: 'application/json;charset=UTF-8' }, { name: 'Transfer-Encoding', value: 'chunked' }, { name: 'Connection', value: 'keep-alive' }, { name: 'Vary', value: 'Accept-Encoding' }, { name: 'X-Application-Context', value: 'a-b-c:7001' }, { name: 'X-Content-Type-Options', value: 'nosniff' }, { name: 'X-XSS-Protection', value: '1; mode=block' }, { name: 'Cache-Control', value: 'no-cache, no-store, max-age=0, must-revalidate' }, { name: 'Pragma', value: 'no-cache' }, { name: 'Expires', value: '0' }, { name: 'X-Frame-Options', value: 'DENY' }, { name: 'Strict-Transport-Security', value: 'max-age=31536000 ; includeSubDomains' }, { name: 'Content-Encoding', value: 'gzip' }, { name: 'Server', value: 'Tengine/Aserver' }, { name: 'EagleEye-TraceId', value: '0a67793015313127251908120e23db' }, { name: 'Timing-Allow-Origin', value: '*' } ], statusCode: 200, statusLine: 'HTTP/1.1 200', tabId: 2988, timeStamp: 1531312725294.728, type: 'xmlhttprequest', url: 'http://dev-c.d.com/overview/type.json?' }; const expectHeaderDetails = [ { name: 'Date', value: 'Wed, 11 Jul 2018 12:38:45 GMT' }, { name: 'Content-Type', value: 'application/json;charset=UTF-8' }, { name: 'Transfer-Encoding', value: 'chunked' }, { name: 'Connection', value: 'keep-alive' }, { name: 'Vary', value: 'Accept-Encoding' }, { name: 'X-Application-Context', value: 'a-b-c:7001' }, { name: 'X-Content-Type-Options', value: 'nosniff' }, { name: 'X-XSS-Protection', value: '1; mode=block' }, { name: 'Cache-Control', value: 'no-cache, no-store, max-age=0, must-revalidate' }, { name: 'Pragma', value: 'no-cache' }, { name: 'Expires', value: '0' }, { name: 'X-Frame-Options', value: 'DENY' }, { name: 'Strict-Transport-Security', value: 'max-age=31536000 ; includeSubDomains' }, { name: 'Content-Encoding', value: 'gzip' }, { name: 'Server', value: 'Tengine/Aserver' }, { name: 'EagleEye-TraceId', value: '0a67793015313127251908120e23db' }, { name: 'Timing-Allow-Origin', value: '*' }, { name: 'access-control-allow-origin', value: 'http://dev-a.b.com' }, { name: 'access-control-allow-credentials', value: 'true' }, { name: 'access-control-allow-methods', value: '*' }, { name: 'access-control-allow-headers', value: 'Content-Type, access-control-allow-headers, Authorization, X-Requested-With, X-Referer' } ]; expect( // @ts-ignore forward.onHeadersReceivedCallback(testheaderDetails).responseHeaders ).toEqual(expectHeaderDetails); }); }); describe('CORS withCredentials', () => { test('should support cors', () => { forward.config.proxy = [ ['http://127.0.0.1/(.*).json', 'http://a.b.com/$1.json'] ]; forward.config.cors = ['http://a.b.com']; const testheaderDetails = { frameId: 0, initiator: 'http://127.0.0.1', method: 'GET', parentFrameId: -1, requestId: '271953', responseHeaders: [ { name: 'Date', value: 'Thu, 12 Jul 2018 02:32:09 GMT' }, { name: 'Content-Type', value: 'application/json;charset=UTF-8' }, { name: 'Transfer-Encoding', value: 'chunked' }, { name: 'Connection', value: 'keep-alive' }, { name: 'Vary', value: 'Accept-Encoding' }, { name: 'X-Content-Type-Options', value: 'nosniff' }, { name: 'X-XSS-Protection', value: '1; mode=block' }, { name: 'Cache-Control', value: 'no-cache, no-store, max-age=0, must-revalidate' }, { name: 'Pragma', value: 'no-cache' }, { name: 'Expires', value: '0' }, { name: 'X-Frame-Options', value: 'DENY' }, { name: 'Strict-Transport-Security', value: 'max-age=31536000 ; includeSubDomains' }, { name: 'access-control-allow-credentials', value: 'true' }, { name: 'access-control-allow-origin', value: 'http://127.0.0.1' }, { name: 'Vary', value: 'Origin' }, { name: 'Access-Control-Expose-Headers', value: 'Set-Cookie' }, { name: 'X-Application-Context', value: 'ottscgadmin:7001' }, { name: 'EagleEye-TraceId-daily', value: '1e37823915313627291994023e' }, { name: 'Content-Encoding', value: 'gzip' }, { name: 'Server', value: 'Tengine/Aserver' }, { name: 'EagleEye-TraceId', value: '0bef992c15313627291782432e3237' }, { name: 'Timing-Allow-Origin', value: '*' } ], statusCode: 200, statusLine: 'HTTP/1.1 200', tabId: 3055, timeStamp: 1531362729284.772, type: 'xmlhttprequest', url: 'http://a.b.com/scg/option.json?' }; const expectHeaderDetails = [ { name: 'Date', value: 'Thu, 12 Jul 2018 02:32:09 GMT' }, { name: 'Content-Type', value: 'application/json;charset=UTF-8' }, { name: 'Transfer-Encoding', value: 'chunked' }, { name: 'Connection', value: 'keep-alive' }, { name: 'Vary', value: 'Accept-Encoding' }, { name: 'X-Content-Type-Options', value: 'nosniff' }, { name: 'X-XSS-Protection', value: '1; mode=block' }, { name: 'Cache-Control', value: 'no-cache, no-store, max-age=0, must-revalidate' }, { name: 'Pragma', value: 'no-cache' }, { name: 'Expires', value: '0' }, { name: 'X-Frame-Options', value: 'DENY' }, { name: 'Strict-Transport-Security', value: 'max-age=31536000 ; includeSubDomains' }, { name: 'Vary', value: 'Origin' }, { name: 'Access-Control-Expose-Headers', value: 'Set-Cookie' }, { name: 'X-Application-Context', value: 'ottscgadmin:7001' }, { name: 'EagleEye-TraceId-daily', value: '1e37823915313627291994023e' }, { name: 'Content-Encoding', value: 'gzip' }, { name: 'Server', value: 'Tengine/Aserver' }, { name: 'EagleEye-TraceId', value: '0bef992c15313627291782432e3237' }, { name: 'Timing-Allow-Origin', value: '*' }, { name: 'access-control-allow-origin', value: 'http://127.0.0.1' }, { name: 'access-control-allow-credentials', value: 'true' }, { name: 'access-control-allow-methods', value: '*' }, { name: 'access-control-allow-headers', value: 'Content-Type, access-control-allow-headers, Authorization, X-Requested-With, X-Referer' } ]; expect( // @ts-ignore forward.onHeadersReceivedCallback(testheaderDetails).responseHeaders ).toEqual(expectHeaderDetails); }); }); describe('CORS withCredentials and no forwardConfig', () => { test('should return {}', () => { forward.config.proxy = []; // @ts-ignore expect(forward.onHeadersReceivedCallback({}).responseHeaders).toEqual( undefined ); }); }); describe('CORS withCredentials and forwardConfig is disabled', () => { test('should return {}', () => { forward.disabled = Enabled.NO; // @ts-ignore expect(forward.onHeadersReceivedCallback({}).responseHeaders).toEqual( undefined ); }); });
the_stack
import AsyncStorage from '@react-native-community/async-storage'; import geoHash from 'latlon-geohash'; import moment from 'moment'; import BackgroundTimer from 'react-native-background-timer'; import { removeGeoPastExposure, setExposures, updateBlePastExposure, updateGeoPastExposure } from '../actions/ExposuresActions'; import { initLocale } from '../actions/LocaleActions'; import config from '../config/config'; import { DISMISSED_EXPOSURES, IS_IOS, LAST_FETCH_TS } from '../constants/Constants'; import { IntersectionSickDatabase, UserClusteredLocationsDatabase, UserLocationsDatabase } from '../database/Database'; import store from '../store'; import { Cluster, Exposure, ExposureProperties, Location, SickJSON } from '../types'; import { initBLETracing, match } from './BLEService'; import { onError } from './ErrorService'; import { registerLocalNotification } from './PushService'; import { downloadAndVerifySigning } from './SigningService'; // tslint:disable-next-line:no-var-requires const haversine = require('haversine'); export const startForegroundTimer = async () => { await checkBLESickPeople(); await checkGeoSickPeople(); BackgroundTimer.runBackgroundTimer(backgroundTimerFn, config().fetchMilliseconds); if (IS_IOS) { // background timer to try and restarting BLE service in IOS BackgroundTimer.runBackgroundTimer(initBLETracing, config().fetchMilliseconds); } await AsyncStorage.setItem( LAST_FETCH_TS, JSON.stringify(moment().valueOf()), ); }; const backgroundTimerFn = async () => { await checkBLESickPeople(); await checkGeoSickPeople(); await AsyncStorage.setItem( LAST_FETCH_TS, JSON.stringify(moment().valueOf()), ); }; export const queryDB = async (isClusters: boolean) => { const db = new UserLocationsDatabase(); const cdb = new UserClusteredLocationsDatabase(); const rows = isClusters ? await cdb.listClusters() : await db.listSamples(); return rows; }; export const checkBLESickPeople = async () => { try { const lastFetch: number = JSON.parse((await AsyncStorage.getItem(LAST_FETCH_TS)) || '0'); // check if interval is above the minimum delay if (moment(lastFetch).add(config().minimumBLEFetchIntervalMin, 'm').isAfter(moment())) { return; } const bleMatches: any[] = await match(); if (bleMatches.length > 0) { const bleMatchNotUTC = bleMatches.sort((matchA, matchB) => matchB.startContactTimestamp - matchA.startContactTimestamp)[0]; // convert ble match to have normal time(it lacks the ms's) const bleMatch = { ...bleMatchNotUTC, startContactTimestamp: parseInt(bleMatchNotUTC.startContactTimestamp.toString()) * 1000, endContactTimestamp: parseInt(bleMatchNotUTC.endContactTimestamp.toString()) * 1000 }; bleMatch.BLETimestamp = moment(Math.floor((bleMatch.startContactTimestamp + bleMatch.endContactTimestamp) / 2)).startOf('hour').valueOf(); const sickDB = new IntersectionSickDatabase(); // check if BLe match is not a duplicate const hasBLTS = await sickDB.containsBLE(bleMatch.BLETimestamp); if (!hasBLTS) { await checkBleAndGeoIntersection(bleMatch, sickDB); } } } catch (error) { onError({ error }); } }; const checkBleAndGeoIntersection = async ({ startContactTimestamp, endContactTimestamp, BLETimestamp }, sickDB) => { const exposures: Exposure[] = await sickDB.listAllRecords(); const overlappingGeoExposure = exposures.find((properties) => { return properties?.OBJECTID && (Math.min(properties.toTime, endContactTimestamp) - Math.max(properties.fromTime, startContactTimestamp)) > 0; }); if (overlappingGeoExposure) { const newExposure = await sickDB.MergeBLEIntoSickRecord(overlappingGeoExposure.OBJECTID, BLETimestamp); // if user already told us he was not there - alert him by removing exposure from dismissed and resetting it in exposures if (!overlappingGeoExposure.wasThere) { // remove exposure from dismissed exposures list const dismissedExposures = await AsyncStorage.getItem(DISMISSED_EXPOSURES); const parsedDismissedExposures: number[] = JSON.parse(dismissedExposures ?? ''); await AsyncStorage.setItem(DISMISSED_EXPOSURES, JSON.stringify(parsedDismissedExposures.filter((num: number) => num !== overlappingGeoExposure.OBJECTID))); store().dispatch(removeGeoPastExposure(overlappingGeoExposure.OBJECTID)); await onSickPeopleNotify([{ ...overlappingGeoExposure, wasThere: true, BLETimestamp }]); } // update in past exposures store().dispatch(updateGeoPastExposure({ properties: { ...overlappingGeoExposure, wasThere: true, BLETimestamp } })); } else { const lastExposure = exposures.filter(properties => properties.BLETimestamp).sort((matchA, matchB) => matchB.BLETimestamp - matchA.BLETimestamp)[0]; // check if latest ble exposure is before the new exposure if (!lastExposure?.BLETimestamp || moment(BLETimestamp).isAfter(lastExposure.BLETimestamp)) { // new exposure that doesn't overlap const sick = await sickDB.addBLESickRecord(BLETimestamp); await onSickPeopleNotify([sick]); } } }; export const checkGeoSickPeople = async () => { try { const lastFetch: number = JSON.parse((await AsyncStorage.getItem(LAST_FETCH_TS)) || '0'); // check if interval is above the minimum delay if (moment(lastFetch).add(config().minimumGeoFetchIntervalMin, 'm').isAfter(moment())) { return; } const responseJson: SickJSON = await downloadAndVerifySigning(config().dataUrl_utc); const myData = await queryDB(config().intersectWithClusters); const shouldFilterByGeohash = !!responseJson.features[0]?.properties?.geohashFilter; const sickPeopleIntersected: any = shouldFilterByGeohash ? getIntersectingSickRecordsByGeoHash(myData, responseJson) : getIntersectingSickRecords(myData, responseJson); if (sickPeopleIntersected.length > 0) { const dbSick = new IntersectionSickDatabase(); const filteredIntersected: Exposure[] = []; for (const currSick of sickPeopleIntersected) { const queryResult = await dbSick.containsObjectID( currSick.properties.Key_Field, ); // exposure is not a duplicate if (!queryResult) { const overlappingBLEExposure = await checkGeoAndBleIntersection(currSick, dbSick); // BLE was found if (overlappingBLEExposure?.BLETimestamp) { // merge geo and ble exposure await dbSick.MergeGeoIntoSickRecord(currSick, overlappingBLEExposure.BLETimestamp); // update merged exposure in store store().dispatch(updateBlePastExposure({ properties: { ...currSick.properties, BLETimestamp: overlappingBLEExposure.BLETimestamp, wasThere: true } })); } else { const sick = await dbSick.addSickRecord(currSick); filteredIntersected.push(sick); } } } if (filteredIntersected.length > 0) { await onSickPeopleNotify(filteredIntersected); } } } catch (error) { onError({ error }); } }; export const getIntersectingSickRecords = (myData: Location[], sickRecordsJson: SickJSON) => { const sickPeopleIntersected: any = []; if (myData.length === 0) { console.log('Could not find data'); } else { // for each feature in json data sickRecordsJson.features.map((sickRecord: Exposure) => { // for each raw in user data myData.reverse().forEach((userRecord: Location) => { if ( isTimeOverlapping(userRecord, sickRecord) && isSpaceOverlapping(userRecord, sickRecord) ) { // add sick people you intersects sickRecord.properties.fromTime_utc = Math.max(userRecord.startTime, sickRecord.properties.fromTime_utc); sickRecord.properties.toTime_utc = userRecord.endTime; sickPeopleIntersected.push(sickRecord); } }); }); } return [...new Set(sickPeopleIntersected)]; }; export const getIntersectingSickRecordsByGeoHash = (myData: Location[], sickRecordsJson: SickJSON) => { const sickPeopleIntersected: any[] = []; if (myData.length === 0) { console.log('Could not find data'); return sickPeopleIntersected; } const mappedLocations: { [key: string]: Location[] } = {}; myData.forEach((location) => { // fix for geoHashes entered with a "'" from google timeline. const locationGeohashPrefix = location.geoHash.replace(/[']/g, '').slice(0, sickRecordsJson.features[0].properties.geohashFilter.length); if (mappedLocations[locationGeohashPrefix]) { mappedLocations[locationGeohashPrefix].push(location); } else { mappedLocations[locationGeohashPrefix] = [location]; } }); // for each feature in json data sickRecordsJson.features.forEach((sickRecord: Exposure) => { const sickRecordGeohashPrefix = sickRecord.properties.geohashFilter; // get 8 neighbors of geolocation const neighborsArr = [sickRecordGeohashPrefix, ...Object.values(geoHash.neighbours(sickRecordGeohashPrefix))]; neighborsArr.forEach((geo) => { // for each raw in user data if (mappedLocations[geo]) { mappedLocations[geo].forEach((userRecord: Location) => { if (isTimeOverlapping(userRecord, sickRecord) && isSpaceOverlapping(userRecord, sickRecord)) { // add sick people you intersects sickRecord.properties.fromTime_utc = Math.max(userRecord.startTime, sickRecord.properties.fromTime_utc); sickRecord.properties.toTime_utc = userRecord.endTime; sickPeopleIntersected.push(sickRecord); } }); } }); }); const sickPeopleIntersectedSet = new Set(sickPeopleIntersected); // sort array from the most early to last return [...sickPeopleIntersectedSet].sort((intersectA, intersectB) => intersectB.fromTime_utc - intersectA.fromTime_utc); }; const checkMillisecondsDiff = (to: number, from: number) => { return to - from > (config().intersectWithClusters ? config().intersectMillisecondsWithCluster : config().intersectMilliseconds); }; export const isTimeOverlapping = (userRecord: Location, sickRecord: Exposure) => { return checkMillisecondsDiff( Math.min(userRecord.endTime, sickRecord.properties.toTime_utc), Math.max(userRecord.startTime, sickRecord.properties.fromTime_utc) ); }; export const isSpaceOverlapping = (clusterOrLocation: Location | Cluster, { properties: { radius }, geometry: { coordinates } }: Exposure) => { const start = { latitude: clusterOrLocation.lat, longitude: clusterOrLocation.long, }; const end = { latitude: coordinates[config().sickGeometryLatIndex], longitude: coordinates[config().sickGeometryLongIndex], }; return haversine(start, end, { threshold: (radius || config().meterRadius) + (config().intersectWithClusters ? clusterOrLocation.radius : 0), unit: config().bufferUnits }); }; const checkGeoAndBleIntersection = async (currSick, dbSick) => { const exposures: ExposureProperties[] = await dbSick.listAllRecords(); return exposures.find((exposure) => { // if its a geo exposure or exposure doesn't have ble time stamp if (exposure.OBJECTID !== null || !exposure.BLETimestamp) { return false; } const bleStart = moment(exposure.BLETimestamp).valueOf(); const bleEnd = moment(exposure.BLETimestamp).add(1, 'hours').valueOf(); return (Math.min(currSick.properties.toTime_utc, bleEnd) - Math.max(currSick.properties.fromTime_utc, bleStart)) > 0; }); }; export const onSickPeopleNotify = async (sickPeopleIntersected: ExposureProperties[]) => { try { if (sickPeopleIntersected.length > 0) { await store().dispatch(setExposures(sickPeopleIntersected.map((exposure: any) => ({ properties: { ...exposure } })))); const { locale, notificationData } = await store().dispatch(initLocale()); await registerLocalNotification( notificationData.sickMessage[locale].title, notificationData.sickMessage[locale].body, notificationData.sickMessage.duration, 'ms', ); } } catch (error) { onError({ error }); } };
the_stack
import ko = require('knockout'); import mapping = require('knockout.mapping'); import services = require('services/Service'); import site = require('Site'); function translateOrder(source) { //source.OrderDate = services.fixJsonDates(source.OrderDate); var order = mapping.fromJS(source); var orderDetails = order.OrderDetails(); order.OrderDetails = ko.observableArray(); for (var i = 0; i < orderDetails.length; i++) { orderDetails[i].Amount = ko.computed(function () { return this.Price() * this.Quantity(); }, orderDetails[i]); order.OrderDetails.push(orderDetails[i]); } order.ProductsAmount = ko.computed(function () { var amount = 0; for (var i = 0; i < orderDetails.length; i++) { amount = amount + orderDetails[i].Amount(); } return amount; }, order); order.StatusText = ko.computed(function () { var status = this.Status(); switch (status) { case 'WaitingForPayment': return '待付款'; case 'Paid': return '已付款'; case 'Send': return '已发货'; case 'Canceled': return '已取消'; case 'Finish': return '已完成' case 'Received': return '已收货'; default: return ''; } }, order); order.ReceiptInfoId = ko.observable(); order.ReceiptAddress.extend({ required: true }); return order; }; function translateReceipt(source) { var item = mapping.fromJS(source); item.Detail = ko.computed(function () { var result = this.ProvinceName() + ' ' + this.CityName() + ' ' + this.CountyName() + ' ' + this.Address(); result = result + ' 联系人: ' + this.Consignee(); result = result + ' 电话:' if (this.Phone() != null && this.Mobile() != null) result = result + this.Phone() + ', ' + this.Mobile(); else result = result + (this.Phone() || this.Mobile()); return result; }, item); item.Name.extend({ required: true }); item.ProvinceId.extend({ required: { onlyIf: $.proxy(function () { return this.Name(); }, item) } }); item.CityId.extend({ required: { onlyIf: $.proxy(function () { return this.ProvinceId(); }, item) } }); item.CountyId.extend({ required: { onlyIf: $.proxy(function () { return this.CityId(); }, item) } }); item.AreaCode = ko.observable(); item.PhoneNumber = ko.observable(); item.BranchNumber = ko.observable(); item.AreaCode.extend({ required: { onlyIf: $.proxy(function () { return this.PhoneNumber(); }, item) } }); item.PhoneNumber.extend({ required: { onlyIf: $.proxy(function () { return this.AreaCode(); }, item) } }); item.Phone = ko.computed({ read: function () { var phone = ''; var areaCode = $.trim(this.AreaCode()); var phoneNumber = $.trim(this.PhoneNumber()); var branchNumber = $.trim(this.BranchNumber()); if (areaCode != '' && phoneNumber != '') phone = areaCode + '-' + phoneNumber; if (phone != '' && branchNumber != '') phone = phone + '-' + branchNumber; return phone == '' ? null : phone; }, write: function (value: string) { if (value == null || value == '') return; var arr = value.split('-'); this.AreaCode(arr[0]); this.PhoneNumber(arr[1]); this.BranchNumber(arr[2]); } }, item); item.Address.extend({ required: true }); item.Consignee.extend({ required: true }); item.Mobile.extend({ required: true }); item.Phone(source.Phone); return item; } class OrderInfo { notPaidCount = ko.observable(0) toReceiveCount = ko.observable(0) evaluateCount = ko.observable(2) } class AccountService { //====================================================== // 说明:事件 receiptInfoUpdated = $.Callbacks() receiptInfoInserted = $.Callbacks() //====================================================== orderStatusChanged = (oldStatus: string, newStatus: string) => { //var status = ko.unwrap(order.Status); var old_count: KnockoutObservable<number>; var new_count: KnockoutObservable<number>; var get_counter = (status: string): KnockoutObservable<number> => { var counter: KnockoutObservable<number> switch (status) { case 'WaitingForPayment': counter = this.orderInfo.notPaidCount; break; case 'Send': counter = this.orderInfo.toReceiveCount break; case 'Received': counter = this.orderInfo.evaluateCount; break; } return counter; } old_count = get_counter(oldStatus); new_count = get_counter(newStatus); if (old_count) old_count(old_count() - 1); if (new_count) new_count(new_count() + 1); } newReceiptInfo = () => { var result = services.callRemoteMethod('Address/NewReceiptInfo').then(function (item) { return translateReceipt(item); }); return result; //return $.Deferred().resolve(new ReceiptInfo()); } getReceiptInfo = (id) => { var result = services.callRemoteMethod('Address/GetReceiptInfo', { id: id }); return result; } getReceiptInfos = () => { /// <returns type="jQuery.Deferred"/> var result = services.get<Array<any>>(services.config.shopServiceUrl, 'Address/GetReceiptInfos').then(function (items) { var result = []; for (var i = 0; i < items.length; i++) { result[i] = translateReceipt(items[i]); } // return result; }); return result; } /** * @param string receiptInfoId 收货地址编号 * @returns JQueryPromise<any> */ deleteReceiptInfo(receiptInfoId: string): JQueryPromise<any> { var result = services.callRemoteMethod('Address/DeleteReceiptInfo', { receiptInfoId: receiptInfoId }); return result; } saveReceiptInfo = (receiptInfo) => { /// <summary>保存用户的收货地址</summary> /// <param name="receiptInfo" type="models.receiptInfo"/> /// <returns type="jQuery.Deferred"/> var obj = mapping.toJS(receiptInfo); obj.RegionId = receiptInfo.CountyId(); var self = this; var result = services.callMethod(services.config.shopServiceUrl, 'Address/SaveReceiptInfo', obj) .done(function (data) { receiptInfo.Id(data.Id); receiptInfo.IsDefault(data.IsDefault); if (receiptInfo.Id()) { self.receiptInfoUpdated.fire(receiptInfo); } else { self.receiptInfoInserted.fire(receiptInfo); } }); return result; } /** * 设置默认的收货地址 * param string receiptInfoId 收货地址编号 */ setDefaultReceipt(receiptInfoId): JQueryPromise<any> { var result = services.callRemoteMethod('Address/SetDefaultReceiptInfo', { receiptInfoId: receiptInfoId }); return result; } /** * 获取用户的优惠券 * returns JQueryPromise<any[]> */ getMyCoupons = () => { var args = {}; var result = services.get(services.config.shopServiceUrl, 'Coupon/GetMyCoupons', args); return result; } receiveCoupon = (coupon) => { /// <param name="coupon" type="models.coupon"/> var result = services.callRemoteMethod('Coupon/ReceiveCouponCode', { couponId: coupon.id() }); return result; } useCoupon = (coupon) => { var args = { code: coupon.code() }; var result = services.callRemoteMethod('Coupon/UseCouponCode', args); return result; } getProvinces(): JQueryPromise<any[]> { var result = services.get<any[]>(services.config.shopServiceUrl, 'Address/GetProvinces'); return result; } getCities(province): JQueryPromise<any[]> { var guidRule = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; if (guidRule.test(province)) return services.get(services.config.shopServiceUrl, 'Address/GetCities', { provinceId: province }); return services.get(services.config.shopServiceUrl, 'Address/GetCities', { provinceName: province });; } getCounties = (city) => { /// <summary>获取县</summary> /// <returns type="jQuery.Deferred"/> var cityId; if (typeof city == 'string') cityId = city; else cityId = city.id(); var result = services.get(services.config.shopServiceUrl, 'Address/GetCounties', { cityId: cityId }); return result; } getMyOrders = (status, pageIndex) => { /// <summary>获取当前登录用户的订单</summary> var filter; if (status) { filter = 'it.Status=="' + status + '"'; } var args = { filter: filter, StartRowIndex: pageIndex * services.defaultPageSize, MaximumRows: services.defaultPageSize }; var result = services.callRemoteMethod('Order/GetMyOrders', args) .then(function (orders) { for (var i = 0; i < orders.length; i++) { orders[i] = translateOrder(orders[i]); } return orders; }); result.done($.proxy(function (orders) { this._result.loadCompleted = orders.length < services.defaultPageSize; }, { _result: result })); return result; } confirmReceived = (orderId: string): JQueryPromise<any> => { /// <summary>确认已收到货</summary> /// <param name="orderId" type="String"/> var result = services.callMethod(services.config.shopServiceUrl, 'Order/ConfirmReceived', { orderId: orderId }) .then((data) => { this.orderStatusChanged('Send', data.Status); return data; }); return result; } cancelOrder = (orderId): JQueryPromise<any> => { /// <summary>取消订单</summary> /// <param name="orderId" type="String"/> /// <returns type="jQuery.Deferred"/> var result = services.callRemoteMethod('Order/CancelOrder', { orderId: orderId }) .then((data) => { this.orderStatusChanged('WaitingForPayment', data.Status); return data; }); return result; } purchaseOrder = (orderId: string, amount: number): JQueryPromise<any> => { var weixin = services['weixin']; var openid = weixin.openid(); var notify_url = services.config.weixinServiceUrl + 'WeiXin/OrderPurchase/' + services.config.appId; var out_trade_no = ko.unwrap(orderId).replace(/\-/g, ''); return weixin.pay(openid, notify_url, out_trade_no, site.config.storeName, amount) .done(() => { this.orderStatusChanged('WaitingForPayment', 'Paid'); }); } /** * 评价晒单 */ evaluateProduct(orderDetailId: string, score: number, evaluation: string, anonymous: boolean, imageDatas: string, imageThumbs: string) { var data = { orderDetailId, evaluation, imageDatas, score, imageThumbs, anonymous }; var result = services.callMethod(services.config.shopServiceUrl, 'Product/EvaluateProduct', data).done(() => { var count = this.orderInfo.evaluateCount(); this.orderInfo.evaluateCount(count - 1); }) return result; } getSquareCode = () => { var deferred = $.Deferred(); services.callRemoteMethod('ShouTao/SquareCodeTicket').done(function (args) { var url; if (args.ticket == '' || args.ticket == null) url = '//code_no.jpg'; else url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' + args.ticket; deferred.resolve(url); }).fail(function () { deferred.reject(); }); return deferred; } /** * 发送修改密码的验证码 */ sendChangePasswordVerifyCode = (mobile) => { return services.callRemoteMethod('VerifyCode/SendChangePassword', { mobile: mobile }); } bind = (username, password) => { return $.ajax({ url: '/User/Bind', data: { username: username, password: password } }).done(function (result) { if (result.Code == 'Success') { alert('绑定成功'); } else { alert(result.Message); } }); } /** * 获取用户账户的余额 */ getBalance = () => { return services.callMethod(services.config.accountServiceUrl, 'Account/GetAccount').then(function (data) { return (new Number(data.Balance)).valueOf(); }); } /** * 获取用户信息 */ userInfo = () => { return services.get<any>(services.config.memberServiceUrl, 'User/CurrentUserInfo'); } orderInfo = new OrderInfo() getToCommentProducts(): LoadListPromise<any> { var result: LoadListPromise<any> = <LoadListPromise<any>>services.callMethod(services.config.shopServiceUrl, 'Product/GetToCommentProducts') .done(() => { result.loadCompleted = true }); return result; } getCommentedProducts(): LoadListPromise<any> { var result: LoadListPromise<any> = <LoadListPromise<any>>services.callMethod(services.config.shopServiceUrl, 'Product/GetCommentedProducts') .done(() => { result.loadCompleted = true }); return result; } getScoreDetails(): LoadListPromise<any> { var result: LoadListPromise<any> = <LoadListPromise<any>>services.callMethod(services.config.accountServiceUrl, 'Account/GetScoreDetails') .done(() => { result.loadCompleted = true; }); return result; } getBalanceDetails(): LoadListPromise<any> { var result: LoadListPromise<any> = <LoadListPromise<any>>services.callMethod(services.config.accountServiceUrl, 'Account/GetBalanceDetails') .done(() => { result.loadCompleted = true; }); return result; } } module models { class user { userName = ko.observable(''); nickName = ko.observable(''); realName = ko.observable(''); gender = ko.observable('Male'); email = ko.observable(''); password = ko.observable(''); score = ko.observable(0); mobile = ko.observable(); openid = ko.observable(); } class ReceiptInfo { Address = ko.observable(); CityId = ko.observable(); CityName = ko.observable(); Consignee = ko.observable(); CountyId = ko.observable(); CountyName = ko.observable(); Detail = ko.observable(); FullAddress = ko.observable(); Id = ko.observable(); IsDefault = ko.observable(); Mobile = ko.observable(); Name = ko.observable(); Phone = ko.observable(); PhoneNumber = ko.observable(); PostalCode = ko.observable(); ProvinceId = ko.observable(); ProvinceName = ko.observable(); } } export = <AccountService>(services['account'] = services['account'] || new AccountService());
the_stack
import { DataTypes } from 'https://raw.githubusercontent.com/eveningkid/denodb/abed3063dd92436ceb4f124227daee5ee6604b2d/mod.ts'; import { v4 } from "https://deno.land/std/uuid/mod.ts"; /** * @summary Interface of all allowed validation opts. * @interface */ export interface ValidationOpts { minLength?: number, maxLength?: number, regExp?: RegExp | string, // Term 'regExp', instead of 'regEx' has been in JS world for quite a while, hence it's being used here as well unique?: any, // Originally accepts a Model, if false, won't perform any checking (can be omitted as well) required?: boolean, // Allows nullable values, but not the undefined ones email?: boolean, uuid?: boolean, includes?: any, // Please note that this is case sensitive. Transform the field value and all array elements to lowercase and then compare them if needed. excludes?: any, notIn?: Array<any>, in?: Array<any>, equals?: any, between?: Array<number>, gt?: number, gte?: number, lt?: number, lte?: number } /** * @summary Interface for validation results (return values of each validator method) * @interface */ export interface ValidationResult { success: boolean, invalidFields: Array<any> } /** * @summary Interface for validation rules (An object containing props whose values correlate to ValidationOpts). * @interface */ export interface ValidationRules { [field: string]: ValidationOpts } export interface InvalidField { name: string, passedValue: any, error: string } class Validator { public static async isModelDataValid(model : any, data : any) : Promise<any> { const modelFields = model.fields; for (const field in modelFields) { if (!Object.prototype.hasOwnProperty.call(data, field) && (!modelFields[field].allowNull && typeof modelFields[field].allowNull === 'boolean')) return { success: false, validationFailedAt: field }; this.validateField(modelFields, field, data); } return { success: true }; } private static validateField(modelFields : any, field : any, value : any) { const fieldType = modelFields[field]; /** * @summary Trivial validation, as an example */ if (fieldType === DataTypes.INTEGER) { const boundary = Math.pow(2, 31); return value <= boundary && value >= -boundary; } /** * @summary Any passed UUID ought to be UUIDv4 */ if (fieldType === DataTypes.UUID) return value.match(/^[0-9A-F]{8}-[0-9A-F]{4}-[4][0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i); } public static sanitize(allowedFields : Array<string>, data : any) { for (let field in data) { if (Object.prototype.hasOwnProperty.call(data, field) && !allowedFields.includes(field)) delete data[field]; } return data; } public static validateModel(model: any, fields: any): ValidationResult { return { success: true, invalidFields: [] }; } /** * @summary Consumes the assigned rules and fields for validations to iteratively validate passed payload. * @param rules * @param fields */ public static async validate(rules: ValidationRules, fields: object = {}): Promise<ValidationResult> { const invalidFields: Array<string> = []; for (const field in rules) { if (!Object.prototype.hasOwnProperty.call(rules, field)) continue; for (const rule in rules[field]) { if (!Object.prototype.hasOwnProperty.call(rules[field], rule)) continue; const func = `validate${rule.charAt(0).toUpperCase() + rule.slice(1)}`; // @ts-ignore if (this[func]) { // @ts-ignore const validationError = await (this[func] as any)(field, fields[field], rules[field][rule]); if (validationError) { invalidFields.push(validationError); break; } } } } return { success: invalidFields.length === 0, invalidFields }; } /** * @summary Checks whether field string lengths is below minimum characters required rule. * @param fieldName * @param fieldValue * @param minLength */ private static validateMinLength(fieldName: string, fieldValue: string, minLength: number): InvalidField | undefined { return String(fieldValue).length < minLength ? { name: fieldName, passedValue: fieldValue, error: `${fieldName} should be at least ${minLength} characters long.` } : undefined; } /** * @summary Checks if field string length exceeds declared rule length. * @param fieldName * @param fieldValue * @param maxLength */ private static validateMaxLength(fieldName: string, fieldValue: string, maxLength: number): InvalidField | undefined { return String(fieldValue).length > maxLength ? { name: fieldName, passedValue: fieldValue, error: `${fieldName} should not exceed ${maxLength} characters limit.` } : undefined; } /** * @summary Checks if there's an already existing REST resource with specified field value bonded to field name. * It uses a model as a reference to search for another occurrence. * Other instances, objects or types won't work. Validation will function normally if and only if the * passed model is inheriting Model class from '/lib/Model.ts' which inherits DenoDB's Model. * @param fieldName * @param fieldValue * @param model */ private static async validateUnique(fieldName: string, fieldValue: string, model: any): Promise<InvalidField | undefined> { if (!model) return undefined; const isDuplicate = await this.isDuplicate(model, fieldName, fieldValue); return isDuplicate ? { name: fieldName, passedValue: fieldValue, error: `A record with this ${fieldName} already exists.` } : undefined; } /** * @summary Executes the query and returns a boolean indicating whether there's an occurrence or not. * @param model * @param field * @param value */ private static async isDuplicate(model: any, field: string, value: any): Promise<boolean> { const duplicate = await model.where({ [field] : value }).take(1).get(); return !!duplicate.length; } /** * @summary Checks if passed string matches the regular expression pattern * @param fieldName * @param fieldValue * @param regExp */ private static validateRegExp(fieldName: string, fieldValue: string, regExp: RegExp | string): InvalidField | undefined { return fieldValue && !fieldValue.toString().match(regExp) ? { name: fieldName, passedValue: fieldValue, error: `${fieldName}'s format is invalid.` } : undefined; } /** * @summary Checks if required field is present. * @param fieldName * @param fieldValue */ private static validateRequired(fieldName: string, fieldValue: boolean): InvalidField | undefined { return fieldValue === undefined || !fieldValue.toString().length ? { name: fieldName, passedValue: fieldValue, error: `${fieldName} is required.` } : undefined; } /** * @summary Checks if passed field value matches email regular expression * @param fieldName * @param fieldValue */ private static validateEmail(fieldName: string, fieldValue: string): InvalidField | undefined { return fieldValue && !fieldValue.toString().match(/^(([^<>()\[\].,;:\s@"]+(\.[^<>()\[\].,;:\s@"]+)*)|(".+"))@(([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{2,})$/i) ? { name: fieldName, passedValue: fieldValue, error: `${fieldName} doesn't have an email format.` } : undefined; } /** * @summary Validates field with expected UUID value. * @param fieldName * @param fieldValue */ private static validateUuid(fieldName: string, fieldValue: string): InvalidField | undefined { return !v4.validate(fieldValue) ? { name: fieldName, passedValue: fieldValue, error: `${fieldName} must be an UUID.` } : undefined; } /** * @summary Checks if passed array includes predefined value. * @param fieldName * @param fieldValue * @param toBeIncluded */ private static validateIncludes(fieldName: string, fieldValue: any, toBeIncluded: any): InvalidField | undefined { return fieldValue && !fieldValue.includes(toBeIncluded) ? { name: fieldName, passedValue: fieldValue, error: `${fieldName} should include ${toBeIncluded}.` } : undefined; } /** * @summary Checks if passed array excludes predefined value. * @param fieldName * @param fieldValue * @param toBeExcluded */ private static validateExcludes(fieldName: string, fieldValue: any, toBeExcluded: any): InvalidField | undefined { return fieldValue && fieldValue.includes(toBeExcluded) ? { name: fieldName, passedValue: fieldValue, error: `${fieldName} should exclude ${toBeExcluded}.` } : undefined; } /** * @summary Validates if a passed value isn't part of a predefined array * @param fieldName * @param fieldValue * @param array */ private static validateNotIn(fieldName: string, fieldValue: any, array: Array<any>): InvalidField | undefined { return array && array.includes(fieldValue) ? { name: fieldName, passedValue: fieldValue, error: `${fieldValue} is part of ${fieldName}.` } : undefined; } /** * @summary Validates if a passed value isn part of a predefined array * @param fieldName * @param fieldValue * @param array */ private static validateIn(fieldName: string, fieldValue: any, array: Array<any>): InvalidField | undefined { return array && !array.includes(fieldValue) ? { name: fieldName, passedValue: fieldValue, error: `${fieldValue} is not part of ${fieldName}.` } : undefined; } /** * @summary Validates values equality * @param fieldName * @param fieldValue * @param equalWith */ private static validateEquals(fieldName: string, fieldValue: any, equalWith: any): InvalidField | undefined { return fieldValue !== equalWith ? { name: fieldName, passedValue: fieldValue, error: `${fieldName}'s ${fieldValue} is not equal with expected ${equalWith}.` } : undefined; } /** * @summary Checks if field value is in range. There should be two numbers in an array. It refers to the first and the last one. * @param fieldName * @param fieldValue * @param range */ private static validateBetween(fieldName: string, fieldValue: any, range: Array<number>): InvalidField | undefined { return fieldValue < range[0] || fieldValue > range[range.length - 1] ? { name: fieldName, passedValue: fieldValue, error: `${fieldName}'s value (${fieldValue}) is not in desired range.` } : undefined; } /** * @summary Checks if the passed value is greater than the predefined one * @param fieldName * @param fieldValue * @param comparedTo */ private static validateGt(fieldName: string, fieldValue: any, comparedTo: number): InvalidField | undefined { return !(fieldValue > comparedTo) ? { name: fieldName, passedValue: fieldValue, error: `${fieldName}'s value (${fieldValue}) is not greater than ${comparedTo}.` } : undefined; } /** * @summary Checks if the passed value is greater than or equal to the predefined one * @param fieldName * @param fieldValue * @param comparedTo */ private static validateGte(fieldName: string, fieldValue: any, comparedTo: number): InvalidField | undefined { return !(fieldValue >= comparedTo) ? { name: fieldName, passedValue: fieldValue, error: `${fieldName}'s value (${fieldValue}) is not greater than or equal to ${comparedTo}.` } : undefined; } /** * @summary Checks if the passed value is less than the predefined one * @param fieldName * @param fieldValue * @param comparedTo */ private static validateLt(fieldName: string, fieldValue: any, comparedTo: number): InvalidField | undefined { return !(fieldValue < comparedTo) ? { name: fieldName, passedValue: fieldValue, error: `${fieldName}'s value (${fieldValue}) is not less than ${comparedTo}.` } : undefined; } /** * @summary Checks if the passed value is less than or equal to the predefined one * @param fieldName * @param fieldValue * @param comparedTo */ private static validateLte(fieldName: string, fieldValue: any, comparedTo: number): InvalidField | undefined { return !(fieldValue <= comparedTo) ? { name: fieldName, passedValue: fieldValue, error: `${fieldName}'s value (${fieldValue}) is not less than or equal to ${comparedTo}.` } : undefined; } } export default Validator;
the_stack
import 'jest-extended'; import { toString, bigIntToJSON, isNotNil } from '@terascope/utils'; import { DataTypeFields, ESGeoShapeMultiPolygon, ESGeoShapePoint, ESGeoShapePolygon, ESGeoShapeType, FieldType, GeoShapeMultiPolygon, GeoShapePoint, GeoShapePolygon, GeoShapeType } from '@terascope/types'; import { Builder, ReadableData, Vector, WritableData } from '../../src'; describe('Vector', () => { type Case = [ type: FieldType, input: any[], childConfig?: DataTypeFields, output?: any[], invalid?: any[] ]; const nowDate = new Date(); const now = nowDate.getTime(); const testCases: Case[] = [ [ FieldType.Any, ['foo', 'bar', 1, 2, null, null] ], [ FieldType.String, ['foo', 'bar', true, 1, 2, null, undefined], undefined, ['foo', 'bar', 'true', '1', '2', null, null], [{ foo: 'bar' }] ], [ FieldType.Float, [12.344, '2.01', BigInt(200), 1, 2, null, undefined], undefined, [12.344, 2.01, 200, 1, 2, null, null] ], [ FieldType.Integer, [12.344, '2.01', BigInt(200), 1, 2, null, undefined], undefined, [12, 2, 200, 1, 2, null, null], [-(2 ** 31) - 1, 2 ** 31 + 1, 'foo'] ], [ FieldType.Byte, [12.344, '2.01', -1, 2, null, undefined], undefined, [12, 2, -1, 2, null, null], [128, -129, 'bar'] ], [ FieldType.Short, [12.344, '-2.01', 1000, 2, null, undefined], undefined, [12, -2, 1000, 2, null, null], [32_768, -32_769, 'baz', '++1'] ], [ FieldType.Long, [12.344, '2.01', BigInt(200), 1, null, undefined], undefined, [BigInt(12), BigInt(2), BigInt(200), BigInt(1), null, null] ], [ FieldType.Boolean, ['yes', 'no', true, false, 0, 1, null, undefined], undefined, [true, false, true, false, false, true, null, null], ['Y E S', 'foo', 23] ], [ FieldType.Date, [nowDate, nowDate.toISOString(), now, '1941-08-20T07:00:00.000Z', null, undefined], undefined, [ nowDate.toISOString(), nowDate.toISOString(), nowDate.toISOString(), '1941-08-20T07:00:00.000Z', null, null ], ['not a date', Number.NaN], ], [ FieldType.IP, [ '8.8.8.8', '192.172.1.18', '11.0.1.18', '2001:db8:85a3:8d3:1319:8a2e:370:7348', 'fe80::1ff:fe23:4567:890a%eth2', '2001:DB8::1', '172.16.0.1', '10.168.0.1', 'fc00:db8:85a3:8d3:1319:8a2e:370:7348', null, undefined ], undefined, [ '8.8.8.8', '192.172.1.18', '11.0.1.18', '2001:db8:85a3:8d3:1319:8a2e:370:7348', 'fe80::1ff:fe23:4567:890a%eth2', '2001:DB8::1', '172.16.0.1', '10.168.0.1', 'fc00:db8:85a3:8d3:1319:8a2e:370:7348', null, null ] ], [ FieldType.IPRange, [ '1.2.3.4/32', '8.8.0.0/12', '2001:0db8:0123:4567:89ab:cdef:1234:5678/128', '2001::1234:5678/128', null, undefined ], undefined, [ '1.2.3.4/32', '8.8.0.0/12', '2001:0db8:0123:4567:89ab:cdef:1234:5678/128', '2001::1234:5678/128', null, null ] ], [ FieldType.GeoPoint, [[90, 60], ['90.123', '60.456'], { lat: '89.002', lon: '20.034990' }, null, undefined], undefined, [ { lat: 60, lon: 90 }, { lat: 60.456, lon: 90.123 }, { lat: 89.002, lon: 20.034990 }, null, null ], ], [ FieldType.Boundary, [[[90, 60], ['90.123', '60.456']], null, undefined], undefined, [ [{ lat: 60, lon: 90 }, { lat: 60.456, lon: 90.123 }], null, null ], ], [ FieldType.GeoJSON, [ { type: ESGeoShapeType.MultiPolygon, coordinates: [ [ [[10, 10], [10, 50], [50, 50], [50, 10], [10, 10]], ], [ [[-10, -10], [-10, -50], [-50, -50], [-50, -10], [-10, -10]], ] ] } as ESGeoShapeMultiPolygon, { type: ESGeoShapeType.Polygon, coordinates: [ [[10, 10], [10, 50], [50, 50], [50, 10], [10, 10]], ] } as ESGeoShapePolygon, { type: ESGeoShapeType.Point, coordinates: [12, 12] } as ESGeoShapePoint, null, undefined ], undefined, [ { type: GeoShapeType.MultiPolygon, coordinates: [ [ [[10, 10], [10, 50], [50, 50], [50, 10], [10, 10]], ], [ [[-10, -10], [-10, -50], [-50, -50], [-50, -10], [-10, -10]], ] ] } as GeoShapeMultiPolygon, { type: GeoShapeType.Polygon, coordinates: [ [[10, 10], [10, 50], [50, 50], [50, 10], [10, 10]], ] } as GeoShapePolygon, { type: GeoShapeType.Point, coordinates: [12, 12] } as GeoShapePoint, null, null ], ], [ FieldType.Object, [ { foo: 'bar', other: { 1: 2 }, arr: [1, 2, 3] }, { field1: null, field2: undefined }, {}, null, undefined ], undefined, [ { foo: 'bar', other: { 1: 2 }, arr: [1, 2, 3] }, { field1: null, field2: undefined }, {}, null, null ], [ [], 'foo', ], ], [ FieldType.Tuple, [ [true, 'hi', 3], ['FALSE', 2, 1.1], [null, undefined, null], [null, 'hello', undefined], [], null, undefined ], { 0: { type: FieldType.Boolean }, 1: { type: FieldType.String }, 2: { type: FieldType.Integer }, }, [ [true, 'hi', 3], [false, '2', 1], [undefined, undefined, undefined], [undefined, 'hello', undefined], [undefined, undefined, undefined], undefined, undefined ], [ [true, 'hi', 'hello', 'extra-arg'], ['not a boolean'], 'foo', { hi: true }, 0 ], ], ]; describe.each(testCases)('when field type is %s', (type, input, childConfig, output, invalid) => { let vector: Vector<any>; let expected: any[]; beforeAll(() => { const builder = Builder.make(new WritableData(input.length), { childConfig, config: { type, array: false }, }); input.forEach((val) => builder.append(val)); vector = builder.toVector(); expected = (output ?? input).map((val) => { if (typeof val === 'bigint') { return bigIntToJSON(val); } if (val == null) return undefined; return val; }); }); it('should return the correct output', () => { expect(vector.toJSON()).toEqual(expected); }); it('should return have the correct size', () => { expect(vector.size).toBe(expected.length); }); it('should have the correct distinct values', () => { const unique = new Set( expected.filter(isNotNil).map(toString) ); expect(vector.countUnique()).toBe(unique.size); }); it('should have the correct field config', () => { expect(vector.config).toEqual({ type, array: false }); }); it('should be able to detect when there are non-nil values', () => { expect(vector.hasNilValues()).toEqual(expected.some((value) => value == null)); }); it('should be able to detect count the non-nil values', () => { expect(vector.countValues()).toEqual(expected.reduce((acc, value) => { if (value == null) return acc; return acc + 1; }, 0)); }); it('should be able to detect if the vector is empty', () => { expect(vector.isEmpty()).toBeFalse(); }); describe('when appended to itself', () => { let appended: Vector<any>; let newData: ReadableData<any>; beforeAll(() => { newData = new ReadableData(vector.data[0].toWritable()); appended = vector.append(newData); }); it('should be have doubled in size', () => { expect(appended.size).toEqual(expected.length * 2); }); it('should be able to find the first half of the data', () => { const found = appended.findDataWithIndex(1); if (found == null) { expect(found).not.toBeNil(); return; } // this can't use toBe because jest throw cannot serialize bigint errors expect(found[0] === vector.data[0]).toBeTrue(); expect(found[1]).toBe(1); }); it('should be able to find the second half of the data', () => { const found = appended.findDataWithIndex(vector.size); if (found == null) { expect(found).not.toBeNil(); return; } // this can't use toBe because jest throw cannot serialize bigint errors expect(found[0] === newData).toBeTrue(); expect(found[1]).toBe(0); }); it('should be able return double the output', () => { expect(appended.toJSON()).toEqual( expected.concat(expected) ); }); it('should be able to slice the results to 1', () => { expect(appended.slice(0, 1).size).toBe(1); }); it('should be able to slice the results to the last item', () => { expect(appended.slice(-1).size).toBe(1); }); it('should be able to slice the first half', () => { expect(appended.slice(vector.size).size).toBe(vector.size); }); it('should be able to slice the second half', () => { expect(appended.slice(0, vector.size).size).toBe(vector.size); }); describe('when appended to itself again', () => { let appended2: Vector<any>; let newData2: ReadableData<any>; beforeAll(() => { newData2 = new ReadableData(appended.data[1].toWritable()); appended2 = appended.append(newData2); }); it('should be have tripled in size', () => { expect(appended2.size).toEqual(expected.length * 3); }); it('should be able to find the first half of the data', () => { const found = appended2.findDataWithIndex(1); if (found == null) { expect(found).not.toBeNil(); return; } // this can't use toBe because jest throw cannot serialize bigint errors expect(found[0] === vector.data[0]).toBeTrue(); expect(found[1]).toBe(1); }); it('should be able to find the second half of the data', () => { const found = appended2.findDataWithIndex(vector.size); if (found == null) { expect(found).not.toBeNil(); return; } // this can't use toBe because jest throw cannot serialize bigint errors expect(found[0] === newData).toBeTrue(); expect(found[1]).toBe(0); }); it('should be able to find the third half of the data', () => { const found = appended2.findDataWithIndex(appended.size); if (found == null) { expect(found).not.toBeNil(); return; } // this can't use toBe because jest throw cannot serialize bigint errors expect(found[0] === newData2).toBeTrue(); expect(found[1]).toBe(0); }); it('should be able return triple the output', () => { expect(appended2.toJSON()).toEqual( expected.concat(expected, expected) ); }); it('should be able to slice the results to 1', () => { expect(appended2.slice(0, 1).size).toBe(1); }); it('should be able to slice the results to the last item', () => { expect(appended2.slice(-1).size).toBe(1); }); it('should be able to slice the first part', () => { expect(appended2.slice(appended.size).size).toBe(vector.size); }); it('should be able to slice the second part', () => { expect(appended2.slice(0, appended.size).size).toBe(appended.size); }); it('should be able to slice the third part', () => { expect(appended2.slice(appended.size, appended2.size).size).toBe(vector.size); }); }); }); if (invalid?.length) { test.each(invalid)('should NOT be able to parse %p', (val) => { const builder = Builder.make(new WritableData(invalid.length), { config: { type, array: false }, childConfig }); expect(() => { builder.append(val); }).toThrowError(); }); } it('should be an instance of a Vector', () => { expect(vector).toBeInstanceOf(Vector); }); it('should be immutable', () => { expect(() => { // @ts-expect-error vector.data[0].values = '10'; }).toThrow(); }); }); it('should be able to return 2 data buckets (with a an start index of 0) when slicing', () => { const writable1 = new WritableData(1); writable1.set(0, 'hi'); const writable2 = new WritableData(1); writable2.set(0, 'hello'); const vector = Vector.make([ new ReadableData(writable1), new ReadableData(writable2) ], { config: { type: FieldType.String, }, name: 'test' }); expect(vector.slice().toJSON()).toEqual([ 'hi', 'hello' ]); }); it('should be able to return 2 data buckets (with a an start index of 1) when slicing', () => { const writable1 = new WritableData(1); writable1.set(0, 'hi'); const writable2 = new WritableData(2); writable2.set(0, 'hello'); writable2.set(1, 'howdy'); const writable3 = new WritableData(1); writable3.set(0, 'hey'); const vector = Vector.make([ new ReadableData(writable1), new ReadableData(writable2), new ReadableData(writable3) ], { config: { type: FieldType.String, }, name: 'test' }); expect(vector.slice(1).toJSON()).toEqual([ 'hello', 'howdy', 'hey' ]); }); });
the_stack