text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * Capacities * __NOTE__: An instance of this class is automatically created for an * instance of the PowerBIDedicatedManagementClient. */ export interface Capacities { /** * Gets details about the specified dedicated capacity. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the dedicated capacity. It * must be a minimum of 3 characters, and a maximum of 63. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DedicatedCapacity>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getDetailsWithHttpOperationResponse(resourceGroupName: string, dedicatedCapacityName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DedicatedCapacity>>; /** * Gets details about the specified dedicated capacity. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the dedicated capacity. It * must be a minimum of 3 characters, and a maximum of 63. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DedicatedCapacity} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DedicatedCapacity} [result] - The deserialized result object if an error did not occur. * See {@link DedicatedCapacity} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getDetails(resourceGroupName: string, dedicatedCapacityName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DedicatedCapacity>; getDetails(resourceGroupName: string, dedicatedCapacityName: string, callback: ServiceCallback<models.DedicatedCapacity>): void; getDetails(resourceGroupName: string, dedicatedCapacityName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DedicatedCapacity>): void; /** * Provisions the specified Dedicated capacity based on the configuration * specified in the request. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be a minimum of 3 characters, and a maximum of 63. * * @param {object} capacityParameters Contains the information used to * provision the Dedicated capacity. * * @param {object} [capacityParameters.administration] A collection of * Dedicated capacity administrators * * @param {array} [capacityParameters.administration.members] An array of * administrator user identities. * * @param {string} capacityParameters.location Location of the PowerBI * Dedicated resource. * * @param {object} capacityParameters.sku The SKU of the PowerBI Dedicated * resource. * * @param {string} capacityParameters.sku.name Name of the SKU level. * * @param {string} [capacityParameters.sku.tier] The name of the Azure pricing * tier to which the SKU applies. Possible values include: 'PBIE_Azure' * * @param {object} [capacityParameters.tags] Key-value pairs of additional * resource provisioning properties. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DedicatedCapacity>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(resourceGroupName: string, dedicatedCapacityName: string, capacityParameters: models.DedicatedCapacity, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DedicatedCapacity>>; /** * Provisions the specified Dedicated capacity based on the configuration * specified in the request. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be a minimum of 3 characters, and a maximum of 63. * * @param {object} capacityParameters Contains the information used to * provision the Dedicated capacity. * * @param {object} [capacityParameters.administration] A collection of * Dedicated capacity administrators * * @param {array} [capacityParameters.administration.members] An array of * administrator user identities. * * @param {string} capacityParameters.location Location of the PowerBI * Dedicated resource. * * @param {object} capacityParameters.sku The SKU of the PowerBI Dedicated * resource. * * @param {string} capacityParameters.sku.name Name of the SKU level. * * @param {string} [capacityParameters.sku.tier] The name of the Azure pricing * tier to which the SKU applies. Possible values include: 'PBIE_Azure' * * @param {object} [capacityParameters.tags] Key-value pairs of additional * resource provisioning properties. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DedicatedCapacity} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DedicatedCapacity} [result] - The deserialized result object if an error did not occur. * See {@link DedicatedCapacity} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ create(resourceGroupName: string, dedicatedCapacityName: string, capacityParameters: models.DedicatedCapacity, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DedicatedCapacity>; create(resourceGroupName: string, dedicatedCapacityName: string, capacityParameters: models.DedicatedCapacity, callback: ServiceCallback<models.DedicatedCapacity>): void; create(resourceGroupName: string, dedicatedCapacityName: string, capacityParameters: models.DedicatedCapacity, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DedicatedCapacity>): void; /** * Deletes the specified Dedicated capacity. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be at least 3 characters in length, and no more than 63. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroupName: string, dedicatedCapacityName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the specified Dedicated capacity. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be at least 3 characters in length, and no more than 63. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroupName: string, dedicatedCapacityName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroupName: string, dedicatedCapacityName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroupName: string, dedicatedCapacityName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Updates the current state of the specified Dedicated capacity. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be at least 3 characters in length, and no more than 63. * * @param {object} capacityUpdateParameters Request object that contains the * updated information for the capacity. * * @param {object} [capacityUpdateParameters.sku] The SKU of the Dedicated * capacity resource. * * @param {string} capacityUpdateParameters.sku.name Name of the SKU level. * * @param {string} [capacityUpdateParameters.sku.tier] The name of the Azure * pricing tier to which the SKU applies. Possible values include: 'PBIE_Azure' * * @param {object} [capacityUpdateParameters.tags] Key-value pairs of * additional provisioning properties. * * @param {object} [capacityUpdateParameters.administration] A collection of * Dedicated capacity administrators * * @param {array} [capacityUpdateParameters.administration.members] An array of * administrator user identities. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DedicatedCapacity>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ updateWithHttpOperationResponse(resourceGroupName: string, dedicatedCapacityName: string, capacityUpdateParameters: models.DedicatedCapacityUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DedicatedCapacity>>; /** * Updates the current state of the specified Dedicated capacity. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be at least 3 characters in length, and no more than 63. * * @param {object} capacityUpdateParameters Request object that contains the * updated information for the capacity. * * @param {object} [capacityUpdateParameters.sku] The SKU of the Dedicated * capacity resource. * * @param {string} capacityUpdateParameters.sku.name Name of the SKU level. * * @param {string} [capacityUpdateParameters.sku.tier] The name of the Azure * pricing tier to which the SKU applies. Possible values include: 'PBIE_Azure' * * @param {object} [capacityUpdateParameters.tags] Key-value pairs of * additional provisioning properties. * * @param {object} [capacityUpdateParameters.administration] A collection of * Dedicated capacity administrators * * @param {array} [capacityUpdateParameters.administration.members] An array of * administrator user identities. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DedicatedCapacity} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DedicatedCapacity} [result] - The deserialized result object if an error did not occur. * See {@link DedicatedCapacity} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ update(resourceGroupName: string, dedicatedCapacityName: string, capacityUpdateParameters: models.DedicatedCapacityUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DedicatedCapacity>; update(resourceGroupName: string, dedicatedCapacityName: string, capacityUpdateParameters: models.DedicatedCapacityUpdateParameters, callback: ServiceCallback<models.DedicatedCapacity>): void; update(resourceGroupName: string, dedicatedCapacityName: string, capacityUpdateParameters: models.DedicatedCapacityUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DedicatedCapacity>): void; /** * Suspends operation of the specified dedicated capacity instance. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be at least 3 characters in length, and no more than 63. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ suspendWithHttpOperationResponse(resourceGroupName: string, dedicatedCapacityName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Suspends operation of the specified dedicated capacity instance. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be at least 3 characters in length, and no more than 63. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ suspend(resourceGroupName: string, dedicatedCapacityName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; suspend(resourceGroupName: string, dedicatedCapacityName: string, callback: ServiceCallback<void>): void; suspend(resourceGroupName: string, dedicatedCapacityName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Resumes operation of the specified Dedicated capacity instance. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be at least 3 characters in length, and no more than 63. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ resumeWithHttpOperationResponse(resourceGroupName: string, dedicatedCapacityName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Resumes operation of the specified Dedicated capacity instance. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be at least 3 characters in length, and no more than 63. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ resume(resourceGroupName: string, dedicatedCapacityName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; resume(resourceGroupName: string, dedicatedCapacityName: string, callback: ServiceCallback<void>): void; resume(resourceGroupName: string, dedicatedCapacityName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets all the Dedicated capacities for the given resource group. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DedicatedCapacities>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DedicatedCapacities>>; /** * Gets all the Dedicated capacities for the given resource group. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DedicatedCapacities} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DedicatedCapacities} [result] - The deserialized result object if an error did not occur. * See {@link DedicatedCapacities} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroup(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DedicatedCapacities>; listByResourceGroup(resourceGroupName: string, callback: ServiceCallback<models.DedicatedCapacities>): void; listByResourceGroup(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DedicatedCapacities>): void; /** * Lists all the Dedicated capacities for the given subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DedicatedCapacities>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DedicatedCapacities>>; /** * Lists all the Dedicated capacities for the given subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DedicatedCapacities} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DedicatedCapacities} [result] - The deserialized result object if an error did not occur. * See {@link DedicatedCapacities} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DedicatedCapacities>; list(callback: ServiceCallback<models.DedicatedCapacities>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DedicatedCapacities>): void; /** * Lists eligible SKUs for PowerBI Dedicated resource provider. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SkuEnumerationForNewResourceResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listSkusWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SkuEnumerationForNewResourceResult>>; /** * Lists eligible SKUs for PowerBI Dedicated resource provider. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SkuEnumerationForNewResourceResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SkuEnumerationForNewResourceResult} [result] - The deserialized result object if an error did not occur. * See {@link SkuEnumerationForNewResourceResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listSkus(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SkuEnumerationForNewResourceResult>; listSkus(callback: ServiceCallback<models.SkuEnumerationForNewResourceResult>): void; listSkus(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SkuEnumerationForNewResourceResult>): void; /** * Lists eligible SKUs for a PowerBI Dedicated resource. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be at least 3 characters in length, and no more than 63. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<SkuEnumerationForExistingResourceResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listSkusForCapacityWithHttpOperationResponse(resourceGroupName: string, dedicatedCapacityName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.SkuEnumerationForExistingResourceResult>>; /** * Lists eligible SKUs for a PowerBI Dedicated resource. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be at least 3 characters in length, and no more than 63. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {SkuEnumerationForExistingResourceResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {SkuEnumerationForExistingResourceResult} [result] - The deserialized result object if an error did not occur. * See {@link SkuEnumerationForExistingResourceResult} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listSkusForCapacity(resourceGroupName: string, dedicatedCapacityName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.SkuEnumerationForExistingResourceResult>; listSkusForCapacity(resourceGroupName: string, dedicatedCapacityName: string, callback: ServiceCallback<models.SkuEnumerationForExistingResourceResult>): void; listSkusForCapacity(resourceGroupName: string, dedicatedCapacityName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.SkuEnumerationForExistingResourceResult>): void; /** * Provisions the specified Dedicated capacity based on the configuration * specified in the request. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be a minimum of 3 characters, and a maximum of 63. * * @param {object} capacityParameters Contains the information used to * provision the Dedicated capacity. * * @param {object} [capacityParameters.administration] A collection of * Dedicated capacity administrators * * @param {array} [capacityParameters.administration.members] An array of * administrator user identities. * * @param {string} capacityParameters.location Location of the PowerBI * Dedicated resource. * * @param {object} capacityParameters.sku The SKU of the PowerBI Dedicated * resource. * * @param {string} capacityParameters.sku.name Name of the SKU level. * * @param {string} [capacityParameters.sku.tier] The name of the Azure pricing * tier to which the SKU applies. Possible values include: 'PBIE_Azure' * * @param {object} [capacityParameters.tags] Key-value pairs of additional * resource provisioning properties. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DedicatedCapacity>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginCreateWithHttpOperationResponse(resourceGroupName: string, dedicatedCapacityName: string, capacityParameters: models.DedicatedCapacity, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DedicatedCapacity>>; /** * Provisions the specified Dedicated capacity based on the configuration * specified in the request. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be a minimum of 3 characters, and a maximum of 63. * * @param {object} capacityParameters Contains the information used to * provision the Dedicated capacity. * * @param {object} [capacityParameters.administration] A collection of * Dedicated capacity administrators * * @param {array} [capacityParameters.administration.members] An array of * administrator user identities. * * @param {string} capacityParameters.location Location of the PowerBI * Dedicated resource. * * @param {object} capacityParameters.sku The SKU of the PowerBI Dedicated * resource. * * @param {string} capacityParameters.sku.name Name of the SKU level. * * @param {string} [capacityParameters.sku.tier] The name of the Azure pricing * tier to which the SKU applies. Possible values include: 'PBIE_Azure' * * @param {object} [capacityParameters.tags] Key-value pairs of additional * resource provisioning properties. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DedicatedCapacity} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DedicatedCapacity} [result] - The deserialized result object if an error did not occur. * See {@link DedicatedCapacity} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginCreate(resourceGroupName: string, dedicatedCapacityName: string, capacityParameters: models.DedicatedCapacity, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DedicatedCapacity>; beginCreate(resourceGroupName: string, dedicatedCapacityName: string, capacityParameters: models.DedicatedCapacity, callback: ServiceCallback<models.DedicatedCapacity>): void; beginCreate(resourceGroupName: string, dedicatedCapacityName: string, capacityParameters: models.DedicatedCapacity, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DedicatedCapacity>): void; /** * Deletes the specified Dedicated capacity. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be at least 3 characters in length, and no more than 63. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginDeleteMethodWithHttpOperationResponse(resourceGroupName: string, dedicatedCapacityName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes the specified Dedicated capacity. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be at least 3 characters in length, and no more than 63. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginDeleteMethod(resourceGroupName: string, dedicatedCapacityName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginDeleteMethod(resourceGroupName: string, dedicatedCapacityName: string, callback: ServiceCallback<void>): void; beginDeleteMethod(resourceGroupName: string, dedicatedCapacityName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Updates the current state of the specified Dedicated capacity. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be at least 3 characters in length, and no more than 63. * * @param {object} capacityUpdateParameters Request object that contains the * updated information for the capacity. * * @param {object} [capacityUpdateParameters.sku] The SKU of the Dedicated * capacity resource. * * @param {string} capacityUpdateParameters.sku.name Name of the SKU level. * * @param {string} [capacityUpdateParameters.sku.tier] The name of the Azure * pricing tier to which the SKU applies. Possible values include: 'PBIE_Azure' * * @param {object} [capacityUpdateParameters.tags] Key-value pairs of * additional provisioning properties. * * @param {object} [capacityUpdateParameters.administration] A collection of * Dedicated capacity administrators * * @param {array} [capacityUpdateParameters.administration.members] An array of * administrator user identities. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<DedicatedCapacity>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginUpdateWithHttpOperationResponse(resourceGroupName: string, dedicatedCapacityName: string, capacityUpdateParameters: models.DedicatedCapacityUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.DedicatedCapacity>>; /** * Updates the current state of the specified Dedicated capacity. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be at least 3 characters in length, and no more than 63. * * @param {object} capacityUpdateParameters Request object that contains the * updated information for the capacity. * * @param {object} [capacityUpdateParameters.sku] The SKU of the Dedicated * capacity resource. * * @param {string} capacityUpdateParameters.sku.name Name of the SKU level. * * @param {string} [capacityUpdateParameters.sku.tier] The name of the Azure * pricing tier to which the SKU applies. Possible values include: 'PBIE_Azure' * * @param {object} [capacityUpdateParameters.tags] Key-value pairs of * additional provisioning properties. * * @param {object} [capacityUpdateParameters.administration] A collection of * Dedicated capacity administrators * * @param {array} [capacityUpdateParameters.administration.members] An array of * administrator user identities. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {DedicatedCapacity} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {DedicatedCapacity} [result] - The deserialized result object if an error did not occur. * See {@link DedicatedCapacity} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginUpdate(resourceGroupName: string, dedicatedCapacityName: string, capacityUpdateParameters: models.DedicatedCapacityUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.DedicatedCapacity>; beginUpdate(resourceGroupName: string, dedicatedCapacityName: string, capacityUpdateParameters: models.DedicatedCapacityUpdateParameters, callback: ServiceCallback<models.DedicatedCapacity>): void; beginUpdate(resourceGroupName: string, dedicatedCapacityName: string, capacityUpdateParameters: models.DedicatedCapacityUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.DedicatedCapacity>): void; /** * Suspends operation of the specified dedicated capacity instance. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be at least 3 characters in length, and no more than 63. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginSuspendWithHttpOperationResponse(resourceGroupName: string, dedicatedCapacityName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Suspends operation of the specified dedicated capacity instance. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be at least 3 characters in length, and no more than 63. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginSuspend(resourceGroupName: string, dedicatedCapacityName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginSuspend(resourceGroupName: string, dedicatedCapacityName: string, callback: ServiceCallback<void>): void; beginSuspend(resourceGroupName: string, dedicatedCapacityName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Resumes operation of the specified Dedicated capacity instance. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be at least 3 characters in length, and no more than 63. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ beginResumeWithHttpOperationResponse(resourceGroupName: string, dedicatedCapacityName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Resumes operation of the specified Dedicated capacity instance. * * @param {string} resourceGroupName The name of the Azure Resource group of * which a given PowerBIDedicated capacity is part. This name must be at least * 1 character in length, and no more than 90. * * @param {string} dedicatedCapacityName The name of the Dedicated capacity. It * must be at least 3 characters in length, and no more than 63. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ beginResume(resourceGroupName: string, dedicatedCapacityName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; beginResume(resourceGroupName: string, dedicatedCapacityName: string, callback: ServiceCallback<void>): void; beginResume(resourceGroupName: string, dedicatedCapacityName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; } /** * @class * Operations * __NOTE__: An instance of this class is automatically created for an * instance of the PowerBIDedicatedManagementClient. */ export interface Operations { /** * Lists all of the available PowerBIDedicated REST API operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * Lists all of the available PowerBIDedicated REST API operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; list(callback: ServiceCallback<models.OperationListResult>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; /** * Lists all of the available PowerBIDedicated REST API operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * Lists all of the available PowerBIDedicated REST API operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.OperationListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; }
the_stack
import mockFs from 'mock-fs'; import { PackageJson } from 'type-fest'; import { checkInvariantsAndGetConfiguration } from '../configureRollpkg'; interface PkgJson extends PackageJson { umdGlobalDependencies?: { [key: string]: string }; } interface CreateTestPackageJson { (): PkgJson; } // create a new package.json object each time so it can be mutated to meet the test's needs const createTestPackageJson: CreateTestPackageJson = () => ({ name: 'test-package-name', main: 'dist/test-package-name.cjs.js', module: 'dist/test-package-name.esm.js', types: 'dist/index.d.ts', sideEffects: false, dependencies: { 'some-dependency': '^1.0.0', }, peerDependencies: { 'some-peer-dependency': '^1.0.0', }, }); afterEach(() => { mockFs.restore(); }); // mockFs note: use absolute path "/" in mockFs so that snapshots of error messages // that contain the path (as a helpful hint to the user) don't change based on where // the rollpkg directory is located, e.g. if the test snapshot contains /Users/rafael/dev/rollpkg // the tests will only pass when rollpkg is located in the /Users/rafael/dev directory describe('fails with incorrect configuration', () => { test('fails without a "build" or "watch" command', async () => { mockFs({ '/package.json': JSON.stringify(createTestPackageJson()), '/tsconfig.json': '', '/src/index.ts': '', }); await expect( checkInvariantsAndGetConfiguration({ args: [], cwd: '/', }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"rollpkg requires a \\"build\\" or \\"watch\\" command, received: \\"\\""`, ); }); test('fails with "watch" command and "--addUmdBuild" options', async () => { mockFs({ '/package.json': JSON.stringify(createTestPackageJson()), '/tsconfig.json': '', '/src/index.ts': '', }); await expect( checkInvariantsAndGetConfiguration({ args: ['watch', '--addUmdBuild'], cwd: '/', }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"--addUmdBuild option is not valid in watch mode (only the esm build is created in watch mode)"`, ); }); test('fails with "watch" command and "--noStats" options', async () => { mockFs({ '/package.json': JSON.stringify(createTestPackageJson()), '/tsconfig.json': '', '/src/index.ts': '', }); await expect( checkInvariantsAndGetConfiguration({ args: ['watch', '--noStats'], cwd: '/', }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"--noStats option is not valid in watch mode (stats are never calculated in watch mode)"`, ); }); test('fails without a package.json file', async () => { mockFs({ '/tsconfig.json': '', '/src/index.ts': '', }); await expect( checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Cannot read package.json at /package.json"`, ); }); test('fails when "name" field not present', async () => { const packageJson = createTestPackageJson(); delete packageJson.name; mockFs({ '/package.json': JSON.stringify(packageJson), '/tsconfig.json': '', '/src/index.ts': '', }); await expect( checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"\\"name\\" field is required in package.json and needs to be a string, value found: undefined"`, ); }); test('fails when "name" is not a valid npm package name', async () => { const packageJson = createTestPackageJson(); packageJson.name = '!some/name'; mockFs({ '/package.json': JSON.stringify(packageJson), '/tsconfig.json': '', '/src/index.ts': '', }); await expect( checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }), ).rejects.toThrowErrorMatchingInlineSnapshot(` "Invalid npm package name, see https://www.npmjs.com/package/validate-npm-package-name Npm Error: name can only contain URL-friendly characters" `); }); test('fails when "main" field not present', async () => { const packageJson = createTestPackageJson(); delete packageJson.main; mockFs({ '/package.json': JSON.stringify(packageJson), '/tsconfig.json': '', '/src/index.ts': '', }); await expect( checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"The value of \\"main\\" in package.json needs to be \\"dist/test-package-name.cjs.js\\", value found: \\"undefined\\""`, ); }); test('fails when "main" does not match convention', async () => { const packageJson = createTestPackageJson(); packageJson.main = 'some-main.js'; mockFs({ '/package.json': JSON.stringify(packageJson), '/tsconfig.json': '', '/src/index.ts': '', }); await expect( checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"The value of \\"main\\" in package.json needs to be \\"dist/test-package-name.cjs.js\\", value found: \\"some-main.js\\""`, ); }); test('fails when "module" field not present', async () => { const packageJson = createTestPackageJson(); delete packageJson.module; mockFs({ '/package.json': JSON.stringify(packageJson), '/tsconfig.json': '', '/src/index.ts': '', }); await expect( checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"The value of \\"module\\" in package.json needs to be \\"dist/test-package-name.esm.js\\", value found: \\"undefined\\""`, ); }); test('fails when "module" does not match convention', async () => { const packageJson = createTestPackageJson(); packageJson.module = 'some-module.js'; mockFs({ '/package.json': JSON.stringify(packageJson), '/tsconfig.json': '', '/src/index.ts': '', }); await expect( checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"The value of \\"module\\" in package.json needs to be \\"dist/test-package-name.esm.js\\", value found: \\"some-module.js\\""`, ); }); test('fails when "types" does not match convention', async () => { const packageJson = createTestPackageJson(); packageJson.types = 'some-types.d.ts'; mockFs({ '/package.json': JSON.stringify(packageJson), '/tsconfig.json': '', '/src/index.ts': '', }); await expect( checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"The value of \\"types\\" in package.json needs to be \\"dist/index.d.ts\\", value found: \\"some-types.d.ts\\""`, ); }); test('fails when "sideEffects" field is not present', async () => { const packageJson = createTestPackageJson(); delete packageJson.sideEffects; mockFs({ '/package.json': JSON.stringify(packageJson), '/tsconfig.json': '', '/src/index.ts': '', }); await expect( checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"\\"sideEffects\\" field is required in package.json and needs to be a boolean, value found: undefined"`, ); }); test('fails when "sideEffects" is not a boolean', async () => { const packageJson = createTestPackageJson(); packageJson.sideEffects = ['/src/someFileWithSideEffects.ts']; mockFs({ '/package.json': JSON.stringify(packageJson), '/tsconfig.json': '', '/src/index.ts': '', }); await expect( checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"\\"sideEffects\\" field is required in package.json and needs to be a boolean, value found: /src/someFileWithSideEffects.ts"`, ); }); test('fails when "umdGlobalDependencies" is present but not an object of strings', async () => { const packageJson = createTestPackageJson(); // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore because intentionally violating types to test that it throws packageJson.umdGlobalDependencies = { 'some-global-dep': true }; mockFs({ '/package.json': JSON.stringify(packageJson), '/tsconfig.json': '', '/src/index.ts': '', }); await expect( checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"If \\"umdGlobalDependencies\\" is specified in package.json, it needs to be an object of the form { \\"package-name\\": \\"GlobalName\\" }, for example { \\"react-dom\\": \\"ReactDOM\\" }"`, ); }); test('fails without a src/index.ts or src/index.tsx file', async () => { mockFs({ '/package.json': JSON.stringify(createTestPackageJson()), '/tsconfig.json': '', }); await expect( checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Cannot find index.ts or index.tsx entry file in /src"`, ); }); test('fails when both src/index.ts and src/index.tsx files exist', async () => { mockFs({ '/package.json': JSON.stringify(createTestPackageJson()), '/src/index.ts': '', '/src/index.tsx': '', '/tsconfig.json': '', }); await expect( checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }), ).rejects.toThrowErrorMatchingInlineSnapshot( `"Cannot have both index.ts and index.tsx files in /src"`, ); }); }); describe('correctly configures rollpkg', () => { test('rollpkg build', async () => { mockFs({ '/package.json': JSON.stringify(createTestPackageJson()), '/tsconfig.json': '', '/src/index.ts': '', }); const { watchMode } = await checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }); expect(watchMode).toBe(false); }); test('rollpkg watch', async () => { mockFs({ '/package.json': JSON.stringify(createTestPackageJson()), '/tsconfig.json': '', '/src/index.ts': '', }); const { watchMode } = await checkInvariantsAndGetConfiguration({ args: ['watch'], cwd: '/', }); expect(watchMode).toBe(true); }); test('scoped package name', async () => { const packageJson = createTestPackageJson(); packageJson.name = '@scope/package-name'; packageJson.main = 'dist/scope-package-name.cjs.js'; packageJson.module = 'dist/scope-package-name.esm.js'; mockFs({ '/package.json': JSON.stringify(packageJson), '/tsconfig.json': '', '/src/index.ts': '', }); const { pkgJsonName, kebabCasePkgName, } = await checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }); expect(pkgJsonName).toBe('@scope/package-name'); expect(kebabCasePkgName).toBe('scope-package-name'); }); test('with index.ts entry file', async () => { mockFs({ '/package.json': JSON.stringify(createTestPackageJson()), '/tsconfig.json': '', '/src/index.ts': '', }); const { entryFile } = await checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }); expect(entryFile).toBe('/src/index.ts'); }); test('with index.tsx entry file', async () => { mockFs({ '/package.json': JSON.stringify(createTestPackageJson()), '/tsconfig.json': '', '/src/index.tsx': '', }); const { entryFile } = await checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }); expect(entryFile).toBe('/src/index.tsx'); }); test('with no "dependencies" and no "peerDependencies"', async () => { const packageJson = createTestPackageJson(); delete packageJson.dependencies; delete packageJson.peerDependencies; mockFs({ '/package.json': JSON.stringify(packageJson), '/tsconfig.json': '', '/src/index.ts': '', }); const { pkgJsonDependencyKeys, pkgJsonPeerDependencyKeys, } = await checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }); expect(pkgJsonDependencyKeys).toEqual([]); expect(pkgJsonPeerDependencyKeys).toEqual([]); }); test('with "umdGlobalDependencies"', async () => { const packageJson = createTestPackageJson(); packageJson.umdGlobalDependencies = { 'react-dom': 'ReactDOM' }; mockFs({ '/package.json': JSON.stringify(packageJson), '/tsconfig.json': '', '/src/index.ts': '', }); const { pkgJsonUmdGlobalDependencies, } = await checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }); expect(pkgJsonUmdGlobalDependencies).toEqual({ 'react-dom': 'ReactDOM' }); }); test('full config snapshot', async () => { mockFs({ '/package.json': JSON.stringify(createTestPackageJson()), '/tsconfig.json': '', '/src/index.ts': '', }); await expect( checkInvariantsAndGetConfiguration({ args: ['build'], cwd: '/', }), ).resolves.toMatchInlineSnapshot(` Object { "addUmdBuild": false, "entryFile": "/src/index.ts", "includeBundlephobiaStats": true, "kebabCasePkgName": "test-package-name", "pkgJsonDependencyKeys": Array [ "some-dependency", ], "pkgJsonName": "test-package-name", "pkgJsonPeerDependencyKeys": Array [ "some-peer-dependency", ], "pkgJsonSideEffects": false, "pkgJsonUmdGlobalDependencies": undefined, "tsconfigPath": undefined, "watchMode": false, } `); }); });
the_stack
'use strict'; // Names from https://blog.codinghorror.com/ascii-pronunciation-rules-for-programmers/ /** * An inlined enum containing useful character codes (to be used with String.charCodeAt). * Please leave the const keyword such that it gets inlined when compiled to JavaScript! */ export const enum CharCode { Null = 0, /** * The `\t` character. */ Tab = 9, /** * The `\n` character. */ LineFeed = 10, /** * The `\r` character. */ CarriageReturn = 13, Space = 32, /** * The `!` character. */ ExclamationMark = 33, /** * The `"` character. */ DoubleQuote = 34, /** * The `#` character. */ Hash = 35, /** * The `$` character. */ DollarSign = 36, /** * The `%` character. */ PercentSign = 37, /** * The `&` character. */ Ampersand = 38, /** * The `'` character. */ SingleQuote = 39, /** * The `(` character. */ OpenParen = 40, /** * The `)` character. */ CloseParen = 41, /** * The `*` character. */ Asterisk = 42, /** * The `+` character. */ Plus = 43, /** * The `,` character. */ Comma = 44, /** * The `-` character. */ Dash = 45, /** * The `.` character. */ Period = 46, /** * The `/` character. */ Slash = 47, Digit0 = 48, Digit1 = 49, Digit2 = 50, Digit3 = 51, Digit4 = 52, Digit5 = 53, Digit6 = 54, Digit7 = 55, Digit8 = 56, Digit9 = 57, /** * The `:` character. */ Colon = 58, /** * The `;` character. */ Semicolon = 59, /** * The `<` character. */ LessThan = 60, /** * The `=` character. */ Equals = 61, /** * The `>` character. */ GreaterThan = 62, /** * The `?` character. */ QuestionMark = 63, /** * The `@` character. */ AtSign = 64, A = 65, B = 66, C = 67, D = 68, E = 69, F = 70, G = 71, H = 72, I = 73, J = 74, K = 75, L = 76, M = 77, N = 78, O = 79, P = 80, Q = 81, R = 82, S = 83, T = 84, U = 85, V = 86, W = 87, X = 88, Y = 89, Z = 90, /** * The `[` character. */ OpenSquareBracket = 91, /** * The `\` character. */ Backslash = 92, /** * The `]` character. */ CloseSquareBracket = 93, /** * The `^` character. */ Caret = 94, /** * The `_` character. */ Underline = 95, /** * The ``(`)`` character. */ BackTick = 96, a = 97, b = 98, c = 99, d = 100, e = 101, f = 102, g = 103, h = 104, i = 105, j = 106, k = 107, l = 108, m = 109, n = 110, o = 111, p = 112, q = 113, r = 114, s = 115, t = 116, u = 117, v = 118, w = 119, x = 120, y = 121, z = 122, /** * The `{` character. */ OpenCurlyBrace = 123, /** * The `|` character. */ Pipe = 124, /** * The `}` character. */ CloseCurlyBrace = 125, /** * The `~` character. */ Tilde = 126, U_Combining_Grave_Accent = 0x0300, // U+0300 Combining Grave Accent U_Combining_Acute_Accent = 0x0301, // U+0301 Combining Acute Accent U_Combining_Circumflex_Accent = 0x0302, // U+0302 Combining Circumflex Accent U_Combining_Tilde = 0x0303, // U+0303 Combining Tilde U_Combining_Macron = 0x0304, // U+0304 Combining Macron U_Combining_Overline = 0x0305, // U+0305 Combining Overline U_Combining_Breve = 0x0306, // U+0306 Combining Breve U_Combining_Dot_Above = 0x0307, // U+0307 Combining Dot Above U_Combining_Diaeresis = 0x0308, // U+0308 Combining Diaeresis U_Combining_Hook_Above = 0x0309, // U+0309 Combining Hook Above U_Combining_Ring_Above = 0x030a, // U+030A Combining Ring Above U_Combining_Double_Acute_Accent = 0x030b, // U+030B Combining Double Acute Accent U_Combining_Caron = 0x030c, // U+030C Combining Caron U_Combining_Vertical_Line_Above = 0x030d, // U+030D Combining Vertical Line Above U_Combining_Double_Vertical_Line_Above = 0x030e, // U+030E Combining Double Vertical Line Above U_Combining_Double_Grave_Accent = 0x030f, // U+030F Combining Double Grave Accent U_Combining_Candrabindu = 0x0310, // U+0310 Combining Candrabindu U_Combining_Inverted_Breve = 0x0311, // U+0311 Combining Inverted Breve U_Combining_Turned_Comma_Above = 0x0312, // U+0312 Combining Turned Comma Above U_Combining_Comma_Above = 0x0313, // U+0313 Combining Comma Above U_Combining_Reversed_Comma_Above = 0x0314, // U+0314 Combining Reversed Comma Above U_Combining_Comma_Above_Right = 0x0315, // U+0315 Combining Comma Above Right U_Combining_Grave_Accent_Below = 0x0316, // U+0316 Combining Grave Accent Below U_Combining_Acute_Accent_Below = 0x0317, // U+0317 Combining Acute Accent Below U_Combining_Left_Tack_Below = 0x0318, // U+0318 Combining Left Tack Below U_Combining_Right_Tack_Below = 0x0319, // U+0319 Combining Right Tack Below U_Combining_Left_Angle_Above = 0x031a, // U+031A Combining Left Angle Above U_Combining_Horn = 0x031b, // U+031B Combining Horn U_Combining_Left_Half_Ring_Below = 0x031c, // U+031C Combining Left Half Ring Below U_Combining_Up_Tack_Below = 0x031d, // U+031D Combining Up Tack Below U_Combining_Down_Tack_Below = 0x031e, // U+031E Combining Down Tack Below U_Combining_Plus_Sign_Below = 0x031f, // U+031F Combining Plus Sign Below U_Combining_Minus_Sign_Below = 0x0320, // U+0320 Combining Minus Sign Below U_Combining_Palatalized_Hook_Below = 0x0321, // U+0321 Combining Palatalized Hook Below U_Combining_Retroflex_Hook_Below = 0x0322, // U+0322 Combining Retroflex Hook Below U_Combining_Dot_Below = 0x0323, // U+0323 Combining Dot Below U_Combining_Diaeresis_Below = 0x0324, // U+0324 Combining Diaeresis Below U_Combining_Ring_Below = 0x0325, // U+0325 Combining Ring Below U_Combining_Comma_Below = 0x0326, // U+0326 Combining Comma Below U_Combining_Cedilla = 0x0327, // U+0327 Combining Cedilla U_Combining_Ogonek = 0x0328, // U+0328 Combining Ogonek U_Combining_Vertical_Line_Below = 0x0329, // U+0329 Combining Vertical Line Below U_Combining_Bridge_Below = 0x032a, // U+032A Combining Bridge Below U_Combining_Inverted_Double_Arch_Below = 0x032b, // U+032B Combining Inverted Double Arch Below U_Combining_Caron_Below = 0x032c, // U+032C Combining Caron Below U_Combining_Circumflex_Accent_Below = 0x032d, // U+032D Combining Circumflex Accent Below U_Combining_Breve_Below = 0x032e, // U+032E Combining Breve Below U_Combining_Inverted_Breve_Below = 0x032f, // U+032F Combining Inverted Breve Below U_Combining_Tilde_Below = 0x0330, // U+0330 Combining Tilde Below U_Combining_Macron_Below = 0x0331, // U+0331 Combining Macron Below U_Combining_Low_Line = 0x0332, // U+0332 Combining Low Line U_Combining_Double_Low_Line = 0x0333, // U+0333 Combining Double Low Line U_Combining_Tilde_Overlay = 0x0334, // U+0334 Combining Tilde Overlay U_Combining_Short_Stroke_Overlay = 0x0335, // U+0335 Combining Short Stroke Overlay U_Combining_Long_Stroke_Overlay = 0x0336, // U+0336 Combining Long Stroke Overlay U_Combining_Short_Solidus_Overlay = 0x0337, // U+0337 Combining Short Solidus Overlay U_Combining_Long_Solidus_Overlay = 0x0338, // U+0338 Combining Long Solidus Overlay U_Combining_Right_Half_Ring_Below = 0x0339, // U+0339 Combining Right Half Ring Below U_Combining_Inverted_Bridge_Below = 0x033a, // U+033A Combining Inverted Bridge Below U_Combining_Square_Below = 0x033b, // U+033B Combining Square Below U_Combining_Seagull_Below = 0x033c, // U+033C Combining Seagull Below U_Combining_X_Above = 0x033d, // U+033D Combining X Above U_Combining_Vertical_Tilde = 0x033e, // U+033E Combining Vertical Tilde U_Combining_Double_Overline = 0x033f, // U+033F Combining Double Overline U_Combining_Grave_Tone_Mark = 0x0340, // U+0340 Combining Grave Tone Mark U_Combining_Acute_Tone_Mark = 0x0341, // U+0341 Combining Acute Tone Mark U_Combining_Greek_Perispomeni = 0x0342, // U+0342 Combining Greek Perispomeni U_Combining_Greek_Koronis = 0x0343, // U+0343 Combining Greek Koronis U_Combining_Greek_Dialytika_Tonos = 0x0344, // U+0344 Combining Greek Dialytika Tonos U_Combining_Greek_Ypogegrammeni = 0x0345, // U+0345 Combining Greek Ypogegrammeni U_Combining_Bridge_Above = 0x0346, // U+0346 Combining Bridge Above U_Combining_Equals_Sign_Below = 0x0347, // U+0347 Combining Equals Sign Below U_Combining_Double_Vertical_Line_Below = 0x0348, // U+0348 Combining Double Vertical Line Below U_Combining_Left_Angle_Below = 0x0349, // U+0349 Combining Left Angle Below U_Combining_Not_Tilde_Above = 0x034a, // U+034A Combining Not Tilde Above U_Combining_Homothetic_Above = 0x034b, // U+034B Combining Homothetic Above U_Combining_Almost_Equal_To_Above = 0x034c, // U+034C Combining Almost Equal To Above U_Combining_Left_Right_Arrow_Below = 0x034d, // U+034D Combining Left Right Arrow Below U_Combining_Upwards_Arrow_Below = 0x034e, // U+034E Combining Upwards Arrow Below U_Combining_Grapheme_Joiner = 0x034f, // U+034F Combining Grapheme Joiner U_Combining_Right_Arrowhead_Above = 0x0350, // U+0350 Combining Right Arrowhead Above U_Combining_Left_Half_Ring_Above = 0x0351, // U+0351 Combining Left Half Ring Above U_Combining_Fermata = 0x0352, // U+0352 Combining Fermata U_Combining_X_Below = 0x0353, // U+0353 Combining X Below U_Combining_Left_Arrowhead_Below = 0x0354, // U+0354 Combining Left Arrowhead Below U_Combining_Right_Arrowhead_Below = 0x0355, // U+0355 Combining Right Arrowhead Below U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below = 0x0356, // U+0356 Combining Right Arrowhead And Up Arrowhead Below U_Combining_Right_Half_Ring_Above = 0x0357, // U+0357 Combining Right Half Ring Above U_Combining_Dot_Above_Right = 0x0358, // U+0358 Combining Dot Above Right U_Combining_Asterisk_Below = 0x0359, // U+0359 Combining Asterisk Below U_Combining_Double_Ring_Below = 0x035a, // U+035A Combining Double Ring Below U_Combining_Zigzag_Above = 0x035b, // U+035B Combining Zigzag Above U_Combining_Double_Breve_Below = 0x035c, // U+035C Combining Double Breve Below U_Combining_Double_Breve = 0x035d, // U+035D Combining Double Breve U_Combining_Double_Macron = 0x035e, // U+035E Combining Double Macron U_Combining_Double_Macron_Below = 0x035f, // U+035F Combining Double Macron Below U_Combining_Double_Tilde = 0x0360, // U+0360 Combining Double Tilde U_Combining_Double_Inverted_Breve = 0x0361, // U+0361 Combining Double Inverted Breve U_Combining_Double_Rightwards_Arrow_Below = 0x0362, // U+0362 Combining Double Rightwards Arrow Below U_Combining_Latin_Small_Letter_A = 0x0363, // U+0363 Combining Latin Small Letter A U_Combining_Latin_Small_Letter_E = 0x0364, // U+0364 Combining Latin Small Letter E U_Combining_Latin_Small_Letter_I = 0x0365, // U+0365 Combining Latin Small Letter I U_Combining_Latin_Small_Letter_O = 0x0366, // U+0366 Combining Latin Small Letter O U_Combining_Latin_Small_Letter_U = 0x0367, // U+0367 Combining Latin Small Letter U U_Combining_Latin_Small_Letter_C = 0x0368, // U+0368 Combining Latin Small Letter C U_Combining_Latin_Small_Letter_D = 0x0369, // U+0369 Combining Latin Small Letter D U_Combining_Latin_Small_Letter_H = 0x036a, // U+036A Combining Latin Small Letter H U_Combining_Latin_Small_Letter_M = 0x036b, // U+036B Combining Latin Small Letter M U_Combining_Latin_Small_Letter_R = 0x036c, // U+036C Combining Latin Small Letter R U_Combining_Latin_Small_Letter_T = 0x036d, // U+036D Combining Latin Small Letter T U_Combining_Latin_Small_Letter_V = 0x036e, // U+036E Combining Latin Small Letter V U_Combining_Latin_Small_Letter_X = 0x036f, // U+036F Combining Latin Small Letter X /** * Unicode Character 'LINE SEPARATOR' (U+2028) * http://www.fileformat.info/info/unicode/char/2028/index.htm */ LINE_SEPARATOR_2028 = 8232, // http://www.fileformat.info/info/unicode/category/Sk/list.htm U_CIRCUMFLEX = 0x005e, // U+005E CIRCUMFLEX U_GRAVE_ACCENT = 0x0060, // U+0060 GRAVE ACCENT U_DIAERESIS = 0x00a8, // U+00A8 DIAERESIS U_MACRON = 0x00af, // U+00AF MACRON U_ACUTE_ACCENT = 0x00b4, // U+00B4 ACUTE ACCENT U_CEDILLA = 0x00b8, // U+00B8 CEDILLA U_MODIFIER_LETTER_LEFT_ARROWHEAD = 0x02c2, // U+02C2 MODIFIER LETTER LEFT ARROWHEAD U_MODIFIER_LETTER_RIGHT_ARROWHEAD = 0x02c3, // U+02C3 MODIFIER LETTER RIGHT ARROWHEAD U_MODIFIER_LETTER_UP_ARROWHEAD = 0x02c4, // U+02C4 MODIFIER LETTER UP ARROWHEAD U_MODIFIER_LETTER_DOWN_ARROWHEAD = 0x02c5, // U+02C5 MODIFIER LETTER DOWN ARROWHEAD U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING = 0x02d2, // U+02D2 MODIFIER LETTER CENTRED RIGHT HALF RING U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING = 0x02d3, // U+02D3 MODIFIER LETTER CENTRED LEFT HALF RING U_MODIFIER_LETTER_UP_TACK = 0x02d4, // U+02D4 MODIFIER LETTER UP TACK U_MODIFIER_LETTER_DOWN_TACK = 0x02d5, // U+02D5 MODIFIER LETTER DOWN TACK U_MODIFIER_LETTER_PLUS_SIGN = 0x02d6, // U+02D6 MODIFIER LETTER PLUS SIGN U_MODIFIER_LETTER_MINUS_SIGN = 0x02d7, // U+02D7 MODIFIER LETTER MINUS SIGN U_BREVE = 0x02d8, // U+02D8 BREVE U_DOT_ABOVE = 0x02d9, // U+02D9 DOT ABOVE U_RING_ABOVE = 0x02da, // U+02DA RING ABOVE U_OGONEK = 0x02db, // U+02DB OGONEK U_SMALL_TILDE = 0x02dc, // U+02DC SMALL TILDE U_DOUBLE_ACUTE_ACCENT = 0x02dd, // U+02DD DOUBLE ACUTE ACCENT U_MODIFIER_LETTER_RHOTIC_HOOK = 0x02de, // U+02DE MODIFIER LETTER RHOTIC HOOK U_MODIFIER_LETTER_CROSS_ACCENT = 0x02df, // U+02DF MODIFIER LETTER CROSS ACCENT U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR = 0x02e5, // U+02E5 MODIFIER LETTER EXTRA-HIGH TONE BAR U_MODIFIER_LETTER_HIGH_TONE_BAR = 0x02e6, // U+02E6 MODIFIER LETTER HIGH TONE BAR U_MODIFIER_LETTER_MID_TONE_BAR = 0x02e7, // U+02E7 MODIFIER LETTER MID TONE BAR U_MODIFIER_LETTER_LOW_TONE_BAR = 0x02e8, // U+02E8 MODIFIER LETTER LOW TONE BAR U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR = 0x02e9, // U+02E9 MODIFIER LETTER EXTRA-LOW TONE BAR U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK = 0x02ea, // U+02EA MODIFIER LETTER YIN DEPARTING TONE MARK U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK = 0x02eb, // U+02EB MODIFIER LETTER YANG DEPARTING TONE MARK U_MODIFIER_LETTER_UNASPIRATED = 0x02ed, // U+02ED MODIFIER LETTER UNASPIRATED U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD = 0x02ef, // U+02EF MODIFIER LETTER LOW DOWN ARROWHEAD U_MODIFIER_LETTER_LOW_UP_ARROWHEAD = 0x02f0, // U+02F0 MODIFIER LETTER LOW UP ARROWHEAD U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD = 0x02f1, // U+02F1 MODIFIER LETTER LOW LEFT ARROWHEAD U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD = 0x02f2, // U+02F2 MODIFIER LETTER LOW RIGHT ARROWHEAD U_MODIFIER_LETTER_LOW_RING = 0x02f3, // U+02F3 MODIFIER LETTER LOW RING U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT = 0x02f4, // U+02F4 MODIFIER LETTER MIDDLE GRAVE ACCENT U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT = 0x02f5, // U+02F5 MODIFIER LETTER MIDDLE DOUBLE GRAVE ACCENT U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT = 0x02f6, // U+02F6 MODIFIER LETTER MIDDLE DOUBLE ACUTE ACCENT U_MODIFIER_LETTER_LOW_TILDE = 0x02f7, // U+02F7 MODIFIER LETTER LOW TILDE U_MODIFIER_LETTER_RAISED_COLON = 0x02f8, // U+02F8 MODIFIER LETTER RAISED COLON U_MODIFIER_LETTER_BEGIN_HIGH_TONE = 0x02f9, // U+02F9 MODIFIER LETTER BEGIN HIGH TONE U_MODIFIER_LETTER_END_HIGH_TONE = 0x02fa, // U+02FA MODIFIER LETTER END HIGH TONE U_MODIFIER_LETTER_BEGIN_LOW_TONE = 0x02fb, // U+02FB MODIFIER LETTER BEGIN LOW TONE U_MODIFIER_LETTER_END_LOW_TONE = 0x02fc, // U+02FC MODIFIER LETTER END LOW TONE U_MODIFIER_LETTER_SHELF = 0x02fd, // U+02FD MODIFIER LETTER SHELF U_MODIFIER_LETTER_OPEN_SHELF = 0x02fe, // U+02FE MODIFIER LETTER OPEN SHELF U_MODIFIER_LETTER_LOW_LEFT_ARROW = 0x02ff, // U+02FF MODIFIER LETTER LOW LEFT ARROW U_GREEK_LOWER_NUMERAL_SIGN = 0x0375, // U+0375 GREEK LOWER NUMERAL SIGN U_GREEK_TONOS = 0x0384, // U+0384 GREEK TONOS U_GREEK_DIALYTIKA_TONOS = 0x0385, // U+0385 GREEK DIALYTIKA TONOS U_GREEK_KORONIS = 0x1fbd, // U+1FBD GREEK KORONIS U_GREEK_PSILI = 0x1fbf, // U+1FBF GREEK PSILI U_GREEK_PERISPOMENI = 0x1fc0, // U+1FC0 GREEK PERISPOMENI U_GREEK_DIALYTIKA_AND_PERISPOMENI = 0x1fc1, // U+1FC1 GREEK DIALYTIKA AND PERISPOMENI U_GREEK_PSILI_AND_VARIA = 0x1fcd, // U+1FCD GREEK PSILI AND VARIA U_GREEK_PSILI_AND_OXIA = 0x1fce, // U+1FCE GREEK PSILI AND OXIA U_GREEK_PSILI_AND_PERISPOMENI = 0x1fcf, // U+1FCF GREEK PSILI AND PERISPOMENI U_GREEK_DASIA_AND_VARIA = 0x1fdd, // U+1FDD GREEK DASIA AND VARIA U_GREEK_DASIA_AND_OXIA = 0x1fde, // U+1FDE GREEK DASIA AND OXIA U_GREEK_DASIA_AND_PERISPOMENI = 0x1fdf, // U+1FDF GREEK DASIA AND PERISPOMENI U_GREEK_DIALYTIKA_AND_VARIA = 0x1fed, // U+1FED GREEK DIALYTIKA AND VARIA U_GREEK_DIALYTIKA_AND_OXIA = 0x1fee, // U+1FEE GREEK DIALYTIKA AND OXIA U_GREEK_VARIA = 0x1fef, // U+1FEF GREEK VARIA U_GREEK_OXIA = 0x1ffd, // U+1FFD GREEK OXIA U_GREEK_DASIA = 0x1ffe, // U+1FFE GREEK DASIA U_OVERLINE = 0x203e, // Unicode Character 'OVERLINE' /** * UTF-8 BOM * Unicode Character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF) * http://www.fileformat.info/info/unicode/char/feff/index.htm */ UTF8_BOM = 65279, }
the_stack
import { RouterModule } from '@angular/router'; import { NgModule } from '@angular/core'; import {HomeComponent} from './home/home.component'; import {GettingStartedComponent} from './getting-started/getting-started.component'; @NgModule({ imports: [ RouterModule.forRoot([ // Showcase { path: '', component: HomeComponent }, { path: 'gettingstarted', component: GettingStartedComponent }, { path: 'home', component: HomeComponent }, { path: 'i18n', loadChildren: () => import('./internationalization/internationalization.module').then(m => m.InternationalizationModule) }, { path: 'theming', loadChildren: () => import('./theming/theming.module').then(m => m.ThemingModule) }, // Components { path: 'accordion', loadChildren: () => import('./components/accordion/accordiondemo.module').then(m => m.AccordionDemoModule) }, { path: 'autocomplete', loadChildren: () => import('./components/autocomplete/autocompletedemo.module').then(m => m.AutoCompleteDemoModule) }, { path: 'tag', loadChildren: () => import('./components/tag/tagdemo.module').then(m => m.TagDemoModule) }, { path: 'avatar', loadChildren: () => import('./components/avatar/avatardemo.module').then(m => m.AvatarDemoModule) }, { path: 'badge', loadChildren: () => import('./components/badge/badgedemo.module').then(m => m.BadgeDemoModule) }, { path: 'card', loadChildren: () => import('./components/card/carddemo.module').then(m => m.CardDemoModule) }, { path: 'button', loadChildren: () => import('./components/button/buttondemo.module').then(m => m.ButtonDemoModule) }, { path: 'buttongroup', loadChildren: () => import('./components/buttongroup/buttongroupdemo.module').then(m => m.ButtonGroupDemoModule) }, { path: 'blockui', loadChildren: () => import('./components/blockui/blockuidemo.module').then(m => m.BlockUIDemoModule) }, { path: 'calendar', loadChildren: () => import('./components/calendar/calendardemo.module').then(m => m.CalendarDemoModule) }, { path: 'colorpicker', loadChildren: () => import('./components/colorpicker/colorpickerdemo.module').then(m => m.ColorPickerDemoModule) }, { path: 'chatlist', loadChildren: () => import('./components/chatlist/chatlistdemo.module').then(m => m.ChatListDemoModule) }, { path: 'checkbox', loadChildren: () => import('./components/checkbox/checkboxdemo.module').then(m => m.CheckBoxDemoModule) }, { path: 'contextmenu', loadChildren: () => import('./components/contextmenu/context-menudemo.module').then(m => m.ContextMenuDemoModule) }, { path: 'step', loadChildren: () => import('./components/step/stepdemo.module').then(m => m.StepDemoModule) }, { path: 'upload', loadChildren: () => import('./components/upload/uploaddemo.module').then(m => m.UploadDemoModule) }, { path: 'datatable', loadChildren: () => import('./components/datatable/overview/datatabledemo-overview.module').then(m => m.DatatableDemoOverviewModule) }, { path: 'datatable/columnfeatures', // tslint:disable-next-line:max-line-length loadChildren: () => import('./components/datatable/columnfeatures/datatable-columnfeatures.demo.module').then(m => m.DatatableColumnFeaturesDemoModule) }, { path: 'datatable/filtering', // tslint:disable-next-line:max-line-length loadChildren: () => import('./components/datatable/filtering/datatable-filtering.demo.module').then(m => m.DatatableFilteringDemoModule) }, { path: 'datatable/rowmodels', // tslint:disable-next-line:max-line-length loadChildren: () => import('./components/datatable/rowmodels/datatable-rowmodels.demo.module').then(m => m.DatatableRowModelsDemoModule) }, { path: 'datatable/tablemodes', // tslint:disable-next-line:max-line-length loadChildren: () => import('./components/datatable/tablemodes/datatable-tablemodes.demo.module').then(m => m.DatatableTableModesDemoModule) }, { path: 'dialog', loadChildren: () => import('./components/dialog/dialogdemo.module').then(m => m.DialogDemoModule) }, { path: 'date', loadChildren: () => import('./components/date/datedemo.module').then(m => m.DateDemoModule) }, { path: 'dropdownlist', loadChildren: () => import('./components/dropdownlist/dropdownlistdemo.module').then(m => m.DropDownListDemoModule) }, { path: 'lightbox', loadChildren: () => import('./components/lightbox/lightboxdemo.module').then(m => m.LightboxDemoModule) }, { path: 'dropdownicon', loadChildren: () => import('./components/dropdownicon/dropdownicondemo.module').then(m => m.DropDownIconDemoModule) }, { path: 'datepicker', loadChildren: () => import('./components/datepicker/datepickerdemo.module').then(m => m.DatePickerDemoModule) }, { path: 'editor', loadChildren: () => import('./components/editor/editordemo.module').then(m => m.EditorDemoModule) }, { path: 'form', loadChildren: () => import('./components/form/formdemo.module').then(m => m.FormDemoModule) }, { path: 'inlineform', loadChildren: () => import('./components/form/inline/form-inlinedemo.module').then(m => m.FormInlineDemoModule) }, { path: 'modalform', loadChildren: () => import('./components/form/modal/form-modaldemo.module').then(m => m.FormModalDemoModule) }, { path: 'smartform', loadChildren: () => import('./components/form/smart/form-smartdemo.module').then(m => m.FormSmartDemoModule) }, { path: 'input', loadChildren: () => import('./components/input/inputdemo.module').then(m => m.InputDemoModule) }, { path: 'inputvalidators', loadChildren: () => import('./components/inputvalidators/inputvalidatorsdemo.module').then(m => m.InputValidatorsDemoModule) }, { path: 'inputmask', loadChildren: () => import('./components/inputmask/inputmaskdemo.module').then(m => m.InputMaskDemoModule) }, { path: 'inputcurrency', loadChildren: () => import('./components/inputcurrency/inputcurrencydemo.module').then(m => m.InputCurrencyDemoModule) }, { path: 'icons', loadChildren: () => import('./components/icons/overview/iconsdemo.module').then(m => m.IconsDemoModule) }, { path: 'icons/dxicons', loadChildren: () => import('./components/icons/dxicons/iconsdemo.module').then(m => m.IconsDemoModule) }, { path: 'icons/font-awesome', loadChildren: () => import('./components/icons/font-awesome/iconsdemo.module').then(m => m.IconsDemoModule) }, { path: 'icons/ionicons', loadChildren: () => import('./components/icons/ionicons/iconsdemo.module').then(m => m.IconsDemoModule) }, { path: 'loader', loadChildren: () => import('./components/loader/loaderdemo.module').then(m => m.LoaderDemoModule) }, { path: 'skeleton', loadChildren: () => import('./components/skeleton/skeletondemo.module').then(m => m.SkeletondemoModule) }, { path: 'listbox', loadChildren: () => import('./components/listbox/listboxdemo.module').then(m => m.ListBoxDemoModule) }, { path: 'modal', loadChildren: () => import('./components/modal/modaldemo.module').then(m => m.ModalDemoModule) }, { path: 'multiselect', loadChildren: () => import('./components/multiselect/multiselectdemo.module').then(m => m.MultiSelectDemoModule) }, { path: 'menu', loadChildren: () => import('./components/menu/menudemo.module').then(m => m.MenuDemoModule) }, { path: 'multiview', loadChildren: () => import('./components/multiview/multiviewdemo.module').then(m => m.MultiViewDemoModule) }, { path: 'overlaypanel', loadChildren: () => import('./components/overlaypanel/overlay-paneldemo.module').then(m => m.OverlayPanelDemoModule) }, { path: 'navigator', loadChildren: () => import('./components/navigator/navigatordemo.module').then(m => m.NavigatorDemoModule) }, { path: 'thumbnail', loadChildren: () => import('./components/thumbnail/thumbnaildemo.module').then(m => m.ThumbnailDemoModule) }, { path: 'panelgroup', loadChildren: () => import('./components/panel/paneldemo.module').then(m => m.PanelDemoModule) }, { path: 'permissions', loadChildren: () => import('./components/permissions/permissionsdemo.module').then(m => m.PermissionsDemoModule) }, { path: 'progressbar', loadChildren: () => import('./components/progressbar/progressbardemo.module').then(m => m.ProgressBarDemoModule) }, { path: 'popupmenu', loadChildren: () => import('./components/popupmenu/popupmenudemo.module').then(m => m.PopupMenuDemoModule) }, { path: 'radiobutton', loadChildren: () => import('./components/radiobutton/radiobuttondemo.module').then(m => m.RadioButtonDemoModule) }, { path: 'shortcut', loadChildren: () => import('./components/shortcut/shortcutdemo.module').then(m => m.ShortcutDemoModule) }, { path: 'schedule', loadChildren: () => import('./components/schedule/overview/scheduledemo-overview.module').then(m => m.ScheduledemoOverviewModule) }, { path: 'sidebar', loadChildren: () => import('./components/sidebar/sidebardemo.module').then(m => m.SidebarDemoModule) }, { path: 'splitbutton', loadChildren: () => import('./components/splitbutton/splitbuttondemo.module').then(m => m.SplitButtonDemoModule) }, { path: 'stopwatch', loadChildren: () => import('./components/stopwatch/stopwatchdemo.module').then(m => m.StopwatchDemoModule) }, { path: 'switch', loadChildren: () => import('./components/switch/switchdemo.module').then(m => m.SwitchDemoModule) }, { path: 'textarea', loadChildren: () => import('./components/textarea/textareademo.module').then(m => m.TextareaDemoModule) }, { path: 'clockpicker', loadChildren: () => import('./components/clockpicker/clockpickerdemo.module').then(m => m.ClockPickerDemoModule) }, { path: 'timeline', loadChildren: () => import('./components/timeline/overview/timelinedemo.module').then(m => m.TimelineDemoModule) }, { path: 'timepicker', loadChildren: () => import('./components/timepicker/timepickerdemo.module').then(m => m.TimepickerDemoModule) }, { path: 'timeavailable', // tslint:disable-next-line:max-line-length loadChildren: () => import('./components/time-available-picker/time-available-pickerdemo.module').then(m => m.TimeAvailablePickerDemoModule) }, { path: 'timeline/infinitescroll', loadChildren: () => import('./components/timeline/infinitescroll/timelinedemo.module').then(m => m.TimelineDemoModule) }, { path: 'timeline/dynamictemplate', loadChildren: () => import('./components/timeline/templatedynamic/timelinedemo.module').then(m => m.TimelineDemoModule) }, { path: 'tabcontrol', loadChildren: () => import('./components/tabcontrol/tabcontroldemo.module').then(m => m.TabControlDemoModule) }, { path: 'toaster', loadChildren: () => import('./components/toaster/toasterdemo.module').then(m => m.ToasterDemoModule) }, { path: 'toolbar', loadChildren: () => import('./components/toolbar/toolbardemo.module').then(m => m.ToolbarDemoModule) }, { path: 'tooltip', loadChildren: () => import('./components/tooltip/tooltipdemo.module').then(m => m.TooltipDemoModule) }, { path: 'overlaypanel', loadChildren: () => import('./components/overlaypanel/overlay-paneldemo.module').then(m => m.OverlayPanelDemoModule) }, ]) ], exports: [RouterModule] }) export class AppRoutingModule {}
the_stack
import { Mqtt as Protocol } from 'azure-iot-device-mqtt'; import { Mqtt as ProvProtocol } from 'azure-iot-provisioning-device-mqtt'; import { Client, Message, Twin } from 'azure-iot-device'; import { ConnectionString } from 'azure-iot-common'; import { SymmetricKeySecurityClient } from 'azure-iot-security-symmetric-key'; import { ProvisioningDeviceClient, RegistrationResult } from 'azure-iot-provisioning-device'; import { ProvisioningPayload, RegistrationClient } from 'azure-iot-provisioning-device/dist/interfaces'; let deviceConnectionString = process.env.IOTHUB_DEVICE_CONNECTION_STRING || ''; // DPS connection information const provisioningHost = process.env.IOTHUB_DEVICE_DPS_ENDPOINT || 'global.azure-devices-provisioning.net'; const idScope = process.env.IOTHUB_DEVICE_DPS_ID_SCOPE; const registrationId = process.env.IOTHUB_DEVICE_DPS_DEVICE_ID; const symmetricKey = process.env.IOTHUB_DEVICE_DPS_DEVICE_KEY; const useDps = process.env.IOTHUB_DEVICE_SECURITY_TYPE || 'connectionString'; const modelIdObject: { modelId: string } = { modelId: 'dtmi:com:example:TemperatureController;2', }; const messageSubjectProperty = '$.sub'; const thermostat1ComponentName = 'thermostat1'; const thermostat2ComponentName = 'thermostat2'; const deviceInfoComponentName = 'deviceInformation'; const commandComponentCommandNameSeparator = '*'; let intervalToken1: NodeJS.Timer; let intervalToken2: NodeJS.Timer; let intervalToken3: NodeJS.Timer; class TemperatureSensor { currTemp: number; maxTemp: number; minTemp: number; cumulativeTemperature: number; startTime: string; numberOfTemperatureReadings: number; constructor() { this.currTemp = 1 + Math.random() * 90; this.maxTemp = this.currTemp; this.minTemp = this.currTemp; this.cumulativeTemperature = this.currTemp; this.startTime = new Date(Date.now()).toISOString(); this.numberOfTemperatureReadings = 1; } getCurrentTemperatureObject(): { temperature: number } { return { temperature: this.currTemp }; } updateSensor(): this { this.currTemp = 1 + Math.random() * 90; this.cumulativeTemperature += this.currTemp; this.numberOfTemperatureReadings++; if (this.currTemp > this.maxTemp) this.maxTemp = this.currTemp; if (this.currTemp < this.minTemp) this.minTemp = this.currTemp; return this; } getMaxMinReportObject(): { maxTemp: number; minTemp: number; avgTemp: number; endTime: string; startTime: string; } { return { maxTemp: this.maxTemp, minTemp: this.minTemp, avgTemp: this.cumulativeTemperature / this.numberOfTemperatureReadings, endTime: new Date(Date.now()).toISOString(), startTime: this.startTime, }; } getMaxTemperatureValue(): number { return this.maxTemp; } } const thermostat1: TemperatureSensor = new TemperatureSensor(); const thermostat2: TemperatureSensor = new TemperatureSensor(); const commandNameGetMaxMinReport1 = thermostat1ComponentName + commandComponentCommandNameSeparator + 'getMaxMinReport'; const commandNameGetMaxMinReport2 = thermostat2ComponentName + commandComponentCommandNameSeparator + 'getMaxMinReport'; const commandNameReboot = 'reboot'; const serialNumber = 'alwinexlepaho8329'; const commandHandler = async (request: { methodName: any }, response: any) => { helperLogCommandRequest(request); switch (request.methodName) { case commandNameGetMaxMinReport1: { await sendCommandResponse( request, response, 200, thermostat1.getMaxMinReportObject() ); break; } case commandNameGetMaxMinReport2: { await sendCommandResponse( request, response, 200, thermostat2.getMaxMinReportObject() ); break; } case commandNameReboot: { await sendCommandResponse(request, response, 200, 'reboot response'); break; } default: await sendCommandResponse(request, response, 404, 'unknown method'); break; } }; const sendCommandResponse: ( request: { methodName: any }, response: any, status: number, payload: any ) => Promise<void> = async ( request: { methodName: any }, response: any, status: number, payload: any ) => { try { await response.send(status, payload); console.log( 'Response to method: ' + request.methodName + ' sent successfully.' ); } catch (err) { console.error( 'An error ocurred when sending a method response:\n' + err.toString() ); } }; const helperLogCommandRequest: (request: { methodName: any; payload?: any; }) => void = (request: { methodName: any; payload?: any }) => { console.log( 'Received command request for command name: ' + request.methodName ); if (!!request.payload) { console.log('The command request payload is:'); console.log(request.payload); } }; const helperCreateReportedPropertiesPatch: (propertiesToReport: any, componentName: any) => {} = ( propertiesToReport: any, componentName: any ) => { let patch; if (!!componentName) { patch = {}; propertiesToReport.__t = 'c'; patch[componentName] = propertiesToReport; } else { patch = {}; patch = propertiesToReport; } if (!!componentName) { console.log( 'The following properties will be updated for component: ' + componentName ); } else { console.log('The following properties will be updated for root interface.'); } console.log(patch); return patch; }; const updateComponentReportedProperties: (deviceTwin: Twin, patch: any, componentName: string) => void = ( deviceTwin: Twin, patch: any, componentName: string ) => { let logLine: string; if (!!componentName) { logLine = 'Properties have been reported for component: ' + componentName; } else { logLine = 'Properties have been reported for root interface.'; } deviceTwin.properties.reported.update(patch, function (err: Error): any { if (err) throw err; console.log(logLine); }); }; const desiredPropertyPatchListener = (deviceTwin: Twin, componentNames: any) => { deviceTwin.on('properties.desired', (delta) => { console.log( 'Received an update for device with value: ' + JSON.stringify(delta) ); Object.entries(delta).forEach(([key, values]) => { const version = delta.$version; if (!!componentNames && componentNames.includes(key)) { // then it is a component we are expecting const componentName = key; const patchForComponents = { [componentName]: {} }; Object.entries(values).forEach(([propertyName, propertyValue]) => { if (propertyName !== '__t' && propertyName !== '$version') { console.log('Will update property: ' + propertyName + ' to value: ' + propertyValue + ' of component: ' + componentName); const propertyContent: any = { value: propertyValue }; propertyContent.ac = 200; propertyContent.ad = 'Successfully executed patch'; propertyContent.av = version; patchForComponents[componentName][propertyName] = propertyContent; } }); updateComponentReportedProperties( deviceTwin, patchForComponents, componentName ); } else if (key !== '$version') { // individual property for root const patchForRoot = {}; console.log( 'Will update property: ' + key + ' to value: ' + values + ' for root' ); const propertyContent: any = { value: values }; propertyContent.ac = 200; propertyContent.ad = 'Successfully executed patch'; propertyContent.av = version; patchForRoot[key] = propertyContent; updateComponentReportedProperties(deviceTwin, patchForRoot, null); } }); }); }; const exitListener: (deviceClient: Client) => Promise<void> = async (deviceClient: Client) => { const standardInput = process.stdin; standardInput.setEncoding('utf-8'); console.log('Please enter q or Q to exit sample.'); standardInput.on('data', (data: string) => { if (data === 'q\n' || data === 'Q\n') { console.log('Clearing intervals and exiting sample.'); clearInterval(intervalToken1); clearInterval(intervalToken2); clearInterval(intervalToken3); deviceClient.close(); process.exit(); } else { console.log('User Input was: ' + data); console.log('Please only enter q or Q to exit sample.'); } }); }; async function sendTelemetry(deviceClient: Client, data: string | Message.BufferConvertible, index: number, componentName: string): Promise<void> { if (!!componentName) { console.log( 'Sending telemetry message %d from component: %s ', index, componentName ); } else { console.log('Sending telemetry message %d from root interface', index); } const msg = new Message(data); if (!!componentName) { msg.properties.add(messageSubjectProperty, componentName); } msg.contentType = 'application/json'; msg.contentEncoding = 'utf-8'; await deviceClient.sendEvent(msg); } async function provisionDevice(payload: ProvisioningPayload): Promise<void> { const provSecurityClient: SymmetricKeySecurityClient = new SymmetricKeySecurityClient( registrationId, symmetricKey ); const provisioningClient: RegistrationClient = ProvisioningDeviceClient.create( provisioningHost, idScope, new ProvProtocol(), provSecurityClient ); if (!!payload) { provisioningClient.setProvisioningPayload(payload); } try { let result: RegistrationResult | any = await provisioningClient.register(); deviceConnectionString = 'HostName=' + result.assignedHub + ';DeviceId=' + result.deviceId + ';SharedAccessKey=' + symmetricKey; console.log('registration succeeded'); console.log('assigned hub=' + result.assignedHub); console.log('deviceId=' + result.deviceId); console.log('payload=' + JSON.stringify(result.payload)); } catch (err) { console.error('error registering device: ' + err.toString()); } } async function main(): Promise<void> { // If the user include a provision host then use DPS if (useDps === 'DPS') { await provisionDevice(modelIdObject); } else if (useDps === 'connectionString') { try { if ( !( deviceConnectionString && ConnectionString.parse(deviceConnectionString, [ 'HostName', 'DeviceId', ]) ) ) { console.error('Connection string was not specified.'); process.exit(1); } } catch (err) { console.error('Invalid connection string specified.'); process.exit(1); } } else { console.log('No proper SECURITY TYPE provided.'); process.exit(1); } // fromConnectionString must specify a transport, coming from any transport package. const client: Client = Client.fromConnectionString(deviceConnectionString, Protocol); console.log('Connecting using connection string: ' + deviceConnectionString); let resultTwin; try { // Add the modelId here await client.setOptions(modelIdObject); await client.open(); console.log('Enabling the commands on the client'); client.onDeviceMethod(commandNameGetMaxMinReport1, commandHandler); client.onDeviceMethod(commandNameGetMaxMinReport2, commandHandler); client.onDeviceMethod(commandNameReboot, commandHandler); // Send Telemetry after some interval let index1 = 0; let index2 = 0; let index3 = 0; intervalToken1 = setInterval(() => { const data = JSON.stringify( thermostat1.updateSensor().getCurrentTemperatureObject() ); sendTelemetry(client, data, index1, thermostat1ComponentName).catch( (err) => console.log('error ', err.toString()) ); index1 += 1; }, 5000); intervalToken2 = setInterval(() => { const data = JSON.stringify( thermostat2.updateSensor().getCurrentTemperatureObject() ); sendTelemetry(client, data, index2, thermostat2ComponentName).catch( (err) => console.log('error ', err.toString()) ); index2 += 1; }, 5500); intervalToken3 = setInterval(() => { const data = JSON.stringify({ workingset: 1 + Math.random() * 90 }); sendTelemetry(client, data, index3, null).catch((err) => console.log('error ', err.toString()) ); index3 += 1; }, 6000); // attach a standard input exit listener exitListener(client); try { resultTwin = await client.getTwin(); // Only report readable properties const patchRoot: {} = helperCreateReportedPropertiesPatch({ serialNumber: serialNumber }, null); const patchThermostat1Info = helperCreateReportedPropertiesPatch({ maxTempSinceLastReboot: thermostat1.getMaxTemperatureValue(), }, thermostat1ComponentName); const patchThermostat2Info = helperCreateReportedPropertiesPatch({maxTempSinceLastReboot: thermostat2.getMaxTemperatureValue(),}, thermostat2ComponentName); const patchDeviceInfo = helperCreateReportedPropertiesPatch( { manufacturer: 'Contoso Device Corporation', model: 'Contoso 47-turbo', swVersion: '10.89', osName: 'Contoso_OS', processorArchitecture: 'Contoso_x86', processorManufacturer: 'Contoso Industries', totalStorage: 65000, totalMemory: 640, }, deviceInfoComponentName ); // the below things can only happen once the twin is there updateComponentReportedProperties(resultTwin, patchRoot, null); updateComponentReportedProperties(resultTwin, patchThermostat1Info, thermostat1ComponentName); updateComponentReportedProperties(resultTwin, patchThermostat2Info, thermostat2ComponentName); updateComponentReportedProperties(resultTwin, patchDeviceInfo, deviceInfoComponentName); desiredPropertyPatchListener(resultTwin, [thermostat1ComponentName, thermostat2ComponentName, deviceInfoComponentName,]); } catch (err) { console.error( 'could not retrieve twin or report twin properties\n' + err.toString() ); } } catch (err) { console.error( 'could not connect Plug and Play client or could not attach interval function for telemetry\n' + err.toString() ); } } main() .then(() => console.log('executed sample')) .catch((err) => console.log('error', err));
the_stack
const _PI = Math.PI // GRAPHICS RENDERER /** * The default, two-dimensional renderer. * @property {String} P2D * @final */ export const P2D = 'p2d' /** * One of the two render modes in p5.js: P2D (default renderer) and WEBGL * Enables 3D render by introducing the third dimension: Z * @property {String} WEBGL * @final */ export const WEBGL = 'webgl' // ENVIRONMENT /** * @property {String} ARROW * @final */ export const ARROW = 'default' /** * @property {String} CROSS * @final */ export const CROSS = 'crosshair' /** * @property {String} HAND * @final */ export const HAND = 'pointer' /** * @property {String} MOVE * @final */ export const MOVE = 'move' /** * @property {String} TEXT * @final */ export const TEXT = 'text' /** * @property {String} WAIT * @final */ export const WAIT = 'wait' // TRIGONOMETRY /** * HALF_PI is a mathematical constant with the value * 1.57079632679489661923. It is half the ratio of the * circumference of a circle to its diameter. It is useful in * combination with the trigonometric functions <a href="#/p5/sin">sin()</a> and <a href="#/p5/cos">cos()</a>. * * @property {Number} HALF_PI * @final * * @example * <div><code> * arc(50, 50, 80, 80, 0, HALF_PI); * </code></div> * * @alt * 80x80 white quarter-circle with curve toward bottom right of canvas. */ export const HALF_PI = _PI / 2 /** * PI is a mathematical constant with the value * 3.14159265358979323846. It is the ratio of the circumference * of a circle to its diameter. It is useful in combination with * the trigonometric functions <a href="#/p5/sin">sin()</a> and <a href="#/p5/cos">cos()</a>. * * @property {Number} PI * @final * * @example * <div><code> * arc(50, 50, 80, 80, 0, PI); * </code></div> * * @alt * white half-circle with curve toward bottom of canvas. */ export const PI = _PI /** * QUARTER_PI is a mathematical constant with the value 0.7853982. * It is one quarter the ratio of the circumference of a circle to * its diameter. It is useful in combination with the trigonometric * functions <a href="#/p5/sin">sin()</a> and <a href="#/p5/cos">cos()</a>. * * @property {Number} QUARTER_PI * @final * * @example * <div><code> * arc(50, 50, 80, 80, 0, QUARTER_PI); * </code></div> * * @alt * white eighth-circle rotated about 40 degrees with curve bottom right canvas. */ export const QUARTER_PI = _PI / 4 /** * TAU is an alias for TWO_PI, a mathematical constant with the * value 6.28318530717958647693. It is twice the ratio of the * circumference of a circle to its diameter. It is useful in * combination with the trigonometric functions <a href="#/p5/sin">sin()</a> and <a href="#/p5/cos">cos()</a>. * * @property {Number} TAU * @final * * @example * <div><code> * arc(50, 50, 80, 80, 0, TAU); * </code></div> * * @alt * 80x80 white ellipse shape in center of canvas. */ export const TAU = _PI * 2 /** * TWO_PI is a mathematical constant with the value * 6.28318530717958647693. It is twice the ratio of the * circumference of a circle to its diameter. It is useful in * combination with the trigonometric functions <a href="#/p5/sin">sin()</a> and <a href="#/p5/cos">cos()</a>. * * @property {Number} TWO_PI * @final * * @example * <div><code> * arc(50, 50, 80, 80, 0, TWO_PI); * </code></div> * * @alt * 80x80 white ellipse shape in center of canvas. */ export const TWO_PI = _PI * 2 /** * Constant to be used with <a href="#/p5/angleMode">angleMode()</a> function, to set the mode which * p5.js interprates and calculates angles (either DEGREES or RADIANS). * @property {String} DEGREES * @final * * @example * <div class='norender'><code> * function setup() { * angleMode(DEGREES); * } * </code></div> */ export const DEGREES = 'degrees' /** * Constant to be used with <a href="#/p5/angleMode">angleMode()</a> function, to set the mode which * p5.js interprates and calculates angles (either RADIANS or DEGREES). * @property {String} RADIANS * @final * * @example * <div class='norender'><code> * function setup() { * angleMode(RADIANS); * } * </code></div> */ export const RADIANS = 'radians' export const DEG_TO_RAD = _PI / 180.0 export const RAD_TO_DEG = 180.0 / _PI // SHAPE /** * @property {String} CORNER * @final */ export const CORNER = 'corner' /** * @property {String} CORNERS * @final */ export const CORNERS = 'corners' /** * @property {String} RADIUS * @final */ export const RADIUS = 'radius' /** * @property {String} RIGHT * @final */ export const RIGHT = 'right' /** * @property {String} LEFT * @final */ export const LEFT = 'left' /** * @property {String} CENTER * @final */ export const CENTER = 'center' /** * @property {String} TOP * @final */ export const TOP = 'top' /** * @property {String} BOTTOM * @final */ export const BOTTOM = 'bottom' /** * @property {String} BASELINE * @final * @default alphabetic */ export const BASELINE = 'alphabetic' /** * @property {Number} POINTS * @final * @default 0x0000 */ export const POINTS = 0x0000 /** * @property {Number} LINES * @final * @default 0x0001 */ export const LINES = 0x0001 /** * @property {Number} LINE_STRIP * @final * @default 0x0003 */ export const LINE_STRIP = 0x0003 /** * @property {Number} LINE_LOOP * @final * @default 0x0002 */ export const LINE_LOOP = 0x0002 /** * @property {Number} TRIANGLES * @final * @default 0x0004 */ export const TRIANGLES = 0x0004 /** * @property {Number} TRIANGLE_FAN * @final * @default 0x0006 */ export const TRIANGLE_FAN = 0x0006 /** * @property {Number} TRIANGLE_STRIP * @final * @default 0x0005 */ export const TRIANGLE_STRIP = 0x0005 /** * @property {String} QUADS * @final */ export const QUADS = 'quads' /** * @property {String} QUAD_STRIP * @final * @default quad_strip */ export const QUAD_STRIP = 'quad_strip' /** * @property {String} TESS * @final * @default tess */ export const TESS = 'tess' /** * @property {String} CLOSE * @final */ export const CLOSE = 'close' /** * @property {String} OPEN * @final */ export const OPEN = 'open' /** * @property {String} CHORD * @final */ export const CHORD = 'chord' /** * @property {String} PIE * @final */ export const PIE = 'pie' /** * @property {String} PROJECT * @final * @default square */ export const PROJECT = 'square' // PEND: careful this is counterintuitive /** * @property {String} SQUARE * @final * @default butt */ export const SQUARE = 'butt' /** * @property {String} ROUND * @final */ export const ROUND = 'round' /** * @property {String} BEVEL * @final */ export const BEVEL = 'bevel' /** * @property {String} MITER * @final */ export const MITER = 'miter' // COLOR /** * @property {String} RGB * @final */ export const RGB = 'rgb' /** * HSB (hue, saturation, brightness) is a type of color model. * You can learn more about it at * <a href="https://learnui.design/blog/the-hsb-color-system-practicioners-primer.html">HSB</a>. * * @property {String} HSB * @final */ export const HSB = 'hsb' /** * @property {String} HSL * @final */ export const HSL = 'hsl' // DOM EXTENSION /** * AUTO allows us to automatically set the width or height of an element (but not both), * based on the current height and width of the element. Only one parameter can * be passed to the <a href="/#/p5.Element/size">size</a> function as AUTO, at a time. * * @property {String} AUTO * @final */ export const AUTO = 'auto' /** * @property {Number} ALT * @final */ // INPUT export const ALT = 18 /** * @property {Number} BACKSPACE * @final */ export const BACKSPACE = 8 /** * @property {Number} CONTROL * @final */ export const CONTROL = 17 /** * @property {Number} DELETE * @final */ export const DELETE = 46 /** * @property {Number} DOWN_ARROW * @final */ export const DOWN_ARROW = 40 /** * @property {Number} ENTER * @final */ export const ENTER = 13 /** * @property {Number} ESCAPE * @final */ export const ESCAPE = 27 /** * @property {Number} LEFT_ARROW * @final */ export const LEFT_ARROW = 37 /** * @property {Number} OPTION * @final */ export const OPTION = 18 /** * @property {Number} RETURN * @final */ export const RETURN = 13 /** * @property {Number} RIGHT_ARROW * @final */ export const RIGHT_ARROW = 39 /** * @property {Number} SHIFT * @final */ export const SHIFT = 16 /** * @property {Number} TAB * @final */ export const TAB = 9 /** * @property {Number} UP_ARROW * @final */ export const UP_ARROW = 38 // RENDERING /** * @property {String} BLEND * @final * @default source-over */ export const BLEND = 'source-over' /** * @property {String} REMOVE * @final * @default destination-out */ export const REMOVE = 'destination-out' /** * @property {String} ADD * @final * @default lighter */ export const ADD = 'lighter' // ADD: 'add', // // SUBTRACT: 'subtract', // /** * @property {String} DARKEST * @final */ export const DARKEST = 'darken' /** * @property {String} LIGHTEST * @final * @default lighten */ export const LIGHTEST = 'lighten' /** * @property {String} DIFFERENCE * @final */ export const DIFFERENCE = 'difference' /** * @property {String} SUBTRACT * @final */ export const SUBTRACT = 'subtract' /** * @property {String} EXCLUSION * @final */ export const EXCLUSION = 'exclusion' /** * @property {String} MULTIPLY * @final */ export const MULTIPLY = 'multiply' /** * @property {String} SCREEN * @final */ export const SCREEN = 'screen' /** * @property {String} REPLACE * @final * @default copy */ export const REPLACE = 'copy' /** * @property {String} OVERLAY * @final */ export const OVERLAY = 'overlay' /** * @property {String} HARD_LIGHT * @final */ export const HARD_LIGHT = 'hard-light' /** * @property {String} SOFT_LIGHT * @final */ export const SOFT_LIGHT = 'soft-light' /** * @property {String} DODGE * @final * @default color-dodge */ export const DODGE = 'color-dodge' /** * @property {String} BURN * @final * @default color-burn */ export const BURN = 'color-burn' // FILTERS /** * @property {String} THRESHOLD * @final */ export const THRESHOLD = 'threshold' /** * @property {String} GRAY * @final */ export const GRAY = 'gray' /** * @property {String} OPAQUE * @final */ export const OPAQUE = 'opaque' /** * @property {String} INVERT * @final */ export const INVERT = 'invert' /** * @property {String} POSTERIZE * @final */ export const POSTERIZE = 'posterize' /** * @property {String} DILATE * @final */ export const DILATE = 'dilate' /** * @property {String} ERODE * @final */ export const ERODE = 'erode' /** * @property {String} BLUR * @final */ export const BLUR = 'blur' // TYPOGRAPHY /** * @property {String} NORMAL * @final */ export const NORMAL = 'normal' /** * @property {String} ITALIC * @final */ export const ITALIC = 'italic' /** * @property {String} BOLD * @final */ export const BOLD = 'bold' /** * @property {String} BOLDITALIC * @final */ export const BOLDITALIC = 'bold italic' // TYPOGRAPHY-INTERNAL export const _DEFAULT_TEXT_FILL = '#000000' export const _DEFAULT_LEADMULT = 1.25 export const _CTX_MIDDLE = 'middle' // VERTICES /** * @property {String} LINEAR * @final */ export const LINEAR = 'linear' /** * @property {String} QUADRATIC * @final */ export const QUADRATIC = 'quadratic' /** * @property {String} BEZIER * @final */ export const BEZIER = 'bezier' /** * @property {String} CURVE * @final */ export const CURVE = 'curve' // WEBGL DRAWMODES /** * @property {String} STROKE * @final */ export const STROKE = 'stroke' /** * @property {String} FILL * @final */ export const FILL = 'fill' /** * @property {String} TEXTURE * @final */ export const TEXTURE = 'texture' /** * @property {String} IMMEDIATE * @final */ export const IMMEDIATE = 'immediate' // WEBGL TEXTURE MODE // NORMAL already exists for typography /** * @property {String} IMAGE * @final */ export const IMAGE = 'image' // WEBGL TEXTURE WRAP AND FILTERING // LINEAR already exists above /** * @property {String} NEAREST * @final */ export const NEAREST = 'nearest' /** * @property {String} REPEAT * @final */ export const REPEAT = 'repeat' /** * @property {String} CLAMP * @final */ export const CLAMP = 'clamp' /** * @property {String} MIRROR * @final */ export const MIRROR = 'mirror' // DEVICE-ORIENTATION /** * @property {String} LANDSCAPE * @final */ export const LANDSCAPE = 'landscape' /** * @property {String} PORTRAIT * @final */ export const PORTRAIT = 'portrait' // DEFAULTS export const _DEFAULT_STROKE = '#000000' export const _DEFAULT_FILL = '#FFFFFF' /** * @property {String} GRID * @final */ export const GRID = 'grid' /** * @property {String} AXES * @final */ export const AXES = 'axes' /** * @property {String} LABEL * @final */ export const LABEL = 'label' /** * @property {String} FALLBACK * @final */ export const FALLBACK = 'fallback'
the_stack
import test from 'japa' import { DbIncrementStrategy } from '../src/Strategies/DbIncrement' import { ApplicationContract } from '@ioc:Adonis/Core/Application' import { setupApplication, fs, setupDb, cleanDb, clearDb } from '../test-helpers' let app: ApplicationContract test.group('Db Increment Strategy', (group) => { group.beforeEach(async () => { app = await setupApplication() await setupDb(app.container.resolveBinding('Adonis/Lucid/Database')) }) group.afterEach(async () => { await clearDb(app.container.resolveBinding('Adonis/Lucid/Database')) }) group.after(async () => { await cleanDb(app.container.resolveBinding('Adonis/Lucid/Database')) await fs.cleanup() }) test('generate slug', async (assert) => { const { BaseModel } = app.container.resolveBinding('Adonis/Lucid/Orm') const Database = app.container.resolveBinding('Adonis/Lucid/Database') class Post extends BaseModel { public title: string public slug: string } Post.boot() Post.$addColumn('title', {}) Post.$addColumn('slug', {}) const dbIncrement = new DbIncrementStrategy(Database, { strategy: 'dbIncrement', fields: ['title'], }) const uniqueSlug = await dbIncrement.makeSlugUnique(Post, 'slug', 'hello-world') assert.equal(uniqueSlug, 'hello-world') }) test('add counter to existing duplicate slug', async (assert) => { const { BaseModel } = app.container.resolveBinding('Adonis/Lucid/Orm') const Database = app.container.resolveBinding('Adonis/Lucid/Database') class Post extends BaseModel { public title: string public slug: string } Post.boot() Post.$addColumn('title', {}) Post.$addColumn('slug', {}) await Post.createMany([ { title: 'Hello world', slug: 'hello-world', }, { title: 'Hello world', slug: 'hello-10-world', }, { title: 'Hello world', slug: 'hello10world', }, ]) const dbIncrement = new DbIncrementStrategy(Database, { strategy: 'dbIncrement', fields: ['title'], }) const uniqueSlug = await dbIncrement.makeSlugUnique(Post, 'slug', 'hello-world') assert.equal(uniqueSlug, 'hello-world-1') }) test('perform case insensitive search', async (assert) => { const { BaseModel } = app.container.resolveBinding('Adonis/Lucid/Orm') const Database = app.container.resolveBinding('Adonis/Lucid/Database') class Post extends BaseModel { public title: string public slug: string } Post.boot() Post.$addColumn('title', {}) Post.$addColumn('slug', {}) await Post.createMany([ { title: 'Hello world', slug: 'heLlo-World', }, { title: 'Hello world', slug: 'hello-10-world', }, { title: 'Hello world', slug: 'hello10world', }, ]) const dbIncrement = new DbIncrementStrategy(Database, { strategy: 'dbIncrement', fields: ['title'], }) const uniqueSlug = await dbIncrement.makeSlugUnique(Post, 'slug', 'hello-world') assert.equal(uniqueSlug, 'hello-world-1') }) test('ignore in between numeric values when generating counter', async (assert) => { const { BaseModel } = app.container.resolveBinding('Adonis/Lucid/Orm') const Database = app.container.resolveBinding('Adonis/Lucid/Database') class Post extends BaseModel { public title: string public slug: string } Post.boot() Post.$addColumn('title', {}) Post.$addColumn('slug', {}) await Post.createMany([ { title: 'Hello world', slug: 'post-hello-world', }, { title: 'Hello world', slug: 'post-11am-hello-world11', }, { title: 'Hello world', slug: 'post-11am-hello-world', }, ]) const dbIncrement = new DbIncrementStrategy(Database, { strategy: 'dbIncrement', fields: ['title'], }) const uniqueSlug = await dbIncrement.makeSlugUnique(Post, 'slug', 'post-11am-hello-world') assert.equal(uniqueSlug, 'post-11am-hello-world-1') }) test('generate unique slug when counter was manually tweaked', async (assert) => { const { BaseModel } = app.container.resolveBinding('Adonis/Lucid/Orm') const Database = app.container.resolveBinding('Adonis/Lucid/Database') class Post extends BaseModel { public title: string public slug: string } Post.boot() Post.$addColumn('title', {}) Post.$addColumn('slug', {}) await Post.createMany([ { title: 'Hello world', slug: 'hello-world', }, { title: 'Hello world 1', slug: 'hello-world-1', }, { title: 'Hello world 4', slug: 'hello-world-4', }, { title: 'Hello world fanny', slug: 'hello-world-fanny', }, ]) const dbIncrement = new DbIncrementStrategy(Database, { strategy: 'dbIncrement', fields: ['title'], }) const uniqueSlug = await dbIncrement.makeSlugUnique(Post, 'slug', 'hello-world') assert.equal(uniqueSlug, 'hello-world-5') }) }) test.group('Db Increment Strategy | custom separator', (group) => { group.beforeEach(async () => { app = await setupApplication() await setupDb(app.container.resolveBinding('Adonis/Lucid/Database')) }) group.afterEach(async () => { await clearDb(app.container.resolveBinding('Adonis/Lucid/Database')) }) group.after(async () => { await cleanDb(app.container.resolveBinding('Adonis/Lucid/Database')) await fs.cleanup() }) test('generate slug', async (assert) => { const { BaseModel } = app.container.resolveBinding('Adonis/Lucid/Orm') const Database = app.container.resolveBinding('Adonis/Lucid/Database') class Post extends BaseModel { public title: string public slug: string } Post.boot() Post.$addColumn('title', {}) Post.$addColumn('slug', {}) const dbIncrement = new DbIncrementStrategy(Database, { strategy: 'dbIncrement', fields: ['title'], separator: '_', }) const uniqueSlug = await dbIncrement.makeSlugUnique(Post, 'slug', 'hello_world') assert.equal(uniqueSlug, 'hello_world') }) test('add counter to existing duplicate slug', async (assert) => { const { BaseModel } = app.container.resolveBinding('Adonis/Lucid/Orm') const Database = app.container.resolveBinding('Adonis/Lucid/Database') class Post extends BaseModel { public title: string public slug: string } Post.boot() Post.$addColumn('title', {}) Post.$addColumn('slug', {}) await Post.createMany([ { title: 'Hello world', slug: 'hello_world', }, { title: 'Hello world', slug: 'hello_10_world', }, { title: 'Hello world', slug: 'hello10world', }, ]) const dbIncrement = new DbIncrementStrategy(Database, { strategy: 'dbIncrement', fields: ['title'], separator: '_', }) const uniqueSlug = await dbIncrement.makeSlugUnique(Post, 'slug', 'hello_world') assert.equal(uniqueSlug, 'hello_world_1') }) test('perform case insensitive search', async (assert) => { const { BaseModel } = app.container.resolveBinding('Adonis/Lucid/Orm') const Database = app.container.resolveBinding('Adonis/Lucid/Database') class Post extends BaseModel { public title: string public slug: string } Post.boot() Post.$addColumn('title', {}) Post.$addColumn('slug', {}) await Post.createMany([ { title: 'Hello world', slug: 'heLlo_World', }, { title: 'Hello world', slug: 'hello_10_world', }, { title: 'Hello world', slug: 'hello10world', }, ]) const dbIncrement = new DbIncrementStrategy(Database, { strategy: 'dbIncrement', fields: ['title'], separator: '_', }) const uniqueSlug = await dbIncrement.makeSlugUnique(Post, 'slug', 'hello_world') assert.equal(uniqueSlug, 'hello_world_1') }) test('ignore in between numeric values when generating counter', async (assert) => { const { BaseModel } = app.container.resolveBinding('Adonis/Lucid/Orm') const Database = app.container.resolveBinding('Adonis/Lucid/Database') class Post extends BaseModel { public title: string public slug: string } Post.boot() Post.$addColumn('title', {}) Post.$addColumn('slug', {}) await Post.createMany([ { title: 'Hello world', slug: 'post_hello_world', }, { title: 'Hello world', slug: 'post_11am_hello_world11', }, { title: 'Hello world', slug: 'post_11am_hello_world', }, ]) const dbIncrement = new DbIncrementStrategy(Database, { strategy: 'dbIncrement', fields: ['title'], separator: '_', }) const uniqueSlug = await dbIncrement.makeSlugUnique(Post, 'slug', 'post_11am_hello_world') assert.equal(uniqueSlug, 'post_11am_hello_world_1') }) test('generate unique slug when counter was manually tweaked', async (assert) => { const { BaseModel } = app.container.resolveBinding('Adonis/Lucid/Orm') const Database = app.container.resolveBinding('Adonis/Lucid/Database') class Post extends BaseModel { public title: string public slug: string } Post.boot() Post.$addColumn('title', {}) Post.$addColumn('slug', {}) await Post.createMany([ { title: 'Hello world', slug: 'hello_world', }, { title: 'Hello world 1', slug: 'hello_world_1', }, { title: 'Hello world 4', slug: 'hello_world_4', }, ]) const dbIncrement = new DbIncrementStrategy(Database, { strategy: 'dbIncrement', fields: ['title'], separator: '_', }) const uniqueSlug = await dbIncrement.makeSlugUnique(Post, 'slug', 'hello_world') assert.equal(uniqueSlug, 'hello_world_5') }) })
the_stack
import {WorkflowStepInputModel} from "cwlts/models/generic"; import {StepModel} from "cwlts/models/generic/StepModel"; import {WorkflowInputParameterModel} from "cwlts/models/generic/WorkflowInputParameterModel"; import {WorkflowModel} from "cwlts/models/generic/WorkflowModel"; import {WorkflowOutputParameterModel} from "cwlts/models/generic/WorkflowOutputParameterModel"; import {SVGPlugin} from "../plugins/plugin"; import {DomEvents} from "../utils/dom-events"; import {EventHub} from "../utils/event-hub"; import {Connectable} from "./connectable"; import {Edge as GraphEdge} from "./edge"; import {GraphNode} from "./graph-node"; import {StepNode} from "./step-node"; import {TemplateParser} from "./template-parser"; import {WorkflowStepOutputModel} from "cwlts/models"; /** * @FIXME validation states of old and newly created edges */ export class Workflow { readonly eventHub: EventHub; readonly svgID = this.makeID(); minScale = 0.2; maxScale = 2; domEvents: DomEvents; svgRoot: SVGSVGElement; workflow: SVGGElement; model: WorkflowModel; editingEnabled = true; /** Scale of labels, they are different than scale of other elements in the workflow */ labelScale = 1; private workflowBoundingClientRect; private plugins: SVGPlugin[] = []; private disposers: Function[] = []; private pendingFirstDraw = true; /** Stored in order to ensure that once destroyed graph cannot be reused again */ private isDestroyed = false; constructor(parameters: { svgRoot: SVGSVGElement, model: WorkflowModel, plugins?: SVGPlugin[], editingEnabled?: boolean }) { this.svgRoot = parameters.svgRoot; this.plugins = parameters.plugins || []; this.domEvents = new DomEvents(this.svgRoot as any); this.model = parameters.model; this.editingEnabled = parameters.editingEnabled !== false; // default to true if undefined this.svgRoot.classList.add(this.svgID); this.svgRoot.innerHTML = ` <rect x="0" y="0" width="100%" height="100%" class="pan-handle" transform="matrix(1,0,0,1,0,0)"></rect> <g class="workflow" transform="matrix(1,0,0,1,0,0)"></g> `; this.workflow = this.svgRoot.querySelector(".workflow") as any; this.invokePlugins("registerWorkflow", this); this.eventHub = new EventHub([ "connection.create", "app.create.step", "app.create.input", "app.create.output", "beforeChange", "afterChange", "afterRender", "selectionChange" ]); this.hookPlugins(); this.draw(parameters.model); this.eventHub.on("afterRender", () => this.invokePlugins("afterRender")); } /** Current scale of the document */ private _scale = 1; get scale() { return this._scale; } // noinspection JSUnusedGlobalSymbols set scale(scale: number) { this.workflowBoundingClientRect = this.svgRoot.getBoundingClientRect(); const x = (this.workflowBoundingClientRect.right + this.workflowBoundingClientRect.left) / 2; const y = (this.workflowBoundingClientRect.top + this.workflowBoundingClientRect.bottom) / 2; this.scaleAtPoint(scale, x, y); } static canDrawIn(element: SVGElement): boolean { return element.getBoundingClientRect().width !== 0; } static makeConnectionPath(x1, y1, x2, y2, forceDirection: "right" | "left" | string = "right"): string { if (!forceDirection) { return `M ${x1} ${y1} C ${(x1 + x2) / 2} ${y1} ${(x1 + x2) / 2} ${y2} ${x2} ${y2}`; } else if (forceDirection === "right") { const outDir = x1 + Math.abs(x1 - x2) / 2; const inDir = x2 - Math.abs(x1 - x2) / 2; return `M ${x1} ${y1} C ${outDir} ${y1} ${inDir} ${y2} ${x2} ${y2}`; } else if (forceDirection === "left") { const outDir = x1 - Math.abs(x1 - x2) / 2; const inDir = x2 + Math.abs(x1 - x2) / 2; return `M ${x1} ${y1} C ${outDir} ${y1} ${inDir} ${y2} ${x2} ${y2}`; } } draw(model: WorkflowModel = this.model) { this.assertNotDestroyed("draw"); // We will need to restore the transformations when we redraw the model, so save the current state const oldTransform = this.workflow.getAttribute("transform"); const modelChanged = this.model !== model; if (modelChanged || this.pendingFirstDraw) { this.pendingFirstDraw = false; this.model = model; const stepChangeDisposer = this.model.on("step.change", this.onStepChange.bind(this)); const stepCreateDisposer = this.model.on("step.create", this.onStepCreate.bind(this)); const stepRemoveDisposer = this.model.on("step.remove", this.onStepRemove.bind(this)); const inputCreateDisposer = this.model.on("input.create", this.onInputCreate.bind(this)); const inputRemoveDisposer = this.model.on("input.remove", this.onInputRemove.bind(this)); const outputCreateDisposer = this.model.on("output.create", this.onOutputCreate.bind(this)); const outputRemoveDisposer = this.model.on("output.remove", this.onOutputRemove.bind(this)); const stepInPortShowDisposer = this.model.on("step.inPort.show", this.onInputPortShow.bind(this)); const stepInPortHideDisposer = this.model.on("step.inPort.hide", this.onInputPortHide.bind(this)); const connectionCreateDisposer = this.model.on("connection.create", this.onConnectionCreate.bind(this)); const connectionRemoveDisposer = this.model.on("connection.remove", this.onConnectionRemove.bind(this)); const stepOutPortCreateDisposer = this.model.on("step.outPort.create", this.onOutputPortCreate.bind(this)); const stepOutPortRemoveDisposer = this.model.on("step.outPort.remove", this.onOutputPortRemove.bind(this)); this.disposers.push(() => { stepChangeDisposer.dispose(); stepCreateDisposer.dispose(); stepRemoveDisposer.dispose(); inputCreateDisposer.dispose(); inputRemoveDisposer.dispose(); outputCreateDisposer.dispose(); outputRemoveDisposer.dispose(); stepInPortShowDisposer.dispose(); stepInPortHideDisposer.dispose(); connectionCreateDisposer.dispose(); connectionRemoveDisposer.dispose(); stepOutPortCreateDisposer.dispose(); stepOutPortRemoveDisposer.dispose(); }); this.invokePlugins("afterModelChange"); } this.clearCanvas(); const nodes = [ ...this.model.steps, ...this.model.inputs, ...this.model.outputs ].filter(n => n.isVisible); /** * If there is a missing sbg:x or sbg:y property on any node model, * graph should be arranged to avoid random placement. */ let arrangeNecessary = false; let nodeTemplate = ""; for (let node of nodes) { const patched = GraphNode.patchModelPorts(node); const missingX = isNaN(parseInt(patched.customProps["sbg:x"])); const missingY = isNaN(parseInt(patched.customProps["sbg:y"])); if (missingX || missingY) { arrangeNecessary = true; } nodeTemplate += GraphNode.makeTemplate(patched); } this.workflow.innerHTML += nodeTemplate; this.redrawEdges(); Array.from(this.workflow.querySelectorAll(".node")).forEach(e => { this.workflow.appendChild(e); }); this.addEventListeners(); this.workflow.setAttribute("transform", oldTransform); this.scaleAtPoint(this.scale); this.invokePlugins("afterRender"); } findParent(el: Element, parentClass = "node"): SVGGElement | undefined { let parentNode = el as Element; while (parentNode) { if (parentNode.classList.contains(parentClass)) { return parentNode as SVGGElement; } parentNode = parentNode.parentElement; } } /** * Retrieves a plugin instance * @param {{new(...args: any[]) => T}} plugin * @returns {T} */ getPlugin<T extends SVGPlugin>(plugin: { new(...args: any[]): T }): T { return this.plugins.find(p => p instanceof plugin) as T; } on(event: string, handler) { this.eventHub.on(event, handler); } off(event, handler) { this.eventHub.off(event, handler); } /** * Scales the workflow to fit the available viewport */ fitToViewport(ignoreScaleLimits = false): void { this.scaleAtPoint(1); Object.assign(this.workflow.transform.baseVal.getItem(0).matrix, { e: 0, f: 0 }); let clientBounds = this.svgRoot.getBoundingClientRect(); let wfBounds = this.workflow.getBoundingClientRect(); const padding = 100; if (clientBounds.width === 0 || clientBounds.height === 0) { throw new Error("Cannot fit workflow to the area that has no visible viewport."); } const verticalScale = (wfBounds.height) / (clientBounds.height - padding); const horizontalScale = (wfBounds.width) / (clientBounds.width - padding); const scaleFactor = Math.max(verticalScale, horizontalScale); // Cap the upscaling to 1, we don't want to zoom in workflows that would fit anyway let newScale = Math.min(this.scale / scaleFactor, 1); if (!ignoreScaleLimits) { newScale = Math.max(newScale, this.minScale); } this.scaleAtPoint(newScale); const scaledWFBounds = this.workflow.getBoundingClientRect(); const moveY = clientBounds.top - scaledWFBounds.top + Math.abs(clientBounds.height - scaledWFBounds.height) / 2; const moveX = clientBounds.left - scaledWFBounds.left + Math.abs(clientBounds.width - scaledWFBounds.width) / 2; const matrix = this.workflow.transform.baseVal.getItem(0).matrix; matrix.e += moveX; matrix.f += moveY; } redrawEdges() { const highlightedEdges = new Set(); Array.from(this.workflow.querySelectorAll(".edge")).forEach((el) => { if (el.classList.contains("highlighted")) { const edgeID = el.attributes["data-source-connection"].value + el.attributes["data-destination-connection"].value; highlightedEdges.add(edgeID); } el.remove(); }); const edgesTpl = this.model.connections .map(c => { const edgeId = c.source.id + c.destination.id; const edgeStates = highlightedEdges.has(edgeId) ? "highlighted" : ""; return GraphEdge.makeTemplate(c, this.workflow, edgeStates); }) .reduce((acc, tpl) => acc + tpl, ""); this.workflow.innerHTML = edgesTpl + this.workflow.innerHTML; } /** * Scale the workflow by the scaleCoefficient (not compounded) over given coordinates */ scaleAtPoint(scale = 1, x = 0, y = 0): void { this._scale = scale; this.labelScale = 1 + (1 - this._scale) / (this._scale * 2); const transform = this.workflow.transform.baseVal; const matrix: SVGMatrix = transform.getItem(0).matrix; const coords = this.transformScreenCTMtoCanvas(x, y); matrix.e += matrix.a * coords.x; matrix.f += matrix.a * coords.y; matrix.a = matrix.d = scale; matrix.e -= scale * coords.x; matrix.f -= scale * coords.y; const nodeLabels = this.workflow.querySelectorAll(".node .label") as NodeListOf<SVGPathElement>; for (let el of nodeLabels) { const matrix = el.transform.baseVal.getItem(0).matrix; Object.assign(matrix, { a: this.labelScale, d: this.labelScale }); } } transformScreenCTMtoCanvas(x, y) { const svg = this.svgRoot; const ctm = this.workflow.getScreenCTM(); const point = svg.createSVGPoint(); point.x = x; point.y = y; const t = point.matrixTransform(ctm.inverse()); return { x: t.x, y: t.y }; } enableEditing(enabled: boolean): void { this.invokePlugins("onEditableStateChange", enabled); this.editingEnabled = enabled; } // noinspection JSUnusedGlobalSymbols destroy() { this.svgRoot.classList.remove(this.svgID); this.clearCanvas(); this.eventHub.empty(); this.invokePlugins("destroy"); for (const dispose of this.disposers) { dispose(); } this.isDestroyed = true; } resetTransform() { this.workflow.setAttribute("transform", "matrix(1,0,0,1,0,0)"); this.scaleAtPoint(); } private assertNotDestroyed(method: string) { if (this.isDestroyed) { throw new Error("Cannot call the " + method + " method on a destroyed graph. " + "Destroying this object removes DOM listeners, " + "and reusing it would result in unexpected things not working. " + "Instead, you can just call the “draw” method with a different model, " + "or create a new Workflow object."); } } private addEventListeners(): void { /** * Attach canvas panning */ { let pane: SVGGElement; let x; let y; let matrix: SVGMatrix; this.domEvents.drag(".pan-handle", (dx, dy) => { matrix.e = x + dx; matrix.f = y + dy; }, (ev, el, root) => { pane = root.querySelector(".workflow") as SVGGElement; matrix = pane.transform.baseVal.getItem(0).matrix; x = matrix.e; y = matrix.f; }, () => { pane = undefined; matrix = undefined; }); } } private clearCanvas() { this.domEvents.detachAll(); this.workflow.innerHTML = ""; this.workflow.setAttribute("transform", "matrix(1,0,0,1,0,0)"); this.workflow.setAttribute("class", "workflow"); } private hookPlugins() { this.plugins.forEach(plugin => { plugin.registerOnBeforeChange(event => { this.eventHub.emit("beforeChange", event); }); plugin.registerOnAfterChange(event => { this.eventHub.emit("afterChange", event); }); plugin.registerOnAfterRender(event => { this.eventHub.emit("afterRender", event); }) }); } private invokePlugins(methodName: keyof SVGPlugin, ...args: any[]) { this.plugins.forEach(plugin => { if (typeof plugin[methodName] === "function") { (plugin[methodName] as Function)(...args); } }) } /** * Listener for “connection.create” event on model that renders new edges on canvas */ private onConnectionCreate(source: Connectable, destination: Connectable): void { if (!source.isVisible || !destination.isVisible) { return; } const sourceID = source.connectionId; const destinationID = destination.connectionId; GraphEdge.spawnBetweenConnectionIDs(this.workflow, sourceID, destinationID); } /** * Listener for "connection.remove" event on the model that disconnects nodes */ private onConnectionRemove(source: Connectable, destination: Connectable): void { if (!source.isVisible || !destination.isVisible) { return; } const sourceID = source.connectionId; const destinationID = destination.connectionId; const edge = this.svgRoot.querySelector(`.edge[data-source-connection="${sourceID}"][data-destination-connection="${destinationID}"]`); edge.remove(); } /** * Listener for “input.create” event on model that renders workflow inputs */ private onInputCreate(input: WorkflowInputParameterModel): void { if (!input.isVisible) { return; } const patched = GraphNode.patchModelPorts(input); const graphTemplate = GraphNode.makeTemplate(patched, this.labelScale); const el = TemplateParser.parse(graphTemplate); this.workflow.appendChild(el); } /** * Listener for “output.create” event on model that renders workflow outputs */ private onOutputCreate(output: WorkflowOutputParameterModel): void { if (!output.isVisible) { return; } const patched = GraphNode.patchModelPorts(output); const graphTemplate = GraphNode.makeTemplate(patched, this.labelScale); const el = TemplateParser.parse(graphTemplate); this.workflow.appendChild(el); } private onStepCreate(step: StepModel) { // if the step doesn't have x & y coordinates, check if they are in the run property if (!step.customProps["sbg:x"] && step.run.customProps && step.run.customProps["sbg:x"]) { Object.assign(step.customProps, { "sbg:x": step.run.customProps["sbg:x"], "sbg:y": step.run.customProps["sbg:y"] }); // remove them from the run property once finished delete step.run.customProps["sbg:x"]; delete step.run.customProps["sbg:y"]; } const template = GraphNode.makeTemplate(step, this.labelScale); const element = TemplateParser.parse(template); this.workflow.appendChild(element); } private onStepChange(change: StepModel) { const title = this.workflow.querySelector(`.step[data-id="${change.connectionId}"] .title`) as SVGTextElement; if (title) { title.textContent = change.label; } } private onInputPortShow(input: WorkflowStepInputModel) { const stepEl = this.svgRoot.querySelector(`.step[data-connection-id="${input.parentStep.connectionId}"]`) as SVGElement; new StepNode(stepEl, input.parentStep).update(); } private onInputPortHide(input: WorkflowStepInputModel) { const stepEl = this.svgRoot.querySelector(`.step[data-connection-id="${input.parentStep.connectionId}"]`) as SVGElement; new StepNode(stepEl, input.parentStep).update(); } private onOutputPortCreate(output: WorkflowStepOutputModel) { const stepEl = this.svgRoot.querySelector(`.step[data-connection-id="${output.parentStep.connectionId}"]`) as SVGElement; new StepNode(stepEl, output.parentStep).update(); } private onOutputPortRemove(output: WorkflowStepOutputModel) { const stepEl = this.svgRoot.querySelector(`.step[data-connection-id="${output.parentStep.connectionId}"]`) as SVGElement; new StepNode(stepEl, output.parentStep).update(); } /** * Listener for "step.remove" event on model which removes steps */ private onStepRemove(step: StepModel) { const stepEl = this.svgRoot.querySelector(`.step[data-connection-id="${step.connectionId}"]`) as SVGElement; stepEl.remove(); } /** * Listener for "input.remove" event on model which removes inputs */ private onInputRemove(input: WorkflowInputParameterModel) { if (!input.isVisible) return; const inputEl = this.svgRoot.querySelector(`.node.input[data-connection-id="${input.connectionId}"]`); inputEl.remove(); } /** * Listener for "output.remove" event on model which removes outputs */ private onOutputRemove(output: WorkflowOutputParameterModel) { if (!output.isVisible) return; const outputEl = this.svgRoot.querySelector(`.node.output[data-connection-id="${output.connectionId}"]`); outputEl.remove(); } private makeID(length = 6) { let output = ""; const charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; for (let i = 0; i < length; i++) { output += charset.charAt(Math.floor(Math.random() * charset.length)); } return output; } }
the_stack
declare namespace Linqer { /** * wrapper class over iterable instances that exposes the methods usually found in .NET LINQ * * @export * @class Enumerable * @implements {Iterable<any>} * @implements {IUsesQuickSort} */ export class Enumerable implements Iterable<any>, IUsesQuickSort { _src: IterableType; _generator: () => Iterator<any>; _useQuickSort: boolean; _canSeek: boolean; _count: null | (() => number); _tryGetAt: null | ((index: number) => { value: any; } | null); _wasIterated: boolean; /** * sort an array in place using the Enumerable sort algorithm (Quicksort) * * @static * @memberof Enumerable */ static sort: (arr: any[], comparer?: IComparer) => any[]; /** * You should never use this. Instead use Enumerable.from * @param {IterableType} src * @memberof Enumerable */ constructor(src: IterableType); /** * Wraps an iterable item into an Enumerable if it's not already one * * @static * @param {IterableType} iterable * @returns {Enumerable} * @memberof Enumerable */ static from(iterable: IterableType): Enumerable; /** * the Enumerable instance exposes the same iterator as the wrapped iterable or generator function * * @returns {Iterator<any>} * @memberof Enumerable */ [Symbol.iterator](): Iterator<any>; /** * returns an empty Enumerable * * @static * @returns {Enumerable} * @memberof Enumerable */ static empty(): Enumerable; /** * generates a sequence of integer numbers within a specified range. * * @static * @param {number} start * @param {number} count * @returns {Enumerable} * @memberof Enumerable */ static range(start: number, count: number): Enumerable; /** * Generates a sequence that contains one repeated value. * * @static * @param {*} item * @param {number} count * @returns {Enumerable} * @memberof Enumerable */ static repeat(item: any, count: number): Enumerable; /** * Same value as count(), but will throw an Error if enumerable is not seekable and has to be iterated to get the length */ get length(): number; /** * Concatenates two sequences by appending iterable to the existing one. * * @param {IterableType} iterable * @returns {Enumerable} * @memberof Enumerable */ concat(iterable: IterableType): Enumerable; /** * Returns distinct elements from a sequence. * WARNING: using a comparer makes this slower. Not specifying it uses a Set to determine distinctiveness. * * @param {IEqualityComparer} [equalityComparer=EqualityComparer.default] * @returns {Enumerable} * @memberof Enumerable */ distinct(equalityComparer?: IEqualityComparer): Enumerable; /** * Returns the element at a specified index in a sequence. * * @param {number} index * @returns {*} * @memberof Enumerable */ elementAt(index: number): any; /** * Returns the element at a specified index in a sequence or undefined if the index is out of range. * * @param {number} index * @returns {(any | undefined)} * @memberof Enumerable */ elementAtOrDefault(index: number): any | undefined; /** * Returns the first element of a sequence. * * @returns {*} * @memberof Enumerable */ first(): any; /** * Returns the first element of a sequence, or a default value if no element is found. * * @returns {(any | undefined)} * @memberof Enumerable */ firstOrDefault(): any | undefined; /** * Returns the last element of a sequence. * * @returns {*} * @memberof Enumerable */ last(): any; /** * Returns the last element of a sequence, or undefined if no element is found. * * @returns {(any | undefined)} * @memberof Enumerable */ lastOrDefault(): any | undefined; /** * Returns the count, minimum and maximum value in a sequence of values. * A custom function can be used to establish order (the result 0 means equal, 1 means larger, -1 means smaller) * * @param {IComparer} [comparer] * @returns {{ count: number, min: any, max: any }} * @memberof Enumerable */ stats(comparer?: IComparer): { count: number; min: any; max: any; }; /** * Returns the minimum value in a sequence of values. * A custom function can be used to establish order (the result 0 means equal, 1 means larger, -1 means smaller) * * @param {IComparer} [comparer] * @returns {*} * @memberof Enumerable */ min(comparer?: IComparer): any; /** * Returns the maximum value in a sequence of values. * A custom function can be used to establish order (the result 0 means equal, 1 means larger, -1 means smaller) * * @param {IComparer} [comparer] * @returns {*} * @memberof Enumerable */ max(comparer?: IComparer): any; /** * Projects each element of a sequence into a new form. * * @param {ISelector} selector * @returns {Enumerable} * @memberof Enumerable */ select(selector: ISelector): Enumerable; /** * Bypasses a specified number of elements in a sequence and then returns the remaining elements. * * @param {number} nr * @returns {Enumerable} * @memberof Enumerable */ skip(nr: number): Enumerable; /** * Takes start elements, ignores howmany elements, continues with the new items and continues with the original enumerable * Equivalent to the value of an array after performing splice on it with the same parameters * @param start * @param howmany * @param items * @returns splice */ splice(start: number, howmany: number, ...newItems: any[]): Enumerable; /** * Computes the sum of a sequence of numeric values. * * @returns {(number | undefined)} * @memberof Enumerable */ sum(): number | undefined; /** * Computes the sum and count of a sequence of numeric values. * * @returns {{ sum: number, count: number }} * @memberof Enumerable */ sumAndCount(): { sum: number; count: number; }; /** * Returns a specified number of contiguous elements from the start of a sequence. * * @param {number} nr * @returns {Enumerable} * @memberof Enumerable */ take(nr: number): Enumerable; /** * creates an array from an Enumerable * * @returns {any[]} * @memberof Enumerable */ toArray(): any[]; /** * similar to toArray, but returns a seekable Enumerable (itself if already seekable) that can do count and elementAt without iterating * * @returns {Enumerable} * @memberof Enumerable */ toList(): Enumerable; /** * Filters a sequence of values based on a predicate. * * @param {IFilter} condition * @returns {Enumerable} * @memberof Enumerable */ where(condition: IFilter): Enumerable; } export function _ensureIterable(src: IterableType): void; export function _ensureFunction(f: Function): void; export function _toArray(iterable: IterableType): any[]; export function _ensureInternalCount(enumerable: Enumerable): void; export function _ensureInternalTryGetAt(enumerable: Enumerable): void; /** * an extended iterable type that also supports generator functions */ export type IterableType = Iterable<any> | (() => Iterator<any>) | Enumerable; /** * A comparer function to be used in sorting */ export type IComparer = (item1: any, item2: any) => -1 | 0 | 1; /** * A selector function to be used in mapping */ export type ISelector<T = any> = (item: any, index?: number) => T; /** * A filter function */ export type IFilter = ISelector<boolean>; /** * The default comparer function between two items * @param item1 * @param item2 */ export const _defaultComparer: IComparer; /** * Interface for an equality comparer */ export type IEqualityComparer = (item1: any, item2: any) => boolean; /** * Predefined equality comparers * default is the equivalent of == * exact is the equivalent of === */ export const EqualityComparer: { default: (item1: any, item2: any) => boolean; exact: (item1: any, item2: any) => boolean; }; interface IUsesQuickSort { _useQuickSort: boolean; } export {}; } declare namespace Linqer { interface Enumerable extends Iterable<any> { /** * Applies an accumulator function over a sequence. * The specified seed value is used as the initial accumulator value, and the specified function is used to select the result value. * * @param {*} accumulator * @param {(acc: any, item: any) => any} aggregator * @returns {*} * @memberof Enumerable */ aggregate(accumulator: any, aggregator: (acc: any, item: any) => any): any; /** * Determines whether all elements of a sequence satisfy a condition. * @param condition * @returns true if all */ all(condition: IFilter): boolean; /** * Determines whether any element of a sequence exists or satisfies a condition. * * @param {IFilter} condition * @returns {boolean} * @memberof Enumerable */ any(condition: IFilter): boolean; /** * Appends a value to the end of the sequence. * * @param {*} item * @returns {Enumerable} * @memberof Enumerable */ append(item: any): Enumerable; /** * Computes the average of a sequence of numeric values. * * @returns {(number | undefined)} * @memberof Enumerable */ average(): number | undefined; /** * Returns itself * * @returns {Enumerable} * @memberof Enumerable */ asEnumerable(): Enumerable; /** * Checks the elements of a sequence based on their type * If type is a string, it will check based on typeof, else it will use instanceof. * Throws if types are different. * @param {(string | Function)} type * @returns {Enumerable} * @memberof Enumerable */ cast(type: string | Function): Enumerable; /** * Determines whether a sequence contains a specified element. * A custom function can be used to determine equality between elements. * * @param {*} item * @param {IEqualityComparer} equalityComparer * @returns {boolean} * @memberof Enumerable */ contains(item: any, equalityComparer: IEqualityComparer): boolean; defaultIfEmpty(): never; /** * Produces the set difference of two sequences * WARNING: using the comparer is slower * * @param {IterableType} iterable * @param {IEqualityComparer} equalityComparer * @returns {Enumerable} * @memberof Enumerable */ except(iterable: IterableType, equalityComparer: IEqualityComparer): Enumerable; /** * Produces the set intersection of two sequences. * WARNING: using a comparer is slower * * @param {IterableType} iterable * @param {IEqualityComparer} equalityComparer * @returns {Enumerable} * @memberof Enumerable */ intersect(iterable: IterableType, equalityComparer: IEqualityComparer): Enumerable; /** * Same as count * * @returns {number} * @memberof Enumerable */ longCount(): number; /** * Filters the elements of a sequence based on their type * If type is a string, it will filter based on typeof, else it will use instanceof * * @param {(string | Function)} type * @returns {Enumerable} * @memberof Enumerable */ ofType(type: string | Function): Enumerable; /** * Adds a value to the beginning of the sequence. * * @param {*} item * @returns {Enumerable} * @memberof Enumerable */ prepend(item: any): Enumerable; /** * Inverts the order of the elements in a sequence. * * @returns {Enumerable} * @memberof Enumerable */ reverse(): Enumerable; /** * Projects each element of a sequence to an iterable and flattens the resulting sequences into one sequence. * * @param {ISelector<IterableType>} selector * @returns {Enumerable} * @memberof Enumerable */ selectMany(selector: ISelector<IterableType>): Enumerable; /** * Determines whether two sequences are equal and in the same order according to an optional equality comparer. * * @param {IterableType} iterable * @param {IEqualityComparer} equalityComparer * @returns {boolean} * @memberof Enumerable */ sequenceEqual(iterable: IterableType, equalityComparer: IEqualityComparer): boolean; /** * Returns the single element of a sequence and throws if it doesn't have exactly one * * @returns {*} * @memberof Enumerable */ single(): any; /** * Returns the single element of a sequence or undefined if none found. It throws if the sequence contains multiple items. * * @returns {(any | undefined)} * @memberof Enumerable */ singleOrDefault(): any | undefined; /** * Returns a new enumerable collection that contains the elements from source with the last nr elements of the source collection omitted. * * @param {number} nr * @returns {Enumerable} * @memberof Enumerable */ skipLast(nr: number): Enumerable; /** * Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements. * * @param {IFilter} condition * @returns {Enumerable} * @memberof Enumerable */ skipWhile(condition: IFilter): Enumerable; /** * Selects the elements starting at the given start argument, and ends at, but does not include, the given end argument. * @param start * @param end * @returns slice */ slice(start: number | undefined, end: number | undefined): Enumerable; /** * Returns a new enumerable collection that contains the last nr elements from source. * * @param {number} nr * @returns {Enumerable} * @memberof Enumerable */ takeLast(nr: number): Enumerable; /** * Returns elements from a sequence as long as a specified condition is true, and then skips the remaining elements. * * @param {IFilter} condition * @returns {Enumerable} * @memberof Enumerable */ takeWhile(condition: IFilter): Enumerable; toDictionary(): never; /** * creates a Map from an Enumerable * * @param {ISelector} keySelector * @param {ISelector} valueSelector * @returns {Map<any, any>} * @memberof Enumerable */ toMap(keySelector: ISelector, valueSelector: ISelector): Map<any, any>; /** * creates an object from an Enumerable * * @param {ISelector} keySelector * @param {ISelector} valueSelector * @returns {{ [key: string]: any }} * @memberof Enumerable */ toObject(keySelector: ISelector, valueSelector: ISelector): { [key: string]: any; }; toHashSet(): never; /** * creates a Set from an enumerable * * @returns {Set<any>} * @memberof Enumerable */ toSet(): Set<any>; /** * Produces the set union of two sequences. * * @param {IterableType} iterable * @param {IEqualityComparer} equalityComparer * @returns {Enumerable} * @memberof Enumerable */ union(iterable: IterableType, equalityComparer: IEqualityComparer): Enumerable; /** * Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results. * * @param {IterableType} iterable * @param {(item1: any, item2: any, index: number) => any} zipper * @returns {*} * @memberof Enumerable */ zip(iterable: IterableType, zipper: (item1: any, item2: any, index: number) => any): any; } } declare namespace Linqer { interface Enumerable extends Iterable<any> { /** * Groups the elements of a sequence. * * @param {ISelector} keySelector * @returns {Enumerable} * @memberof Enumerable */ groupBy(keySelector: ISelector): Enumerable; /** * Correlates the elements of two sequences based on key equality and groups the results. A specified equalityComparer is used to compare keys. * WARNING: using the equality comparer will be slower * * @param {IterableType} iterable * @param {ISelector} innerKeySelector * @param {ISelector} outerKeySelector * @param {(item1: any, item2: any) => any} resultSelector * @param {IEqualityComparer} equalityComparer * @returns {Enumerable} * @memberof Enumerable */ groupJoin(iterable: IterableType, innerKeySelector: ISelector, outerKeySelector: ISelector, resultSelector: (item1: any, item2: any) => any, equalityComparer: IEqualityComparer): Enumerable; /** * Correlates the elements of two sequences based on matching keys. * WARNING: using the equality comparer will be slower * * @param {IterableType} iterable * @param {ISelector} innerKeySelector * @param {ISelector} outerKeySelector * @param {(item1: any, item2: any) => any} resultSelector * @param {IEqualityComparer} equalityComparer * @returns {Enumerable} * @memberof Enumerable */ join(iterable: IterableType, innerKeySelector: ISelector, outerKeySelector: ISelector, resultSelector: (item1: any, item2: any) => any, equalityComparer: IEqualityComparer): Enumerable; toLookup(): never; } /** * An Enumerable that also exposes a group key * * @export * @class GroupEnumerable * @extends {Enumerable} */ class GroupEnumerable extends Enumerable { key: string; constructor(iterable: IterableType, key: string); } } declare namespace Linqer { export interface Enumerable extends Iterable<any> { /** * Sorts the elements of a sequence in ascending order. * * @param {ISelector} keySelector * @returns {OrderedEnumerable} * @memberof Enumerable */ orderBy(keySelector: ISelector): OrderedEnumerable; /** * Sorts the elements of a sequence in descending order. * * @param {ISelector} keySelector * @returns {OrderedEnumerable} * @memberof Enumerable */ orderByDescending(keySelector: ISelector): OrderedEnumerable; /** * use QuickSort for ordering (default). Recommended when take, skip, takeLast, skipLast are used after orderBy * * @returns {Enumerable} * @memberof Enumerable */ useQuickSort(): Enumerable; /** * use the default browser sort implementation for ordering at all times * * @returns {Enumerable} * @memberof Enumerable */ useBrowserSort(): Enumerable; } enum RestrictionType { skip = 0, skipLast = 1, take = 2, takeLast = 3 } /** * An Enumerable yielding ordered items * * @export * @class OrderedEnumerable * @extends {Enumerable} */ export class OrderedEnumerable extends Enumerable { _keySelectors: { keySelector: ISelector; ascending: boolean; }[]; _restrictions: { type: RestrictionType; nr: number; }[]; /** *Creates an instance of OrderedEnumerable. * @param {IterableType} src * @param {ISelector} [keySelector] * @param {boolean} [ascending=true] * @memberof OrderedEnumerable */ constructor(src: IterableType, keySelector?: ISelector, ascending?: boolean); private getSortedArray; private generateSortFunc; private getStartAndEndIndexes; /** * Performs a subsequent ordering of the elements in a sequence in ascending order. * * @param {ISelector} keySelector * @returns {OrderedEnumerable} * @memberof OrderedEnumerable */ thenBy(keySelector: ISelector): OrderedEnumerable; /** * Performs a subsequent ordering of the elements in a sequence in descending order. * * @param {ISelector} keySelector * @returns {OrderedEnumerable} * @memberof OrderedEnumerable */ thenByDescending(keySelector: ISelector): OrderedEnumerable; /** * Deferred and optimized implementation of take * * @param {number} nr * @returns {OrderedEnumerable} * @memberof OrderedEnumerable */ take(nr: number): OrderedEnumerable; /** * Deferred and optimized implementation of takeLast * * @param {number} nr * @returns {OrderedEnumerable} * @memberof OrderedEnumerable */ takeLast(nr: number): OrderedEnumerable; /** * Deferred and optimized implementation of skip * * @param {number} nr * @returns {OrderedEnumerable} * @memberof OrderedEnumerable */ skip(nr: number): OrderedEnumerable; /** * Deferred and optimized implementation of skipLast * * @param {number} nr * @returns {OrderedEnumerable} * @memberof OrderedEnumerable */ skipLast(nr: number): OrderedEnumerable; /** * An optimized implementation of toArray * * @returns {any[]} * @memberof OrderedEnumerable */ toArray(): any[]; /** * An optimized implementation of toMap * * @param {ISelector} keySelector * @param {ISelector} [valueSelector=x => x] * @returns {Map<any, any>} * @memberof OrderedEnumerable */ toMap(keySelector: ISelector, valueSelector?: ISelector): Map<any, any>; /** * An optimized implementation of toObject * * @param {ISelector} keySelector * @param {ISelector} [valueSelector=x => x] * @returns {{ [key: string]: any }} * @memberof OrderedEnumerable */ toObject(keySelector: ISelector, valueSelector?: ISelector): { [key: string]: any; }; /** * An optimized implementation of to Set * * @returns {Set<any>} * @memberof OrderedEnumerable */ toSet(): Set<any>; } export {}; } declare namespace Linqer { interface Enumerable extends Iterable<any> { /** * Returns a randomized sequence of items from an initial source * @returns shuffle */ shuffle(): Enumerable; /** * implements random reservoir sampling of k items, with the option to specify a maximum limit for the items * @param k * @param limit * @returns sample */ randomSample(k: number, limit: number): Enumerable; /** * Returns the count of the items in a sequence. Depending on the sequence type this iterates through it or not. * @returns count */ count(): number; /** * returns the distinct values based on a hashing function * * @param {ISelector} hashFunc * @returns {Enumerable} * @memberof Enumerable */ distinctByHash(hashFunc: ISelector): Enumerable; /** * returns the values that have different hashes from the items of the iterable provided * * @param {IterableType} iterable * @param {ISelector} hashFunc * @returns {Enumerable} * @memberof Enumerable */ exceptByHash(iterable: IterableType, hashFunc: ISelector): Enumerable; /** * returns the values that have the same hashes as items of the iterable provided * * @param {IterableType} iterable * @param {ISelector} hashFunc * @returns {Enumerable} * @memberof Enumerable */ intersectByHash(iterable: IterableType, hashFunc: ISelector): Enumerable; /** * returns the index of a value in an ordered enumerable or false if not found * WARNING: use the same comparer as the one used to order the enumerable. The algorithm assumes the enumerable is already sorted. * * @param {*} value * @param {IComparer} comparer * @returns {(number | boolean)} * @memberof Enumerable */ binarySearch(value: any, comparer: IComparer): number | boolean; /** * joins each item of the enumerable with previous items from the same enumerable * @param offset * @param zipper * @returns lag */ lag(offset: number, zipper: (item1: any, item2: any) => any): Enumerable; /** * joins each item of the enumerable with next items from the same enumerable * * @param {number} offset * @param {(item1: any, item2: any) => any} zipper * @returns {Enumerable} * @memberof Enumerable */ lead(offset: number, zipper: (item1: any, item2: any) => any): Enumerable; /** * returns an enumerable of at least minLength, padding the end with a value or the result of a function * * @param {number} minLength * @param {(any | ((index: number) => any))} filler * @returns {Enumerable} * @memberof Enumerable */ padEnd(minLength: number, filler: any | ((index: number) => any)): Enumerable; /** * returns an enumerable of at least minLength, padding the start with a value or the result of a function * if the enumerable cannot seek, then it will be iterated minLength time * * @param {number} minLength * @param {(any | ((index: number) => any))} filler * @returns {Enumerable} * @memberof Enumerable */ padStart(minLength: number, filler: any | ((index: number) => any)): Enumerable; } } export = Linqer;
the_stack
import { sleep } from '@test/utils' import { TreeSelect } from 'antd' import { mount } from 'enzyme' import { createBrowserHistory } from 'history' import axiosMock from 'jest-mock-axios' import _ from 'lodash' import React from 'react' import HtSelectTree from '~/components/Field/components/SelectTrees/index' import { HtSelectTreeProps, HtSelectTreeState, } from '~/components/Field/components/SelectTrees/interface' import { Field } from '~/components/Form/interface' import { Hetu } from '~/Hetu' const history = createBrowserHistory() const TreeNode = TreeSelect.TreeNode type SelectField = Partial<Field & HtSelectTreeProps> const local = { cityOptions: [ { title: '全城范围', value: 'all', searchable: false, selectable: true, disabled: false, }, { title: '北京', value: '110000', searchable: true, selectable: true, disabled: false, }, { title: '广州', value: '120000', searchable: true, selectable: true, disabled: true, }, ], } const field0: SelectField = { field: 'tree1', title: '树选择器-单选', type: 'SelectTrees', showSearch: true, treeCheckable: false, labelField: 'title', valueField: 'value', defaultValue: [], optionsSourceType: 'all', searchConfigs: [ { url: '/mock/api/tree/all', searchField: 'key', params: {}, transform: data => data, }, ], } const field1: SelectField = { field: 'tree2', title: '树选择器-多选', type: 'SelectTrees', showSearch: true, treeCheckable: true, labelField: 'title', valueField: 'value', optionsSourceType: 'all', searchConfigs: [ { url: '/mock/api/tree/all', searchField: 'key', }, ], } const field2: SelectField = { field: 'tree3', title: '单选回显', type: 'SelectTrees', showSearch: true, treeCheckable: false, labelField: 'title', valueField: 'value', optionsSourceType: 'dependencies', searchConfigs: [ { url: '/mock/api/tree/all', searchField: '', params: {}, }, ], placeholder: '请输入单选回显', tooltip: 'xxx', defaultValue: [ { title: 'sss', value: '123', }, ], required: false, disabled: false, showCheckedStrategy: 'SHOW_ALL', // @ts-ignore treeData: '<%:= cityOptions %>', } const field3: SelectField = { field: 'tree4', title: '异步加载可以保存父子关系', type: 'SelectTrees', showSearch: true, treeCheckable: true, labelField: 'title', valueField: 'value', optionsSourceType: 'async', searchConfigs: [ { url: '/mock/api/tree/1', searchField: 'key', params: {}, }, { url: '/mock/api/tree/2', searchField: 'key', params: {}, }, { url: '/mock/api/tree/3', searchField: '', params: {}, }, ], placeholder: '', tooltip: '', defaultValue: [ { title: '大区2', value: '110000>>>shiyebu1>>>daqu2', }, ], required: false, disabled: false, showCheckedStrategy: 'SHOW_PARENT', nodePath: true, splitTag: '>>>', } const elementConfig = { type: 'HtForm', props: { url: '/', buttons: [], fields: [field0, field1, field2, field3], }, children: [], } const wrapper = mount( <Hetu elementConfig={elementConfig} history={history} local={local} /> ) const WrapperSelect0 = wrapper .find<React.Component<HtSelectTreeProps, HtSelectTreeState>>(HtSelectTree) .at(0) const WrapperSelect1 = wrapper .find<React.Component<HtSelectTreeProps, HtSelectTreeState>>(HtSelectTree) .at(1) const WrapperSelect2 = wrapper .find<React.Component<HtSelectTreeProps, HtSelectTreeState>>(HtSelectTree) .at(2) const WrapperSelect3 = wrapper .find<React.Component<HtSelectTreeProps, HtSelectTreeState>>(HtSelectTree) .at(3) const WrapperSelect1Instance = WrapperSelect1.instance() const WrapperSelect2Instance = WrapperSelect2.instance() describe('正确的props', () => { test('defaultValue & value', () => { expect(WrapperSelect0.prop('value')).toEqual(field0.defaultValue) }) test('disabled', () => { expect(WrapperSelect0.prop('disabled')).toEqual(field0.disabled || false) }) test('showSearch', () => { expect(WrapperSelect0.prop('showSearch')).toEqual( field0.showSearch || false ) }) test('treeData', () => { expect(WrapperSelect0.prop('treeData')).toEqual(field0.treeData || []) }) test('searchConfigs', () => { expect(WrapperSelect1.prop('searchConfigs')).toEqual(field1.searchConfigs) }) test('treeCheckable', () => { expect(WrapperSelect1.prop('treeCheckable')).toEqual(field1.treeCheckable) }) test('optionsSourceType', () => { expect(WrapperSelect1.prop('optionsSourceType')).toEqual( field1.optionsSourceType ) }) test('labelField', () => { expect(WrapperSelect1.prop('labelField')).toEqual(field1.labelField) }) test('valueField', () => { expect(WrapperSelect1.prop('valueField')).toEqual(field1.valueField) }) test('placeholder', () => { expect(WrapperSelect2.prop('placeholder')).toEqual(field2.placeholder) }) test('showCheckedStrategy', () => { expect(WrapperSelect2.prop('showCheckedStrategy')).toEqual( field2.showCheckedStrategy ) }) test('splitTag', () => { expect(WrapperSelect3.prop('splitTag')).toEqual(field3.splitTag) }) test('nodePath', () => { expect(WrapperSelect3.prop('nodePath')).toEqual(field3.nodePath) }) }) describe('正确的方法', () => { test('componentDidMount optionsSourceType 为 dependencies', () => { const mockSetState = jest.spyOn(WrapperSelect2Instance, 'setState') // @ts-ignore WrapperSelect2Instance.componentDidMount() expect(mockSetState).toHaveBeenCalledTimes(1) mockSetState.mockRestore() }) test('componentDidMount searchConfigs', () => { // @ts-ignore const requestData = jest.spyOn(WrapperSelect0.instance(), 'requestData') // @ts-ignore WrapperSelect0.instance().componentDidMount() expect(requestData).toHaveBeenCalledTimes(1) requestData.mockRestore() }) test('requestData', () => { // @ts-ignore const res = WrapperSelect1Instance.requestData('aaa') // @ts-ignore const targetUrl = field1.searchConfigs[0].url || 'xxxasdfasdf' const requestInfo = axiosMock.getReqByUrl(targetUrl) expect(requestInfo.config.params).toMatchObject({ key: 'aaa', }) const mockResponse = { status: 200, data: { code: 0, data: [{ AAA: 1324 }] }, } axiosMock.mockResponseFor(targetUrl, mockResponse) return expect(res).resolves.toEqual(mockResponse.data.data) }) test('onLoadData', async () => { // @ts-ignore const mockRequestData = jest.spyOn(WrapperSelect3.instance(), 'requestData') const dataRef = { disabled: false, searchable: true, selectable: true, title: '北京', value: '110000', } // @ts-ignore WrapperSelect3.instance().onLoadData(dataRef) await sleep(10) expect(mockRequestData).toBeCalledTimes(0) // @ts-ignore mockRequestData.mockRestore() }) test('onTreeExpand', () => { const expandedKeys = ['x', 'yu', 'z'] // @ts-ignore WrapperSelect1Instance.onTreeExpand(expandedKeys) expect(WrapperSelect1Instance.state.expandedKeys).toEqual(expandedKeys) }) describe('renderTreeNodes', () => { const originData = [ { key: '0-0', title: 'Node1', value: '0-0', children: [ { title: 'Node1-1', value: '0-0-0', key: '0-0-0', disabled: true }, ], }, { title: '叶子节点', value: '1', key: '1', isLeaf: true, }, ] // @ts-ignore const _nodes = WrapperSelect1Instance.renderTreeNodes(originData) test('lenght', () => { expect(_nodes).toHaveLength(originData.length) }) function checkNodes(nodes: any[], data: any[], parentKey = '') { if (_.isArray(nodes)) { let i = 0 for (let item of nodes) { let itemData = data[i] test(`${parentKey} nodes[${i}]`, () => { expect(item.type).toEqual(TreeNode) expect(item.key).toEqual(itemData.key) expect(item.props).toMatchObject({ title: itemData.title, value: itemData.value, dataRef: itemData, }) if (itemData.isLeaf !== undefined) { expect(item.props.isLeaf).toEqual(itemData.isLeaf) } if (itemData.disabled !== undefined) { expect(item.props.disabled).toEqual(itemData.disabled) } }) if (_.isArray(itemData.children)) { test(`${parentKey} nodes[${i}].children`, () => { checkNodes(item.children, itemData.children, itemData.key) }) } i++ } } } checkNodes(_nodes, originData) }) describe('onChange', () => { test('onChange 单选', () => { const value = [{ label: '昌平区', value: 'cq' }] // @ts-ignore WrapperSelect2Instance.onChange(value) expect(WrapperSelect2.prop('labelField')).toEqual('title') expect(WrapperSelect2.prop('valueField')).toEqual('value') const value1 = 'aaa' try { // @ts-ignore WrapperSelect2Instance.onChange(value1) } catch (error) { expect(error.message).toEqual(`格式错误: value is not a string`) } }) test('onChange 多选', () => { const value = [ { label: '昌平区', value: 'cq' }, { label: '海淀区', value: 'hd' }, ] // @ts-ignore WrapperSelect1Instance.onChange(value) expect(WrapperSelect1.prop('labelField')).toEqual('title') expect(WrapperSelect1.prop('valueField')).toEqual('value') const value1 = 'xxx' try { // @ts-ignore WrapperSelect1Instance.onChange(value1) } catch (error) { expect(error.message).toEqual(`格式错误: value is not an array`) } }) }) })
the_stack
import { BLOCK_MAXSIZE, BLOCK, BLOCK_OVERHEAD } from "rt/common"; import { E_INVALIDLENGTH, E_INDEXOUTOFRANGE } from "util/error"; import { Uint8Array } from "typedarray"; export class Buffer extends Uint8Array { [key: number]: u8; constructor(size: i32) { super(size); } static alloc(size: i32): Buffer { return new Buffer(size); } @unsafe static allocUnsafe(size: i32): Buffer { // range must be valid if (<usize>size > BLOCK_MAXSIZE) throw new RangeError(E_INVALIDLENGTH); let buffer = __alloc(size, idof<ArrayBuffer>()); let result = __alloc(offsetof<Buffer>(), idof<Buffer>()); // set the properties store<usize>(result, __retain(buffer), offsetof<Buffer>("buffer")); store<usize>(result, buffer, offsetof<Buffer>("dataStart")); store<i32>(result, size, offsetof<Buffer>("byteLength")); // return and retain return changetype<Buffer>(result); } static isBuffer<T>(value: T): bool { return value instanceof Buffer; } // Adapted from https://github.com/AssemblyScript/assemblyscript/blob/master/std/assembly/typedarray.ts subarray(begin: i32 = 0, end: i32 = 0x7fffffff): Buffer { var len = <i32>this.byteLength; begin = begin < 0 ? max(len + begin, 0) : min(begin, len); end = end < 0 ? max(len + end, 0) : min(end, len); end = max(end, begin); var out = __alloc(offsetof<Buffer>(), idof<Buffer>()); // retains store<usize>(out, __retain(changetype<usize>(this.buffer)), offsetof<Buffer>("buffer")); store<usize>(out, this.dataStart + <usize>begin, offsetof<Buffer>("dataStart")); store<i32>(out, end - begin, offsetof<Buffer>("byteLength")); // retains return changetype<Buffer>(out); } readInt8(offset: i32 = 0): i8 { if (i32(offset < 0) | i32(offset >= this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); return load<i8>(this.dataStart + <usize>offset); } readUInt8(offset: i32 = 0): u8 { if (i32(offset < 0) | i32(offset >= this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); return load<u8>(this.dataStart + <usize>offset); } writeInt8(value: i8, offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset >= this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); store<i8>(this.dataStart + offset, value); return offset + 1; } writeUInt8(value: u8, offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset >= this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); store<u8>(this.dataStart + offset, value); return offset + 1; } readInt16LE(offset: i32 = 0): i16 { if (i32(offset < 0) | i32(offset + 2 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); return load<i16>(this.dataStart + <usize>offset); } readInt16BE(offset: i32 = 0): i16 { if (i32(offset < 0) | i32(offset + 2 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); return bswap(load<i16>(this.dataStart + <usize>offset)); } readUInt16LE(offset: i32 = 0): u16 { if (i32(offset < 0) | i32(offset + 2 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); return load<u16>(this.dataStart + <usize>offset); } readUInt16BE(offset: i32 = 0): u16 { if (i32(offset < 0) | i32(offset + 2 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); return bswap(load<u16>(this.dataStart + <usize>offset)); } writeInt16LE(value: i16, offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset + 2 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); store<i16>(this.dataStart + offset, value); return offset + 2; } writeInt16BE(value: i16, offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset + 2 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); store<i16>(this.dataStart + offset, bswap(value)); return offset + 2; } writeUInt16LE(value: u16, offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset + 2 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); store<u16>(this.dataStart + offset, value); return offset + 2; } writeUInt16BE(value: u16, offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset + 2 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); store<u16>(this.dataStart + offset, bswap(value)); return offset + 2; } readInt32LE(offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset + 4 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); return load<i32>(this.dataStart + <usize>offset); } readInt32BE(offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset + 4 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); return bswap(load<i32>(this.dataStart + <usize>offset)); } readUInt32LE(offset: i32 = 0): u32 { if (i32(offset < 0) | i32(offset + 4 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); return load<u32>(this.dataStart + <usize>offset); } readUInt32BE(offset: i32 = 0): u32 { if (i32(offset < 0) | i32(offset + 4 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); return bswap(load<u32>(this.dataStart + <usize>offset)); } writeInt32LE(value: i32, offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset + 4 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); store<i32>(this.dataStart + offset, value); return offset + 4; } writeInt32BE(value: i32, offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset + 4 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); store<i32>(this.dataStart + offset, bswap(value)); return offset + 4; } writeUInt32LE(value: u32, offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset + 4 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); store<u32>(this.dataStart + offset, value); return offset + 4; } writeUInt32BE(value: u32, offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset + 4 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); store<u32>(this.dataStart + offset, bswap(value)); return offset + 4; } readFloatLE(offset: i32 = 0): f32 { if (i32(offset < 0) | i32(offset + 4 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); return load<f32>(this.dataStart + <usize>offset); } readFloatBE(offset: i32 = 0): f32 { if (i32(offset < 0) | i32(offset + 4 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); return reinterpret<f32>(bswap(load<i32>(this.dataStart + <usize>offset))); } writeFloatLE(value: f32, offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset + 4 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); store<f32>(this.dataStart + offset, value); return offset + 4; } writeFloatBE(value: f32, offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset + 4 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); store<i32>(this.dataStart + offset, bswap(reinterpret<i32>(value))); return offset + 4; } readBigInt64LE(offset: i32 = 0): i64 { if (i32(offset < 0) | i32(offset + 8 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); return load<i64>(this.dataStart + <usize>offset); } readBigInt64BE(offset: i32 = 0): i64 { if (i32(offset < 0) | i32(offset + 8 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); return bswap(load<i64>(this.dataStart + <usize>offset)); } readBigUInt64LE(offset: i32 = 0): u64 { if (i32(offset < 0) | i32(offset + 8 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); return load<u64>(this.dataStart + <usize>offset); } readBigUInt64BE(offset: i32 = 0): u64 { if (i32(offset < 0) | i32(offset + 8 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); return bswap(load<u64>(this.dataStart + <usize>offset)); } writeBigInt64LE(value: i64, offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset + 8 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); store<i64>(this.dataStart + offset, value); return offset + 8; } writeBigInt64BE(value: i64, offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset + 8 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); store<i64>(this.dataStart + offset, bswap(value)); return offset + 8; } writeBigUInt64LE(value: u64, offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset + 8 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); store<u64>(this.dataStart + offset, value); return offset + 8; } writeBigUInt64BE(value: u64, offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset + 8 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); store<u64>(this.dataStart + offset, bswap(value)); return offset + 8; } readDoubleLE(offset: i32 = 0): f64 { if (i32(offset < 0) | i32(offset + 8 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); return load<f64>(this.dataStart + <usize>offset); } readDoubleBE(offset: i32 = 0): f64 { if (i32(offset < 0) | i32(offset + 8 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); return reinterpret<f64>(bswap(load<i64>(this.dataStart + <usize>offset))); } writeDoubleLE(value: f64, offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset + 8 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); store<f64>(this.dataStart + offset, value); return offset + 8; } writeDoubleBE(value: f64, offset: i32 = 0): i32 { if (i32(offset < 0) | i32(offset + 8 > this.byteLength)) throw new RangeError(E_INDEXOUTOFRANGE); store<i64>(this.dataStart + offset, bswap(reinterpret<i64>(value))); return offset + 8; } swap16(): Buffer { let byteLength = <usize>this.byteLength; // Make sure byteLength is even if (byteLength & 1) throw new RangeError(E_INVALIDLENGTH); let dataStart = this.dataStart; byteLength += dataStart; while (dataStart < byteLength) { store<u16>(dataStart, bswap(load<u16>(dataStart))); dataStart += 2; } return this; } swap32(): Buffer { let byteLength = <usize>this.byteLength; // Make sure byteLength is divisible by 4 if (byteLength & 3) throw new RangeError(E_INVALIDLENGTH); let dataStart = this.dataStart; byteLength += dataStart; while (dataStart < byteLength) { store<u32>(dataStart, bswap(load<u32>(dataStart))); dataStart += 4; } return this; } swap64(): Buffer { let byteLength = <usize>this.byteLength; // Make sure byteLength is divisible by 8 if (byteLength & 7) throw new RangeError(E_INVALIDLENGTH); let dataStart = this.dataStart; byteLength += dataStart; while (dataStart < <usize>byteLength) { store<u64>(dataStart, bswap(load<u64>(dataStart))); dataStart += 8; } return this; } } export namespace Buffer { export namespace ASCII { export function encode(str: string): ArrayBuffer { let length = str.length; let output = __alloc(length, idof<ArrayBuffer>()); for (let i = 0; i < length; i++) { let char = load<u16>(changetype<usize>(str) + <usize>(i << 1)); store<u8>(output + <usize>i, char & 0x7F); } return changetype<ArrayBuffer>(output); } export function decode(buffer: ArrayBuffer): String { return decodeUnsafe(changetype<usize>(buffer), buffer.byteLength); } // @ts-ignore: decorator @unsafe export function decodeUnsafe(pointer: usize, length: i32): String { let result = __alloc(<usize>length << 1, idof<string>()); for (let i = 0; i < length; i++) { let byte = load<u8>(pointer + <usize>i); store<u16>(result + <usize>(i << 1), byte & 0x7F); } return changetype<String>(result); } } export namespace HEX { /** Calculates the byte length of the specified string when encoded as HEX. */ export function byteLength(str: string): i32 { let ptr = changetype<usize>(str); let byteCount = <usize>changetype<BLOCK>(changetype<usize>(str) - BLOCK_OVERHEAD).rtSize; let length = byteCount >>> 2; // The string length must be even because the bytes come in pairs of characters two wide if (byteCount & 3) return 0; // encoding fails and returns an empty ArrayBuffer byteCount += ptr; while (ptr < byteCount) { var char = load<u16>(ptr); if ( ((char - 0x30) <= 9) || ((char - 0x61) <= 5) || ((char - 0x41) <= 5)) { ptr += 2; continue; } else { return 0; } } return <i32>length; } /** Creates an ArrayBuffer from a given string that is encoded in the HEX format. */ export function encode(str: string): ArrayBuffer { let bufferLength = byteLength(str); // short path: string is not a valid hex string, return a new empty ArrayBuffer if (bufferLength == 0) return changetype<ArrayBuffer>(__alloc(0, idof<ArrayBuffer>())); // long path: loop over each enociding pair and perform the conversion let ptr = changetype<usize>(str); let byteEnd = ptr + <usize>changetype<BLOCK>(changetype<usize>(str) - BLOCK_OVERHEAD).rtSize; let result = __alloc(bufferLength, idof<ArrayBuffer>()); let b: u32 = 0; let outChar = 0; for (let i: usize = 0; ptr < byteEnd; i++) { if (i & 1) { outChar <<= 4; b >>>= 16; if ((b - 0x30) <= 9) { outChar |= b - 0x30; } else if ((b - 0x61) <= 5) { outChar |= b - 0x57; } else if (b - 0x41 <= 5) { outChar |= b - 0x37; } store<u8>(result + (i >> 1), <u8>(outChar & 0xFF)); ptr += 4; } else { b = load<u32>(ptr); outChar <<= 4; let c = b & 0xFF; if ((c - 0x30) <= 9) { outChar |= c - 0x30; } else if ((c - 0x61) <= 5) { outChar |= c - 0x57; } else if (c - 0x41 <= 5) { outChar |= c - 0x37; } } } return changetype<ArrayBuffer>(result); } /** Creates a string from a given ArrayBuffer that is decoded into hex format. */ export function decode(buff: ArrayBuffer): string { return decodeUnsafe(changetype<usize>(buff), buff.byteLength); } /** Decodes a chunk of memory to a utf16le encoded string in hex format. */ // @ts-ignore: decorator @unsafe export function decodeUnsafe(ptr: usize, length: i32): string { let stringByteLength = length << 2; // length * (2 bytes per char) * (2 chars per input byte) let result = __alloc(stringByteLength, idof<String>()); let i = <usize>0; let inputByteLength = <usize>length + ptr; // loop over each byte and store a `u32` for each one while (ptr < inputByteLength) { store<u32>(result + i, charsFromByte(<u32>load<u8>(ptr++))); i += 4; } return changetype<string>(result); } /** Calculates the two char combination from the byte. */ // @ts-ignore: decorator @inline function charsFromByte(byte: u32): u32 { let hi = (byte >>> 4) & 0xF; let lo = byte & 0xF; hi += select(0x57, 0x30, hi > 9); lo += select(0x57, 0x30, lo > 9); return (lo << 16) | hi; } } }
the_stack
import { last, capitalize } from 'lodash'; import { ParameterBag } from '../parameter-bag'; export const comparisions = { equals, greaterThan, greaterEqualTo, lessThan, lessEqualTo, startsWith, endsWith, contains, inArray, hasLabel, exists, between, isNull, regexp, }; export type Comparator = (params: ParameterBag, name: string) => string; function compare(operator: string, value: any, variable?: boolean, paramName?: string): Comparator { return (params: ParameterBag, name: string): string => { const baseParamName = paramName || last(name.split('.')); const parts = [ name, operator, variable ? value : params.addParam(value, baseParamName), ]; return parts.join(' '); }; } /** * Equals comparator for use in where clauses. This is the default so you will * probably never need to use this. * * If you want to compare against a Neo4j variable you can set `variable` to * true and the value will be inserted literally into the query. * * ``` * query.where({ age: equals(18) }) * // WHERE age = 18 * * query.where({ name: equals('clientName', true) }) * // WHERE age = clientName * ``` * @param value * @param {boolean} variable * @returns {Comparator} */ export function equals(value: any, variable?: boolean) { return compare('=', value, variable); } /** * Greater than comparator for use in where clauses. * * If you want to compare against a Neo4j variable you can set `variable` to * true and the value will be inserted literally into the query. * * ``` * query.where({ age: greaterThan(18) }) * // WHERE age > 18 * * query.where({ age: greaterThan('clientAge', true) }) * // WHERE age > clientAge * ``` * @param value * @param {boolean} variable * @returns {Comparator} */ export function greaterThan(value: any, variable?: boolean) { return compare('>', value, variable); } /** * Greater or equal to comparator for use in where clauses. * * If you want to compare against a Neo4j variable you can set `variable` to * true and the value will be inserted literally into the query. * * ``` * query.where({ age: greaterEqualTo(18) }) * // WHERE age >= 18 * * query.where({ age: greaterEqualTo('clientAge', true) }) * // WHERE age >= clientAge * ``` * @param value * @param {boolean} variable * @returns {Comparator} */ export function greaterEqualTo(value: any, variable?: boolean) { return compare('>=', value, variable); } /** * Less than comparator for use in where clauses. * * If you want to compare against a Neo4j variable you can set `variable` to * true and the value will be inserted literally into the query. * * ``` * query.where({ age: lessThan(18) }) * // WHERE age < 18 * * query.where({ age: lessThan('clientAge', true) }) * // WHERE age < clientAge * ``` * @param value * @param {boolean} variable * @returns {Comparator} */ export function lessThan(value: any, variable?: boolean) { return compare('<', value, variable); } /** * Less or equal to comparator for use in where clauses. * * If you want to compare against a Neo4j variable you can set `variable` to * true and the value will be inserted literally into the query. * * ``` * query.where({ age: lessEqualTo(18) }) * // WHERE age <= 18 * * query.where({ age: lessEqualTo('clientAge', true) }) * // WHERE age >= clientAge * ``` * @param value * @param {boolean} variable * @returns {Comparator} */ export function lessEqualTo(value: any, variable?: boolean) { return compare('<=', value, variable); } /** * Starts with comparator for use in where clauses. * * If you want to compare against a Neo4j variable you can set `variable` to * true and the value will be inserted literally into the query. * * ``` * query.where({ name: startsWith('steve') }) * // WHERE name STARTS WITH 'steve' * * query.where({ name: startsWith('clientName', true) }) * // WHERE name STARTS WITH clientName * ``` * @param value * @param {boolean} variable * @returns {Comparator} */ export function startsWith(value: string, variable?: boolean) { return compare('STARTS WITH', value, variable); } /** * Ends with comparator for use in where clauses. * * If you want to compare against a Neo4j variable you can set `variable` to * true and the value will be inserted literally into the query. * * ``` * query.where({ name: endsWith('steve') }) * // WHERE name ENDS WITH 'steve' * * query.where({ name: endsWith('clientName', true) }) * // WHERE name ENDS WITH clientName * ``` * @param value * @param {boolean} variable * @returns {Comparator} */ export function endsWith(value: string, variable?: boolean) { return compare('ENDS WITH', value, variable); } /** * Contains comparator for use in where clauses. * * If you want to compare against a Neo4j variable you can set `variable` to * true and the value will be inserted literally into the query. * * ``` * query.where({ name: contains('steve') }) * // WHERE name CONTAINS 'steve' * * query.where({ name: contains('clientName', true) }) * // WHERE name CONTAINS clientName * ``` * @param value * @param {boolean} variable * @returns {Comparator} */ export function contains(value: string, variable?: boolean) { return compare('CONTAINS', value, variable); } /** * In comparator for use in where clauses. * * If you want to compare against a Neo4j variable you can set `variable` to * true and the value will be inserted literally into the query. * * ``` * query.where({ name: inArray([ 'steve', 'william' ]) }) * // WHERE name IN [ 'steve', 'william' ] * * query.where({ name: inArray('clientNames', true) }) * // WHERE name IN clientNames * ``` * @param value * @param {boolean} variable * @returns {Comparator} */ export function inArray(value: any[], variable?: boolean) { return compare('IN', value, variable); } /** * Regexp comparator for use in where clauses. Also accepts a case insensitive * to make it easier to add the `'(?i)'` flag to the start of your regexp. * If you are already using flags in your regexp, you should not set insensitive * to true because it will prepend `'(?i)'` which will make your regexp * malformed. * * For convenience you can also pass a Javascript RegExp object into this * comparator, which will then be converted into a string before it is * passed to cypher. *However*, beware that the cypher regexp syntax is * inherited from [java]{@link * https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html}, * and may have slight differences to the Javascript syntax. For example, * Javascript RegExp flags will not be preserved when sent to cypher. * * If you want to compare against a Neo4j variable you can set `variable` to * true and the value will be inserted literally into the query. * * ``` * query.where({ name: regexp('s.*e') }) * // WHERE name =~ 's.*e' * * query.where({ name: regexp('s.*e', true) }) * // WHERE name =~ '(?i)s.*e' * * query.where({ name: regexp('clientPattern', false, true) }) * // WHERE name =~ clientPattern * ``` * @param exp * @param insensitive * @param {boolean} variable * @returns {Comparator} */ export function regexp(exp: string | RegExp, insensitive?: boolean, variable?: boolean) { let stringExp = exp; if (exp instanceof RegExp) { // Convert regular expression to string and strip slashes and trailing flags. // This regular expression will always match something so we can use the ! operator to ignore // type errors. stringExp = exp.toString().match(/\/(.*)\/[a-z]*/)![1]; } return compare('=~', insensitive ? `(?i)${stringExp}` : stringExp, variable); } /** * Between comparator for use in where clauses. This comparator uses Neo4j's * shortcut comparison syntax: `18 <= age <= 65`. * * The `lower` and `upper` are the bounds of the comparison. You can use * `lowerInclusive` and `upperInclusive` to control whether it uses `<=` or `<` * for the comparison. They both default to `true`. * * If you pass only `lowerInclusive` then it will use that value for both. * * If you want to compare against a Neo4j variable you can set `variable` to * true and the value will be inserted literally into the query. * * ``` * query.where({ age: between(18, 65) }) * // WHERE age >= 18 AND age <= 65 * * query.where({ age: between(18, 65, false) }) * // WHERE age > 18 < AND age < 65 * * query.where({ age: between(18, 65, true, false) }) * // WHERE age >= 18 AND age < 65 * * query.where({ age: between('lowerBound', 'upperBound', true, false, true) }) * // WHERE age >= lowerBound AND age < upperBound * ``` * * @param lower * @param upper * @param {boolean} lowerInclusive * @param {boolean} upperInclusive * @param {boolean} variables * @returns {Comparator} */ export function between( lower: any, upper: any, lowerInclusive = true, upperInclusive = lowerInclusive, variables?: boolean, ): Comparator { const lowerOp = lowerInclusive ? '>=' : '>'; const upperOp = upperInclusive ? '<=' : '<'; return (params: ParameterBag, name) => { const paramName = capitalize(name); const lowerComparator = compare(lowerOp, lower, variables, `lower${paramName}`); const upperComparator = compare(upperOp, upper, variables, `upper${paramName}`); const lowerConstraint = lowerComparator(params, name); const upperConstraint = upperComparator(params, name); return `${lowerConstraint} AND ${upperConstraint}`; }; } /** * Is null comparator for use in where clauses. Note that this comparator does * not accept any arguments * * ``` * query.where({ name: isNull() }) * // WHERE name IS NULL * ``` * @returns {Comparator} */ export function isNull(): Comparator { return (params, name) => `${name} IS NULL`; } /** * Has label comparator for use in where clauses. * * ``` * query.where({ person: hasLabel('Manager') }) * // WHERE person:Manager * ``` * @param {string} label * @returns {Comparator} */ export function hasLabel(label: string): Comparator { return (params, name) => `${name}:${label}`; } /** * Exists comparator for use in where clauses. Note that this comparator does * not accept any arguments * * ``` * query.where({ person: exists() }) * // WHERE exists(person) * ``` * @returns {Comparator} */ export function exists(): Comparator { return (params, name) => `exists(${name})`; }
the_stack
import * as style from '../style.css'; import { startBlobs } from './meta'; /** * Control point x,y - point x,y - control point x,y */ export type BlobPoint = [number, number, number, number, number, number]; const maxPointDistance = 0.25; function randomisePoint(point: BlobPoint): BlobPoint { const distance = Math.random() * maxPointDistance; const angle = Math.random() * Math.PI * 2; const xShift = Math.sin(angle) * distance; const yShift = Math.cos(angle) * distance; return [ point[0] + xShift, point[1] + yShift, point[2] + xShift, point[3] + yShift, point[4] + xShift, point[5] + yShift, ]; } function easeInOutQuad(x: number): number { return x < 0.5 ? 2 * x * x : 1 - Math.pow(-2 * x + 2, 2) / 2; } function easeInExpo(x: number): number { return x === 0 ? 0 : Math.pow(2, 10 * x - 10); } const rand = (min: number, max: number) => Math.random() * (max - min) + min; interface CircleBlobPointState { basePoint: BlobPoint; pos: number; duration: number; startPoint: BlobPoint; endPoint: BlobPoint; } /** Bezier points for a seven point circle, to 3 decimal places */ const sevenPointCircle: BlobPoint[] = [ [-0.304, -1, 0, -1, 0.304, -1], [0.592, -0.861, 0.782, -0.623, 0.972, -0.386], [1.043, -0.074, 0.975, 0.223, 0.907, 0.519], [0.708, 0.769, 0.434, 0.901, 0.16, 1.033], [-0.16, 1.033, -0.434, 0.901, -0.708, 0.769], [-0.907, 0.519, -0.975, 0.223, -1.043, -0.074], [-0.972, -0.386, -0.782, -0.623, -0.592, -0.861], ]; /* // Should it be needed, here's how the above was created: function createBezierCirclePoints(points: number): BlobPoint[] { const anglePerPoint = 360 / points; const matrix = new DOMMatrix(); const point = new DOMPoint(); const controlDistance = (4 / 3) * Math.tan(Math.PI / (2 * points)); return Array.from({ length: points }, (_, i) => { point.x = -controlDistance; point.y = -1; const cp1 = point.matrixTransform(matrix); point.x = 0; point.y = -1; const p = point.matrixTransform(matrix); point.x = controlDistance; point.y = -1; const cp2 = point.matrixTransform(matrix); const basePoint: BlobPoint = [cp1.x, cp1.y, p.x, p.y, cp2.x, cp2.y]; matrix.rotateSelf(0, 0, anglePerPoint); return basePoint; }); } */ interface CircleBlobOptions { minDuration?: number; maxDuration?: number; startPoints?: BlobPoint[]; } class CircleBlob { private animStates: CircleBlobPointState[]; private minDuration: number; private maxDuration: number; private points: BlobPoint[]; constructor( basePoints: BlobPoint[], { startPoints = basePoints.map((point) => randomisePoint(point)), minDuration = 4000, maxDuration = 11000, }: CircleBlobOptions = {}, ) { this.points = startPoints; this.minDuration = minDuration; this.maxDuration = maxDuration; this.animStates = basePoints.map((basePoint, i) => ({ basePoint, pos: 0, duration: rand(minDuration, maxDuration), startPoint: startPoints[i], endPoint: randomisePoint(basePoint), })); } advance(timeDelta: number): void { this.points = this.animStates.map((animState) => { animState.pos += timeDelta / animState.duration; if (animState.pos >= 1) { animState.startPoint = animState.endPoint; animState.pos = 0; animState.duration = rand(this.minDuration, this.maxDuration); animState.endPoint = randomisePoint(animState.basePoint); } const eased = easeInOutQuad(animState.pos); const point = animState.startPoint.map((startPoint, i) => { const endPoint = animState.endPoint[i]; return (endPoint - startPoint) * eased + startPoint; }) as BlobPoint; return point; }); } draw(ctx: CanvasRenderingContext2D) { const points = this.points; ctx.beginPath(); ctx.moveTo(points[0][2], points[0][3]); for (let i = 0; i < points.length; i++) { const nextI = i === points.length - 1 ? 0 : i + 1; ctx.bezierCurveTo( points[i][4], points[i][5], points[nextI][0], points[nextI][1], points[nextI][2], points[nextI][3], ); } ctx.closePath(); ctx.fill(); } } const centralBlobsRotationTime = 120000; class CentralBlobs { private rotatePos: number = 0; private blobs = Array.from( { length: 4 }, (_, i) => new CircleBlob(sevenPointCircle, { startPoints: startBlobs[i] }), ); advance(timeDelta: number) { this.rotatePos = (this.rotatePos + timeDelta / centralBlobsRotationTime) % 1; for (const blob of this.blobs) blob.advance(timeDelta); } draw(ctx: CanvasRenderingContext2D, x: number, y: number, radius: number) { ctx.save(); ctx.translate(x, y); ctx.scale(radius, radius); ctx.rotate(Math.PI * 2 * this.rotatePos); for (const blob of this.blobs) blob.draw(ctx); ctx.restore(); } } const bgBlobsMinRadius = 7; const bgBlobsMaxRadius = 60; const bgBlobsMinAlpha = 0.2; const bgBlobsMaxAlpha = 0.8; const bgBlobsPerPx = 0.000025; const bgBlobsMinSpinTime = 20000; const bgBlobsMaxSpinTime = 60000; const bgBlobsMinVelocity = 0.0015; const bgBlobsMaxVelocity = 0.007; const gravityVelocityMultiplier = 15; const gravityStartDistance = 300; interface BackgroundBlob { blob: CircleBlob; velocity: number; spinTime: number; alpha: number; alphaMultiplier: number; rotatePos: number; radius: number; x: number; y: number; } const bgBlobsAlphaTime = 2000; class BackgroundBlobs { private bgBlobs: BackgroundBlob[] = []; private overallAlphaPos = 0; constructor(bounds: DOMRect) { const blobs = Math.round(bounds.width * bounds.height * bgBlobsPerPx); this.bgBlobs = Array.from({ length: blobs }, () => { const radiusPos = easeInExpo(Math.random()); return { blob: new CircleBlob(sevenPointCircle, { minDuration: 2000, maxDuration: 5000, }), // Velocity is based on the size velocity: (1 - radiusPos) * (bgBlobsMaxVelocity - bgBlobsMinVelocity) + bgBlobsMinVelocity, alpha: Math.random() ** 3 * (bgBlobsMaxAlpha - bgBlobsMinAlpha) + bgBlobsMinAlpha, alphaMultiplier: 1, spinTime: rand(bgBlobsMinSpinTime, bgBlobsMaxSpinTime), rotatePos: 0, radius: radiusPos * (bgBlobsMaxRadius - bgBlobsMinRadius) + bgBlobsMinRadius, x: Math.random() * bounds.width, y: Math.random() * bounds.height, }; }); } advance( timeDelta: number, bounds: DOMRect, targetX: number, targetY: number, targetRadius: number, ) { if (this.overallAlphaPos !== 1) { this.overallAlphaPos = Math.min( 1, this.overallAlphaPos + timeDelta / bgBlobsAlphaTime, ); } for (const bgBlob of this.bgBlobs) { bgBlob.blob.advance(timeDelta); let dist = Math.hypot(bgBlob.x - targetX, bgBlob.y - targetY); bgBlob.rotatePos = (bgBlob.rotatePos + timeDelta / bgBlob.spinTime) % 1; if (dist < 10) { // Move the circle out to a random edge switch (Math.floor(Math.random() * 4)) { case 0: // top bgBlob.x = Math.random() * bounds.width; bgBlob.y = -(bgBlob.radius * (1 + maxPointDistance)); break; case 1: // left bgBlob.x = -(bgBlob.radius * (1 + maxPointDistance)); bgBlob.y = Math.random() * bounds.height; break; case 2: // bottom bgBlob.x = Math.random() * bounds.width; bgBlob.y = bounds.height + bgBlob.radius * (1 + maxPointDistance); break; case 3: // right bgBlob.x = bounds.width + bgBlob.radius * (1 + maxPointDistance); bgBlob.y = Math.random() * bounds.height; break; } } dist = Math.hypot(bgBlob.x - targetX, bgBlob.y - targetY); const velocity = dist > gravityStartDistance ? bgBlob.velocity : ((1 - dist / gravityStartDistance) * (gravityVelocityMultiplier - 1) + 1) * bgBlob.velocity; const shiftDist = velocity * timeDelta; const direction = Math.atan2(targetX - bgBlob.x, targetY - bgBlob.y); const xShift = Math.sin(direction) * shiftDist; const yShift = Math.cos(direction) * shiftDist; bgBlob.x += xShift; bgBlob.y += yShift; bgBlob.alphaMultiplier = Math.min(dist / targetRadius, 1); } } draw(ctx: CanvasRenderingContext2D) { const overallAlpha = easeInOutQuad(this.overallAlphaPos); for (const bgBlob of this.bgBlobs) { ctx.save(); ctx.globalAlpha = bgBlob.alpha * bgBlob.alphaMultiplier * overallAlpha; ctx.translate(bgBlob.x, bgBlob.y); ctx.scale(bgBlob.radius, bgBlob.radius); ctx.rotate(Math.PI * 2 * bgBlob.rotatePos); bgBlob.blob.draw(ctx); ctx.restore(); } } } const deltaMultiplierStep = 0.01; export function startBlobAnim(canvas: HTMLCanvasElement) { let lastTime: number; const ctx = canvas.getContext('2d')!; const centralBlobs = new CentralBlobs(); let backgroundBlobs: BackgroundBlobs; const loadImgEl = document.querySelector('.' + style.loadImg)!; let hasFocus = document.hasFocus(); let deltaMultiplier = hasFocus ? 1 : 0; let animating = true; const visibilityListener = () => { // 'Pause time' while page is hidden if (document.visibilityState === 'visible') lastTime = performance.now(); }; const focusListener = () => { hasFocus = true; if (!animating) startAnim(); }; const blurListener = () => { hasFocus = false; }; const resizeObserver = new ResizeObserver(() => { // Redraw for new canvas size if (!animating) drawFrame(0); }); resizeObserver.observe(canvas); addEventListener('focus', focusListener); addEventListener('blur', blurListener); document.addEventListener('visibilitychange', visibilityListener); function destruct() { removeEventListener('focus', focusListener); removeEventListener('blur', blurListener); resizeObserver.disconnect(); document.removeEventListener('visibilitychange', visibilityListener); } function drawFrame(delta: number) { const canvasBounds = canvas.getBoundingClientRect(); canvas.width = canvasBounds.width * devicePixelRatio; canvas.height = canvasBounds.height * devicePixelRatio; const loadImgBounds = loadImgEl.getBoundingClientRect(); const computedStyles = getComputedStyle(canvas); const blobPink = computedStyles.getPropertyValue('--blob-pink'); const loadImgCenterX = loadImgBounds.left - canvasBounds.left + loadImgBounds.width / 2; const loadImgCenterY = loadImgBounds.top - canvasBounds.top + loadImgBounds.height / 2; const loadImgRadius = loadImgBounds.height / 2 / (1 + maxPointDistance); ctx.scale(devicePixelRatio, devicePixelRatio); if (!backgroundBlobs) backgroundBlobs = new BackgroundBlobs(canvasBounds); backgroundBlobs.advance( delta, canvasBounds, loadImgCenterX, loadImgCenterY, loadImgRadius, ); centralBlobs.advance(delta); ctx.globalAlpha = Number( computedStyles.getPropertyValue('--center-blob-opacity'), ); ctx.fillStyle = blobPink; backgroundBlobs.draw(ctx); centralBlobs.draw(ctx, loadImgCenterX, loadImgCenterY, loadImgRadius); } function frame(time: number) { // Stop the loop if the canvas is gone if (!canvas.isConnected) { destruct(); return; } // Be kind: If the window isn't focused, bring the animation to a stop. if (!hasFocus) { // Bring the anim to a slow stop deltaMultiplier = Math.max(0, deltaMultiplier - deltaMultiplierStep); if (deltaMultiplier === 0) { animating = false; return; } } else if (deltaMultiplier !== 1) { deltaMultiplier = Math.min(1, deltaMultiplier + deltaMultiplierStep); } const delta = (time - lastTime) * deltaMultiplier; lastTime = time; drawFrame(delta); requestAnimationFrame(frame); } function startAnim() { animating = true; requestAnimationFrame((time: number) => { lastTime = time; frame(time); }); } startAnim(); }
the_stack
import {action, computed, observable} from "mobx"; import {getNodeKey, hasEmptyRoleMapping, isFocused, isHidden, isInline, isRootLandmark} from "./utils"; import {AriaIssues} from "./issues"; export type HtmlID = string; export type AomKey = string; export class Context { root: NodeElement | null; @observable descendants: NonNullable<NodeElement>[] = []; constructor(root: NodeElement | null) { this.root = root; } } export interface TableCell { rowIndex: number; colIndex: number; rowSpan: number; colSpan: number; colHeaders: NodeElement[]; rowHeaders: NodeElement[]; } class Table { data: NodeElement[][] = []; set(row: number, col: number, node: NodeElement) { this.data[row] = this.data[row] ?? []; this.data[row][col] = node; } get(row: number, col: number) { return this.data[row] && this.data[row][col]; } } export class HtmlTableContext { root: NodeElement; @observable _visibleRow: number = 0; @observable _visibleColumn: number = 0; @computed get visibleRow(): number { if (!this.rows.length) { return -1; } const maxRow = this.rows.length - 1; if (this._visibleRow < 0) return 0; if (this._visibleRow >= maxRow) return maxRow; return this._visibleRow; } set visibleRow(value: number) { this._visibleRow = value; } @computed get visibleColumn(): number { if (!this.rows[this.visibleRow]?.length) { return -1; } const maxCol = this.rows[this.visibleRow].length - 1; if (this._visibleColumn < 0) return 0; if (this._visibleColumn >= maxCol) return maxCol; return this._visibleColumn; } set visibleColumn(value: number) { this._visibleColumn = value; } @computed get visibleCell(): NodeElement | null { if (!this.rows) { return null; } return this.rows[this.visibleRow] && this.rows[this.visibleRow][this.visibleColumn]; } @action showCellWithNode(element: NodeElement) { for (let node: NodeElement | null = element; node != null; node = node.ariaParent) { const cell = this.cells.get(node); if (cell) { this.visibleRow = cell.rowIndex; this.visibleColumn = cell.colIndex; } } } private getNextRow(step: 1 | -1) { return this.findNextIndex( this.rows, this.visibleRow, step, row => row[this.visibleColumn] && row[this.visibleColumn] !== this.visibleCell ); } private getNextColumn(step: 1 | -1) { return this.findNextIndex(this.rows[this.visibleRow], this.visibleColumn, step, x => x && x !== this.visibleCell); } @action showNextRow() { const row = this.getNextRow(1); if (row != null) { this.visibleRow = row; } } @action showPreviousRow() { const row = this.getNextRow(-1); if (row != null) { this.visibleRow = row; } } @action showNextColumn() { const column = this.getNextColumn(1); if (column != null) { this.visibleColumn = column; } } @action showPreviousColumn() { const column = this.getNextColumn(-1); if (column != null) { this.visibleColumn = column; } } private findNextIndex<T>(list: T[], start: number, step: number, condition: (arg: T) => boolean) { for (let i = start; i >= 0 && i < list.length; i += step) { if (condition(list[i])) return i; } return null; } private getNodes(root: NodeElement, ...allowedTags: string[]): NodeElement[] { return root.children.filter(child => { return child instanceof NodeElement && allowedTags.includes(child.htmlTag); }) as NodeElement[]; } @computed get rows(): NodeElement[][] { const result = new Table(); const rowNodes = this.getNodes(this.root, "tr", "tbody", "tfooter", "thead") .map(node => (node.htmlTag === "tr" ? node : this.getNodes(node, "tr"))) .flat(); rowNodes.forEach((rowNode, rowIndex) => { let colIndex = 0; result.data[rowIndex] = result.data[rowIndex] || [] this.getNodes(rowNode, "td", "th").forEach(cell => { while (result.get(rowIndex, colIndex)) colIndex++; const {rowSpan, colSpan} = cell.getRawProperties(); for (let i = 0; i < (rowSpan ?? 1); i++) { for (let j = 0; j < (colSpan ?? 1); j++) { result.set(rowIndex + i, colIndex + j, cell); } } }); }); return result.data; } @computed get colCount() { let result = 0; this.rows.forEach(row => (result = Math.max(result, row.length))); return result; } @computed get rowCount() { // TODO - compute it properly taking into account rowspan return this.rows.length; } @computed get colHeaders(): NodeElement[][] { const result: NodeElement[][] = []; for (let rowIndex = 0; rowIndex < this.rows.length; rowIndex++) { if (this.rows[rowIndex].every(x => x.htmlTag === "th")) { for (let colIndex = 0; colIndex < this.rows[rowIndex].length; colIndex++) { result[colIndex] = result[colIndex] ?? []; result[colIndex].push(this.rows[rowIndex][colIndex]); } } else { for (let colIndex = 0; colIndex < this.rows[rowIndex].length; colIndex++) { result[colIndex] = result[colIndex] ?? []; const attrs = this.rows[rowIndex][colIndex]?.getRawAttributes(); if (attrs?.scope === "column" || attrs?.role === "columnheader") { result[colIndex].push(this.rows[rowIndex][colIndex]); } } } } return result; } @computed get rowHeaders(): NodeElement[][] { const result: NodeElement[][] = []; for (let colIndex = 0; colIndex < this.colCount; colIndex++) { if (this.rows.every(row => row[colIndex] == null || row[colIndex].htmlTag === "th")) { for (let rowIndex = 0; rowIndex < this.rows.length; rowIndex++) { result[rowIndex] = result[rowIndex] ?? []; if (!this.colHeaders[colIndex].includes(this.rows[rowIndex][colIndex])) { result[rowIndex].push(this.rows[rowIndex][colIndex]); } } } else { for (let rowIndex = 0; rowIndex < this.rows.length; rowIndex++) { result[rowIndex] = result[rowIndex] ?? []; const attrs = this.rows[rowIndex][colIndex]?.getRawAttributes(); if (attrs?.scope === "row" || attrs?.role === "rowheader") { result[rowIndex].push(this.rows[rowIndex][colIndex]); } } } } return result; } @computed get cells(): Map<NodeElement, TableCell> { const result = new Map<NodeElement, TableCell>(); this.rows.forEach((row, rowIndex) => { row.forEach((cell, colIndex) => { const entry = result.get(cell); const rowHeaders = this.rowHeaders[rowIndex] ?? []; const colHeaders = this.colHeaders[colIndex] ?? []; if (entry) { entry.rowHeaders.push(...rowHeaders.filter(x => !entry.rowHeaders.includes(x))); entry.colHeaders.push(...colHeaders.filter(x => !entry.colHeaders.includes(x))); entry.rowSpan = rowIndex - entry.rowIndex + 1; entry.colSpan = colIndex - entry.colIndex + 1; } else { result.set(cell, { rowHeaders: [...rowHeaders], colHeaders: [...colHeaders], rowIndex, colIndex, rowSpan: 1, colSpan: 1 }); } }); }); return result; } constructor(root: NodeElement) { this.root = root; } } export class AriaTableContext extends HtmlTableContext { private getDescendants(root: NodeElement, ...allowedRoles: AriaRole[]): NodeElement[] { if (allowedRoles.includes(root.role)) { return [root]; } return root.children .map(child => (child instanceof NodeElement ? this.getDescendants(child, ...allowedRoles) : [])) .flat(); } @computed get rows(): NodeElement[][] { const result = new Table(); const rowNodes = this.getDescendants(this.root, "row"); rowNodes.forEach((rowNode, rowIndex) => { let colIndex = 0; this.getDescendants(rowNode, "columnheader", "rowheader", "cell", "gridcell").forEach(cell => { while (result.get(rowIndex, colIndex)) colIndex++; const attrs = cell.getRawAttributes(); const rowSpan = asNumber(attrs["aria-rowspan"]) ?? 1; const colSpan = asNumber(attrs["aria-rowspan"]) ?? 1; const row = asNumber(attrs["aria-rowindex"]) ?? rowIndex; const column = asNumber(attrs["aria-colindex"]) ?? colIndex; for (let i = 0; i < (rowSpan ?? 1); i++) { for (let j = 0; j < (colSpan ?? 1); j++) { result.set(row + i, column + j, cell); } } }); }); return result.data; } } export class AomNodeRelations { node: NodeElement; constructor(node: NodeElement) { this.node = node; } @observable ariaOwns: NodeElement[] = []; @observable ariaOwnedBy: NodeElement[] = []; @observable ariaControls: NodeElement[] = []; @observable ariaControlledBy: NodeElement[] = []; @observable ariaDescriptions: NodeElement[] = []; @observable ariaDescribedBy: NodeElement[] = []; @observable ariaErrorMessageOf: NodeElement[] = []; @observable ariaErrorMessages: NodeElement[] = []; @observable ariaActiveDescendantOf: NodeElement[] = []; @observable ariaActiveDescendants: NodeElement[] = []; @observable ariaLabelOf: NodeElement[] = []; @observable ariaLabelledBy: NodeElement[] = []; @observable htmlForLabelOf: NodeElement[] = []; @observable htmlForLabelledBy: NodeElement[] = []; @observable formContext: Context | null = null; @observable fieldsetContext: Context | null = null; @observable labelContext: Context | null = null; @observable ariaLiveContext: Context | null = null; @observable tableContext: HtmlTableContext | null = null; @observable previousHeading?: NodeElement | null; @computed get labelOf(): NodeElement[] { const result = [...this.htmlForLabelOf, ...this.ariaLabelOf]; if (!this.node.attributes.htmlFor && this.labelContext?.root === this.node) { result.push(...this.labelContext.descendants); } if ( this.node.htmlTag === "legend" && this.fieldsetContext?.root && this.fieldsetContext?.descendants.includes(this.node) ) { result.push(this.fieldsetContext?.root); } return result; } @computed get labelledBy(): NodeElement[] { const result = [...this.htmlForLabelledBy, ...this.ariaLabelledBy]; if ( this.htmlForLabelledBy.length === 0 && this.labelContext?.root && this.labelContext?.descendants.includes(this.node) ) { result.push(this.labelContext.root); } if (this.fieldsetContext?.root === this.node) { result.push(...this.fieldsetContext.descendants); } return result; } } export type AriaRole = | "alert" | "application" | "article" | "banner" | "button" | "checkbox" | "combobox" | "complementary" | "contentinfo" | "dialog" | "document" | "feed" | "figure" | "form" | "grid" | "heading" | "img" | "image" | "link" | "list" | "listbox" | "listitem" | "main" | "navigation" | "paragraph" | "region" | "row" | "rowgroup" | "search" | "switch" | "tab" | "table" | "tabpanel" | "textbox" | "timer" | "treegrid" | "columnheader" | "rowheader" | "cell" | "gridcell" | "text" | "option" | "none" | "presentation" | "radio" | null; export class TextElement { readonly key: AomKey; readonly role: AriaRole = "text"; readonly domNode: HTMLElement | null; @observable text: string; @observable htmlParent: NodeElement | null = null; @computed get hasContent() { return !!this.text.trim(); } @computed get ariaParent() { return this.htmlParent; } @computed get accessibleName() { return this.text; } constructor(props: { key: AomKey; text: string; node: HTMLElement | null }) { this.key = props.key; this.text = props.text; this.domNode = props.node; } } export function getAccessibleNameOf(items: AOMElement[]) { return items .map(item => { return item && (item instanceof TextElement ? item.text : item.accessibleName); }) .filter(name => name != null) .join(" "); } export class RawNodeAttributes { @observable id?: string = undefined; @observable role?: string = undefined; @observable href?: string = undefined; @observable disabled?: string = undefined; @observable src?: string = undefined; @observable alt?: string = undefined; @observable for?: string = undefined; @observable title?: string = undefined; @observable required?: string = undefined; @observable placeholder?: string = undefined; @observable type?: string = undefined; @observable name?: string = undefined; @observable multiple?: string = undefined; @observable size?: string = undefined; @observable scope?: string = undefined; @observable "aria-activedescendant"?: HtmlID = undefined; @observable "aria-atomic"?: boolean = undefined; @observable "aria-autocomplete"?: "inline" | "list" | "both" | "none" = undefined; @observable "aria-controls"?: HtmlID = undefined; @observable "aria-disabled"?: string = undefined; @observable "aria-modal"?: string = undefined; @observable "aria-describedby"?: HtmlID = undefined; @observable "aria-haspopup"?: string = undefined; @observable "aria-expanded"?: string = undefined; @observable "aria-label"?: string = undefined; @observable "aria-invalid"?: "false" | "true" = undefined; @observable "aria-labelledby"?: HtmlID = undefined; @observable "aria-level"?: string = undefined; @observable "aria-live"?: "off" | "polite" | "assertive" = undefined; @observable "aria-multiline"?: boolean = undefined; @observable "aria-multiselectable"?: string = undefined; @observable "aria-selected"?: string = undefined; @observable "aria-orientation"?: "horizontal" | "vertical" = undefined; @observable "aria-owns"?: string = undefined; @observable "aria-posinset"?: string = undefined; @observable "aria-colindex"?: string = undefined; @observable "aria-rowindex"?: string = undefined; @observable "aria-rowspan"?: string = undefined; @observable "aria-colspan"?: string = undefined; @observable "aria-readonly"?: string = undefined; @observable "aria-required"?: string = undefined; @observable "aria-checked"?: string = undefined; @observable "aria-setsize"?: string = undefined; @observable "aria-sort"?: "ascending" | "descending" | "none" | "other" = undefined; @observable "aria-valuemax"?: string = undefined; @observable "aria-valuemin"?: string = undefined; @observable "aria-valuenow"?: string = undefined; @observable "aria-valuetext"?: string = undefined; } function asNumber(value: string | number | null | undefined): number | undefined { switch (typeof value) { case "number": return value; case "string": return parseInt(value); default: return undefined; } } function asBoolean(value: string | boolean | null | undefined) { const isTrue = value === "" || value === "true" || value === true; const isFalse = value === "false"; if (isTrue) return true; if (isFalse) return false; return undefined; } export class RawNodeProperties { @observable value?: string = undefined; @observable invalid?: boolean = undefined; @observable disabled?: boolean = undefined; @observable checked?: boolean = undefined; @observable indeterminate?: boolean = undefined; @observable tabIndex: number = -1; @observable colSpan?: number = undefined; @observable rowSpan?: number = undefined; } export class Aria { private readonly node: NodeElement; private readonly rawAttributes: RawNodeAttributes; private readonly rawProperties: RawNodeProperties; constructor(node: NodeElement) { this.node = node; this.rawAttributes = node.getRawAttributes(); this.rawProperties = node.getRawProperties(); } @computed get mappedAttributes() { // HTML element & role mapping as defined at https://w3c.github.io/html-aam/#html-element-role-mappings const rawRole = this.rawAttributes.role?.trim(); const htmlTag = this.node.htmlTag; if (rawRole) { if (["cell", "gridcell", "columnheader", "rowheader"].includes(rawRole)) { const data = this.node.relations.tableContext?.cells.get(this.node); if (data) { return { role: rawRole, headers: [...data.rowHeaders, ...data.colHeaders], colIndex: data.colIndex + 1, rowIndex: data.rowIndex + 1, colSpan: data.colSpan, rowSpan: data.rowSpan }; } } if (rawRole === "alert") { return {role: rawRole, ariaLive: "assertive", ariaAtomic: true}; } if (rawRole === "switch" && htmlTag === "input" && this.rawAttributes.type?.trim() === "checkbox") { return { role: rawRole, ariaChecked: this.rawProperties.checked ? "true" : "false", ariaDisabled: this.rawProperties.disabled }; } return {role: rawRole}; } if (hasEmptyRoleMapping(htmlTag)) { return null; } if (htmlTag === "main") return {role: "main"}; if (htmlTag === "nav") return {role: "navigation"}; if (htmlTag === "aside") return {role: "complementary"}; if (htmlTag === "header") { return isRootLandmark(this.node) ? {role: "banner"} : null; } if (htmlTag === "footer") { return isRootLandmark(this.node) ? {role: "contentinfo"} : null; } if (["h1", "h2", "h3", "h4", "h5", "h6"].includes(htmlTag)) { return { role: "heading", ariaLevel: parseInt(this.node.htmlTag.slice(1)) }; } if (htmlTag === "a" || htmlTag === "area") { return {role: this.rawAttributes.href?.trim() ? "link" : null}; } if (htmlTag === "menu") { return {role: "list"}; } if (htmlTag === "ol" || htmlTag === "ul") { return {role: "list"}; } if (htmlTag === "li" && this.node.htmlParent) { const parent = this.node.htmlParent; if (parent.htmlTag !== "ol" && parent.htmlTag !== "ul") { return null; } const listItems = parent.htmlChildren.filter(item => item instanceof NodeElement && item.htmlTag === "li"); return { role: "listitem", ariaSetSize: listItems.length, ariaPosInSet: listItems.indexOf(this.node) + 1 }; } if (htmlTag === "img") { return { role: this.rawAttributes.alt?.trim() === "" ? "presentation" : "img" }; } if (htmlTag === "form") { if (this.rawAttributes["aria-label"]?.trim() || this.rawAttributes["aria-labelledby"]?.trim()) { return {role: "form"}; } else { return null; } } if (htmlTag === "fieldset") { return {role: "group"}; } if (htmlTag === "input") { const type = this.rawAttributes.type?.trim(); if (type === "checkbox") { const isMixed = this.rawProperties.indeterminate; const stringValue = this.rawProperties.checked ? "true" : "false"; return { role: "checkbox", ariaChecked: isMixed ? "mixed" : stringValue }; } if (type === "radio") { const groupName = this.rawAttributes.name?.trim(); let ariaSetSize = undefined; let ariaPosInSet = undefined; if (groupName && this.node.relations.formContext) { const groupInputs = this.node.relations.formContext.descendants.filter( node => node.attributes.htmlName === groupName ); ariaSetSize = groupInputs.length; ariaPosInSet = groupInputs.indexOf(this.node) + 1; } return { role: "radio", htmlChecked: this.rawProperties.checked, ariaSetSize, ariaPosInSet }; } if (type === "submit") { return {role: "button"}; } return {role: "textbox"}; } if (htmlTag === "textarea") { return {role: "textbox", ariaMultiline: true}; } if (htmlTag === "button") { return {role: "button"}; } if (htmlTag === "article") { return {role: "article"}; } if (htmlTag === "figure") { return {role: "figure"}; } if (htmlTag === "hr") { return {role: "separator"}; } if (htmlTag === "section") { const hasLabel = this.rawAttributes["aria-label"]?.trim() || this.rawAttributes["aria-labelledby"]?.trim(); return {role: hasLabel ? "region" : null}; } if (htmlTag === "dd") { return {role: "definition"}; } if (htmlTag === "dt") { return {role: "term"}; } if (htmlTag === "select") { const isMultiple = this.rawAttributes.multiple != undefined; const size = asNumber(this.rawAttributes.size); if (isMultiple || (size && size > 1)) { return {role: "listbox"}; } else { return {role: "combobox", ariaExpanded: false}; } } if (htmlTag === "optgroup") { return {role: "group"}; } if (htmlTag === "option") { return {role: "option"}; } if (htmlTag === "svg") { return {role: "graphics-document"}; } if (htmlTag === "table") { return {role: "table"}; } if (htmlTag === "thead" || htmlTag === "tbody" || htmlTag === "tfoot") { return {role: "rowgroup"}; } if (htmlTag === "tr") { return {role: "row"}; } if (htmlTag === "td" || htmlTag === "th") { const data = this.node.relations.tableContext?.cells.get(this.node); if (!this.node.relations.tableContext || !data) { return null; } let role = "cell"; if (htmlTag === "th") { const colHeaders = this.node.relations.tableContext.colHeaders; const rowHeaders = this.node.relations.tableContext.rowHeaders; if (colHeaders[data.colIndex].includes(this.node)) { role = "columnheader"; } else if (rowHeaders[data.rowIndex].includes(this.node)) { role = "rowheader"; } } return { role, headers: [...data.rowHeaders, ...data.colHeaders], colIndex: data.colIndex + 1, rowIndex: data.rowIndex + 1, colSpan: data.colSpan, rowSpan: data.rowSpan }; } return {role: "undefined"}; } @computed get id() { return this.rawAttributes.id?.trim(); } @computed get tabindex() { return this.rawProperties.tabIndex; } @computed get role() { return (this.rawAttributes.role?.trim() ?? this.mappedAttributes?.role ?? null) as AriaRole; } @computed get disabled() { return this.rawAttributes.disabled != null || asBoolean(this.rawAttributes["aria-disabled"]); } @computed get ariaControls() { return this.rawAttributes["aria-controls"]?.trim(); } @computed get ariaLabel() { return this.rawAttributes["aria-label"]?.trim(); } @computed get ariaLabelledBy() { return this.rawAttributes["aria-labelledby"]?.trim(); } @computed get ariaActiveDescendant() { return this.rawAttributes["aria-activedescendant"]?.trim(); } @computed get ariaOwns() { return this.rawAttributes["aria-owns"]?.trim(); } @computed get ariaRequired() { return asBoolean(this.rawAttributes["required"]?.trim()) ?? asBoolean(this.rawAttributes["aria-required"]?.trim()); } @computed get ariaInvalid() { return this.rawProperties.invalid || asBoolean(this.rawAttributes["aria-invalid"]?.trim()); } @computed get ariaMultiline() { return asBoolean(this.rawAttributes["aria-multiline"] ?? this.mappedAttributes?.ariaMultiline); } @computed get ariaMultiselectable() { return asBoolean(this.rawAttributes["aria-multiselectable"]); } @computed get ariaSelected() { return asBoolean(this.rawAttributes["aria-selected"]); } @computed get ariaModal() { return asBoolean(this.rawAttributes["aria-modal"]); } @computed get ariaHasPopup() { return asBoolean(this.rawAttributes["aria-haspopup"]?.trim()); } @computed get ariaLevel(): number | undefined { return asNumber(this.rawAttributes["aria-level"]?.trim() ?? this.mappedAttributes?.ariaLevel); } @computed get ariaSetSize(): number | undefined { return asNumber(this.rawAttributes["aria-setsize"]?.trim() ?? this.mappedAttributes?.ariaSetSize); } @computed get ariaPosInSet(): number | undefined { return asNumber(this.rawAttributes["aria-posinset"]?.trim() ?? this.mappedAttributes?.ariaPosInSet); } @computed get ariaDisabled() { return asBoolean(this.rawAttributes["aria-disabled"]?.trim()) ?? this.mappedAttributes?.ariaDisabled; } @computed get ariaChecked(): "true" | "false" | "mixed" | undefined { const value = this.rawAttributes["aria-checked"]?.trim() ?? this.mappedAttributes?.ariaChecked; if (!value) { return undefined; } return value === "mixed" || value === "true" ? value : "false"; } @computed get ariaColIndex(): number | undefined { return asNumber(this.rawAttributes["aria-colindex"]?.trim() ?? this.mappedAttributes?.colIndex); } @computed get ariaRowIndex(): number | undefined { return asNumber(this.rawAttributes["aria-rowindex"]?.trim() ?? this.mappedAttributes?.rowIndex); } @computed get ariaColSpan(): number | undefined { return asNumber(this.mappedAttributes?.colSpan); } @computed get ariaRowSpan(): number | undefined { return asNumber(this.mappedAttributes?.rowSpan); } @computed get ariaLive() { return this.rawAttributes["aria-live"]?.trim() ?? this.mappedAttributes?.ariaLive ?? "off"; } @computed get ariaExpanded(): boolean | undefined { return asBoolean(this.rawAttributes["aria-expanded"]?.trim() ?? this.mappedAttributes?.ariaExpanded); } @computed get htmlFor() { return this.node.htmlTag === "label" ? this.rawAttributes["for"]?.trim() : undefined; } @computed get htmlName() { return this.rawAttributes["name"]?.trim(); } @computed get htmlType() { return this.rawAttributes["type"]?.trim(); } @computed get htmlAlt() { return this.rawAttributes["alt"]?.trim(); } @computed get htmlTitle() { return this.rawAttributes["title"]?.trim(); } @computed get htmlPlaceholder() { return this.rawAttributes["placeholder"]?.trim(); } @computed get htmlSrc() { return this.node.htmlTag === "img" ? this.rawAttributes["src"]?.trim() : undefined; } @computed get htmlHref() { return this.node.htmlTag === "a" ? this.rawAttributes["href"]?.trim() : undefined; } @computed get htmlValue() { return this.rawProperties["value"]?.trim(); } @computed get htmlChecked() { return this.rawProperties["checked"]; } @computed get headers() { return this.mappedAttributes?.headers; } } export class NodeElement { readonly domNode: HTMLElement; readonly key: AomKey; readonly htmlTag: string; @observable isHidden: boolean; @observable isFocused: boolean; @observable isOpenInSidePanel: boolean; @observable containsFocus?: boolean; @observable isInline: boolean; @observable htmlParent: NodeElement | null = null; @observable htmlChildren: NonNullable<AOMElement>[] = []; private _rawAttributes = new RawNodeAttributes(); private _rawProperties = new RawNodeProperties(); readonly attributes: Aria = new Aria(this); readonly relations = new AomNodeRelations(this); readonly issuesObj = new AriaIssues(this); get id() { return this.attributes.id; } get role() { return this.attributes.role; } get issues() { return this.issuesObj.issues; } getRawAttributes() { return this._rawAttributes; } getRawProperties() { return this._rawProperties; } @computed get hasContent(): boolean { if (this.isHidden) { return false; } if (this.attributes.tabindex >= 0) { return true; } const needsAccessibleName: AriaRole[] = ["image", "img"]; if (needsAccessibleName.includes(this.role)) { return this.accessibleName.trim() !== ""; } const trueRoles: AriaRole[] = ["button", "link", "textbox", "radio", "checkbox", "combobox"]; if (trueRoles.includes(this.role)) { return true; } return this.children.some(x => x.hasContent); } @computed get ariaParent() { return this.relations.ariaOwnedBy.length > 0 ? this.relations.ariaOwnedBy[0] : this.htmlParent; } @computed get children() { const before = new TextElement({key: this.key + '::before', text: this.beforeContent, node: null}) return [...this.htmlChildren, ...this.relations.ariaOwns].filter(x => x.ariaParent === this); } @computed get hasCustomAccessibleName(): boolean { return ( !!this.relations.labelledBy.length || this.attributes.ariaLabel != null || (this.htmlTag === "img" && this.role !== "presentation" && this.attributes.htmlAlt != null) || (this.htmlTag === "img" && this.role !== "presentation" && this.attributes.htmlTitle != null) || this.attributes.htmlPlaceholder != null ); } private isComputingAccessibleName = false; // Accessible name is computed according to https://www.w3.org/TR/accname-1.1/#terminology get accessibleName(): string { try { if (this.isComputingAccessibleName) { return ""; } this.isComputingAccessibleName = true; if (this.isHidden) { return ""; } if (this.relations.ariaLabelledBy?.length) { return getAccessibleNameOf(this.relations.ariaLabelledBy).trim(); } if (this.attributes.ariaLabel != null) { return this.attributes.ariaLabel; } if (this.relations.labelledBy.length) { return getAccessibleNameOf(this.relations.labelledBy).trim(); } if (this.htmlTag === "img" && this.role !== "presentation" && this.attributes.htmlAlt != null) { return this.attributes.htmlAlt; } if (this.htmlTag === "img" && this.role !== "presentation" && this.attributes.htmlTitle != null) { return this.attributes.htmlTitle; } if (this.attributes.htmlPlaceholder != null) { return this.attributes.htmlPlaceholder; } if ( this.htmlTag === "input" && this.attributes.htmlType && this.attributes.htmlValue && ["submit", "button", "reset"].includes(this.attributes.htmlType) ) { return this.attributes.htmlValue; } const children = getAccessibleNameOf(this.children).trim(); if (children) { return children; } // if (this.attributes.htmlSrc != null) { // return this.attributes.htmlSrc; // } // if (this.attributes.htmlHref != null) { // return this.attributes.htmlHref; // } return ""; } finally { this.isComputingAccessibleName = false; } } constructor(node: HTMLElement) { this.domNode = node; this.htmlTag = node.tagName.toLowerCase(); this.key = getNodeKey(node); this.isHidden = isHidden(node); this.isFocused = isFocused(node); this.isInline = isInline(node); this.isOpenInSidePanel = false; } } export type AOMElement = TextElement | NodeElement | null | undefined;
the_stack
import { i18nMark } from "@lingui/react"; import { pipe } from "rxjs"; import { isObject as isObjectUtil, findNestedPropertyInObject, } from "#SRC/js/utils/Util"; import { JobOutput, FormError, UcrImageKind, JobSpec, ConstraintOperator, } from "./JobFormData"; import { OperatorTypes } from "./Constants"; type MetronomeValidators = Record<string, (formData: JobOutput) => FormError[]>; // TODO: can be removed once we're on TS3, as it seems flatMap-support has landed there. const flatMap = <A, B>(map: (x: A, i: number) => B[], xs: A[]): B[] => xs.reduce((acc, x, i) => acc.concat(map(x, i)), [] as B[]); const validation = <T>( isValid: (val: T) => boolean, defaultMessage: string ) => (path: (i: number) => string, values: T[], message = defaultMessage) => ( errors: FormError[] ) => errors.concat( flatMap( (value, index) => isValid(value) ? [] : [{ message, path: path(index).split(".") }], values ) ); const stringMsg = i18nMark("Must be a string"); const presentMsg = i18nMark("Must be present"); const isBoolean = validation<boolean | undefined>( (x) => x === undefined || typeof x === "boolean", i18nMark("Must be a boolean") ); const isNumber = validation<number | undefined>( (x) => x === undefined || typeof x === "number", i18nMark("Must be a number") ); const isObject = validation<object | undefined>( (x) => x === undefined || isObjectUtil(x), i18nMark("Must be an object") ); const isPresent = validation<any>( (x) => x !== undefined && x !== "", presentMsg ); const isString = validation<string | undefined>( (x) => x === undefined || typeof x === "string", stringMsg ); const isArray = validation<any[] | undefined>( (x) => x === undefined || Array.isArray(x), i18nMark("Constraints must be an array") ); const allUniq = validation<any[]>( (list) => new Set(list).size === list.length, i18nMark("All elements must be unique") ); const isUniqIn = <T>(list: T[]) => validation<T>( (el: T) => list.filter((x) => x === el).length < 2, i18nMark("Must be unique") ); const isOnlyWhitespace = (str: unknown): boolean => !`${str}`.replace(/\s/g, "").length; const ensureArray = <T>(something?: T[]): T[] => Array.isArray(something) ? something : []; export const MetronomeSpecValidators: MetronomeValidators = { validate(formData: JobOutput): FormError[] { const { run } = formData; const parameters = ensureArray(run.docker && run.docker.parameters); const constraints = ensureArray(run.placement && run.placement.constraints); // prettier-ignore return pipe( // IS BOOLEAN isBoolean(_ => "run.docker.forcePullImage", [run.docker && run.docker.forcePullImage]), isBoolean(_ => "run.docker.privileged", [run.docker && run.docker.privileged]), isBoolean(_ => "run.ucr.privileged", [run.ucr && run.ucr.privileged]), isBoolean(_ => "run.ucr.image.forcePull", [run.ucr && run.ucr.image&& run.ucr.image.forcePull]), // IS NUMBER isNumber(_ => "run.cpus", [run.cpus]), isNumber(_ => "run.disk", [run.disk]), isNumber(_ => "run.gpus", [run.gpus]), isNumber(_ => "run.maxLaunchDelay", [run.maxLaunchDelay]), isNumber(_ => "run.mem", [run.mem]), isNumber(_ => "run.restart.activeDeadlineSeconds", [run.restart && run.restart.activeDeadlineSeconds]), isNumber(_ => "run.taskKillGracePeriodSeconds", [run.taskKillGracePeriodSeconds]), // IS OBJECT isObject(_ => "labels", [formData.labels]), isObject(_ => "run.docker", [run.docker]), isObject(_ => "run.env", [run.env]), isObject(_ => "run.ucr", [run.ucr]), isObject(_ => "run.ucr.image", [run.ucr && run.ucr.image]), // IS PRESENT isPresent(_ => "id", [formData.id]), isPresent(_ => "run.cpus", [run.cpus]), isPresent(_ => "run.disk", [run.disk]), isPresent(_ => "run.mem", [run.mem]), isPresent(i => `labels.${i}.key`, Object.keys(formData.labels || [])), isPresent(i => `run.artifacts.${i}.uri`, (run.artifacts || []).map(_ => _.uri)), isPresent(i => `run.docker.parameters.${i}.key`, parameters.map(_ => _.key)), isPresent(i => `run.docker.parameters.${i}.value`, parameters.map(_ => _.value)), // IS STRING isString(_ => "id", [formData.id]), isString(_ => "run.cmd", [run.cmd]), isString(_ => "run.docker.image", [run.docker && run.docker.image]), isString(_ => "run.restart.policy", [run.restart && run.restart.policy]), isString(_ => "run.ucr.image.id", [run.ucr && run.ucr.image && run.ucr.image.id]), isString(_ => "run.user", [run.user]), isString(i => `labels.${i}.key`, Object.keys(formData.labels || [])), isString(i => `labels.${i}.value`, Object.values(formData.labels || [])), isString(i => `run.args.${i}`, run.args || []), isString(i => `run.artifacts.${i}.uri`, (run.artifacts || []).map(_ => _.uri)), isString(i => `run.docker.parameters.${i}.key`, parameters.map(_ => _.key)), isString(i => `run.docker.parameters.${i}.value`, parameters.map(_ => _.value)), isString(i => `job.run.placement.constraints.${i}.operator`, constraints.map(_ => _.operator)), isString(i => `job.run.placement.constraints.${i}.attribute`, constraints.map(_ => _.attribute)), isString(i => `job.run.placement.constraints.${i}.value`, constraints.map(_ => _.value)) // pipe only infers 10 steps, so we need a cast here )([]) as FormError[]; }, /** * Ensure ID contains only allowed characters. */ jobIdIsValid(formData: JobOutput): FormError[] { const jobId = findNestedPropertyInObject(formData, "id"); const jobIdRegex = /^([a-z0-9]([a-z0-9-]*[a-z0-9]+)*)([.][a-z0-9]([a-z0-9-]*[a-z0-9]+)*)*$/; const message = i18nMark( "ID must be at least 1 character and may only contain digits (`0-9`), dashes (`-`), and lowercase letters (`a-z`). The ID may not begin or end with a dash" ); if (jobId == undefined) { return []; } // we're currently testing for a trailing "-" separately because the regex crashes // browsers for longer strings that end with a "-". return jobId && !jobId.endsWith("-") && jobIdRegex.test(jobId) ? [] : [{ path: ["id"], message }]; }, /** * Ensure that the user has provided either one of `cmd` or `args`, or a container image field. * Ensure that the user has not provided both `cmd` and `args`. */ containsCmdArgsOrContainer(job: JobOutput): FormError[] { const hasCmd = findNestedPropertyInObject(job, "run.cmd"); const hasArgs = findNestedPropertyInObject(job, "run.args") && (job.run.args as string[]).length; // Dont accept both `args` and `cmd` if (hasCmd && hasArgs) { const notBothMessage = i18nMark( "Please specify only one of `cmd` or `args`" ); return [ { path: ["run", "cmd"], message: notBothMessage, }, { path: ["run", "args"], message: notBothMessage, }, ]; } // Check if we have either of them if (hasCmd || hasArgs) { return []; } // Additional checks if we have container const docker = findNestedPropertyInObject(job, "run.docker"); const ucr = findNestedPropertyInObject(job, "run.ucr"); if (docker || ucr) { // Check if it specifies a docker container with image if (docker && docker.image) { return []; } // Check if it specifies a UCR container with image and image.id if (ucr && ucr.image && ucr.image.id) { return []; } } const message = i18nMark( "You must specify a command, an argument or a container with an image" ); const containerImageErrorPath = job.run.ucr ? ["run", "ucr", "image", "id"] : job.run.docker ? ["run", "docker", "image"] : []; return [ { path: ["run", "cmd"], message }, { path: ["run", "args"], message }, { path: containerImageErrorPath, message }, ]; }, /** * Ensure there is a container image if a container is specified */ mustContainImageOnDockerOrUCR(formData: JobOutput) { const docker = findNestedPropertyInObject(formData, "run.docker"); if (docker && !docker.image) { return [ { path: ["run", "docker", "image"], message: i18nMark( "Must be specified when using the Docker Engine runtime" ), }, ]; } const ucr = findNestedPropertyInObject(formData, "run.ucr"); if (ucr && (!ucr.image || !ucr.image.id)) { return [ { path: ["run", "ucr", "image", "id"], message: i18nMark("Must be specified when using UCR"), }, ]; } return []; }, /** * Ensure GPUs are used only with UCR */ gpusOnlyWithUCR(formData: JobOutput) { const gpus = findNestedPropertyInObject(formData, "run.gpus"); const docker = findNestedPropertyInObject(formData, "run.docker"); if ((gpus || gpus === 0) && docker) { return [ { path: ["run", "gpus"], message: i18nMark("GPUs are only available with UCR"), }, ]; } return []; }, oneOfUcrOrDocker(formData: JobOutput) { const docker = findNestedPropertyInObject(formData, "run.docker"); const ucr = findNestedPropertyInObject(formData, "run.ucr"); if (docker && ucr) { return [ { path: ["run", "docker"], message: i18nMark("Only one of UCR or Docker is allowed"), }, { path: ["run", "ucr"], message: i18nMark("Only one of UCR or Docker is allowed"), }, ]; } return []; }, checkTypesOfUcrProps(formData: JobOutput) { const ucr = findNestedPropertyInObject(formData, "run.ucr"); const errors: FormError[] = []; if (ucr == undefined) { return errors; } const kind = findNestedPropertyInObject(formData, "run.ucr.image.kind"); if ( kind != undefined && kind !== UcrImageKind.Docker && kind !== UcrImageKind.Appc ) { errors.push({ path: ["run", "ucr", "image", "kind"], message: i18nMark("Image kind must be one of `docker` or `appc`"), }); } return errors; }, valuesAreWithinRange(formData: JobOutput) { const cpus = findNestedPropertyInObject(formData, "run.cpus"); const mem = findNestedPropertyInObject(formData, "run.mem"); const disk = findNestedPropertyInObject(formData, "run.disk"); const errors: any[] = []; if (cpus != undefined && typeof cpus === "number" && cpus < 0.01) { errors.push({ path: ["run", "cpus"], message: i18nMark("Minimum value is 0.01"), }); } if (mem != undefined && typeof mem === "number" && mem < 32) { errors.push({ path: ["run", "mem"], message: i18nMark("Minimum value is 32"), }); } if (disk != undefined && typeof disk === "number" && disk < 0) { errors.push({ path: ["run", "disk"], message: i18nMark("Minimum value is 0"), }); } return errors; }, gpusWithinRange(formData: JobOutput) { const gpus = findNestedPropertyInObject(formData, "run.gpus"); if (gpus && typeof gpus === "number" && gpus < 0) { return [ { path: ["run", "gpus"], message: i18nMark("Minimum value is 0"), }, ]; } return []; }, noEmptyArgs(formData: JobOutput) { const args = formData.run.args; const errors: FormError[] = []; if (args && Array.isArray(args)) { args.forEach((arg, index) => { if (arg === "" || arg == undefined) { errors.push({ path: ["run", "args", `${index}`], message: i18nMark("Arg cannot be empty"), }); } }); } return errors; }, argsUsedOnlyWithDocker(formData: JobOutput) { const args = formData.run.args; const docker = formData.run.docker; if (args && !docker) { return [ { path: ["run", "args"], message: i18nMark("Args can only be used with Docker"), }, ]; } return []; }, noDuplicateArgs(formData: JobOutput) { const args = formData.run && formData.run.args; const errors: FormError[] = []; const map: { [key: string]: number } = {}; const dupIndex: number[] = []; if (args && Array.isArray(args)) { args.forEach((arg, index) => { if (!map.hasOwnProperty(arg)) { map[arg] = index; return; } if (dupIndex.length === 0) { dupIndex.push(map[arg]); } dupIndex.push(index); }); dupIndex.forEach((errorIndex) => { errors.push({ path: ["run", "args", `${errorIndex}`], message: i18nMark("No duplicate args"), }); }); } return errors; }, noDuplicateParams(formData: JobOutput) { const docker = formData.run && formData.run.docker; const errors: FormError[] = []; const map: { [key: string]: number } = {}; const dupIndex: number[] = []; if (docker && docker.parameters && Array.isArray(docker.parameters)) { docker.parameters.forEach((param, index) => { const paramId = `${param.key}-${param.value}`; if (!map.hasOwnProperty(paramId)) { map[paramId] = index; return; } if (dupIndex.length === 0) { dupIndex.push(map[paramId]); } dupIndex.push(index); }); dupIndex.forEach((errorIndex) => { errors.push({ path: ["run", "docker", "parameters", `${errorIndex}`], message: i18nMark("No duplicate parameters"), }); }); } return errors; }, scheduleHasId(formData: JobOutput) { const { schedules } = formData; if ( schedules && Array.isArray(schedules) && schedules.length && !schedules[0].id ) { return [ { path: ["schedules", "0", "id"], message: i18nMark("ID is required"), }, ]; } return []; }, scheduleHasCron(formData: JobOutput) { const { schedules } = formData; if ( schedules && Array.isArray(schedules) && schedules.length && !schedules[0].cron ) { return [ { path: ["schedules", "0", "cron"], message: i18nMark("CRON schedule is required"), }, ]; } return []; }, scheduleIdIsValid(formData: JobOutput) { const { schedules } = formData; const idRegex = /^([a-z0-9][a-z0-9\\-]*[a-z0-9]+)$/; const message = i18nMark( "ID must be at least 2 characters and may only contain digits (`0-9`), dashes (`-`), and lowercase letters (`a-z`). The ID may not begin or end with a dash" ); if (!schedules || !Array.isArray(schedules) || !schedules.length) { return []; } const schedule = schedules[0]; if (schedule.id && typeof schedule.id !== "string") { return [ { path: ["schedules", "0", "id"], message: i18nMark("Schedule ID must be a string"), }, ]; } return schedule && schedule.id && idRegex.test(schedule.id) ? [] : [{ path: ["schedules", "0", "id"], message }]; }, scheduleStartingDeadlineIsValid(formData: JobOutput) { const { schedules } = formData; const errors: any[] = []; if ( schedules && Array.isArray(schedules) && schedules.length && schedules[0].startingDeadlineSeconds != undefined ) { if (typeof schedules[0].startingDeadlineSeconds !== "number") { errors.push({ path: ["schedules", "0", "startingDeadlineSeconds"], message: i18nMark("Starting deadline must be a number"), }); } if (schedules[0].startingDeadlineSeconds < 1) { errors.push({ path: ["schedules", "0", "startingDeadlineSeconds"], message: i18nMark("Minimum value is 1"), }); } } return errors; }, constraintsAreArray(formData: JobOutput): FormError[] { const path = "run.placement.constraints"; return isArray((_) => path, [ findNestedPropertyInObject(formData, `job.${path}`), ])([]); }, }; function volumesAreComplete(formData: JobSpec) { const volumes = findNestedPropertyInObject(formData, "job.run.volumes"); const errors: FormError[] = []; if (volumes && Array.isArray(volumes)) { volumes.forEach((volume, index) => { if ( (volume.containerPath == null || volume.containerPath === "") && (volume.hostPath == null || volume.hostPath === "") && (volume.mode == null || volume.mode === "") ) { return; } if (volume.containerPath == null || volume.containerPath === "") { errors.push({ path: ["run", "volumes", `${index}`, "containerPath"], message: i18nMark("Container path is required"), }); } if (!volume.hasOwnProperty("secret")) { if (volume.hostPath == null || volume.hostPath === "") { errors.push({ path: ["run", "volumes", `${index}`, "hostPath"], message: i18nMark("Host path is required"), }); } if (volume.mode == null || volume.mode === "") { errors.push({ path: ["run", "volumes", `${index}`, "mode"], message: i18nMark("Mode is required"), }); } } }); } return errors; } function checkVolumePropertyTypes(formData: JobSpec) { const volumes = findNestedPropertyInObject(formData, "job.run.volumes"); const errors: FormError[] = []; if (volumes && Array.isArray(volumes)) { volumes.forEach((volume, index) => { if ( (volume.containerPath == null || volume.containerPath === "") && (volume.hostPath == null || volume.hostPath === "") && (volume.mode == null || volume.mode === "") ) { return; } if (typeof volume.containerPath !== "string") { errors.push({ path: ["run", "volumes", `${index}`, "containerPath"], message: stringMsg, }); } if (!volume.hasOwnProperty("secret")) { if (typeof volume.hostPath !== "string") { errors.push({ path: ["run", "volumes", `${index}`, "hostPath"], message: stringMsg, }); } if (typeof volume.mode !== "string") { errors.push({ path: ["run", "volumes", `${index}`, "mode"], message: stringMsg, }); } else if (volume.mode !== "RO" && volume.mode !== "RW") { errors.push({ path: ["run", "volumes", `${index}`, "mode"], message: i18nMark("Mode must be one of: RO, RW"), }); } } }); } return errors; } export function constraintOperatorsArePermitted(formData: JobSpec) { const path = "job.run.placement.constraints"; const operators = (findNestedPropertyInObject(formData, path) || []).map( (_: any) => _.operator ); return validation( (op) => Object.values(ConstraintOperator).includes(op) || op === "EQ", i18nMark("Operator must be one of: IS, LIKE, UNLIKE, EQ") )( (i) => `${path}.${i}.operator`, operators )([]); } export function constraintsAreComplete(formData: JobSpec) { const placement = findNestedPropertyInObject(formData, "job.run.placement"); const errors: FormError[] = []; if ( placement && placement.constraints && Array.isArray(placement.constraints) ) { placement.constraints.forEach((constraint: any, i: number) => { const { operator, attribute, value } = constraint; if (!(attribute || operator || value)) { return; } if (operator == null || operator === "" || isOnlyWhitespace(operator)) { errors.push({ path: ["run", "placement", "constraints", `${i}`, "operator"], message: i18nMark("Operator is required"), }); } if ( attribute == null || attribute === "" || isOnlyWhitespace(attribute) ) { errors.push({ path: ["run", "placement", "constraints", `${i}`, "attribute"], message: i18nMark("Field is required"), }); } if ( ((OperatorTypes as any)[operator] || {}).requiresValue && (value == null || value === "" || isOnlyWhitespace(value)) ) { errors.push({ path: ["run", "placement", "constraints", `${i}`, "value"], message: i18nMark("Value is required"), }); } }); } return errors; } // We sometimes need to validate the spec instead of the formOutput to make sure // that e.g. two ENV-params don't have the same key. we need to allow for // that UX-wise, as if you have `DB_HOST` and type `DB_HOSTNAME` in the next // field you'd run into trouble when using a POJO as the backing model. export function validateSpec(jobSpec: JobSpec): FormError[] { const run = jobSpec.job.run || {}; const envsMsg = i18nMark( "Cannot have multiple environment variables with the same key" ); const labels = (jobSpec.job.labels || []).map(([k]) => k); const labelsMsg = i18nMark("Cannot have multiple labels with the same key"); const envVarsErrors: FormError[] = []; const map: { [key: string]: number[] } = {}; (run.env || []).forEach(([k, v], i) => { if (k) { if (map[k] != null) { map[k].push(i); } else { map[k] = [i]; } } if (v && !isObjectUtil(v)) { if (k == null || k === "") { envVarsErrors.push({ path: ["run", "env", `${i}`], message: presentMsg, }); } if (typeof v !== "string") { envVarsErrors.push({ path: ["run", "env", k, "value", `${i}`], message: stringMsg, }); } } if (k && (v == null || v === "")) { envVarsErrors.push({ path: ["run", "env", k, "value", `${i}`], message: presentMsg, }); } }); Object.keys(map).forEach((envVarKey) => { if (map[envVarKey].length > 1) { map[envVarKey].forEach((index) => { envVarsErrors.push({ path: ["run", "env", `${index}`], message: envsMsg, }); }); } }); const constraintErrors = constraintsAreComplete(jobSpec).concat( constraintOperatorsArePermitted(jobSpec) ); const volumesErrors = volumesAreComplete(jobSpec).concat( checkVolumePropertyTypes(jobSpec) ); return pipe( allUniq((_) => "labels", [labels], labelsMsg), isUniqIn(labels)((i) => `labels.${i}`, labels, labelsMsg) )([]) .concat(envVarsErrors) .concat(volumesErrors) .concat(constraintErrors); }
the_stack
import React, { useState } from 'react'; import { flowResult } from 'mobx'; import { Observer, observer } from 'mobx-react-lite'; import { Button, Drawer, Input, message, Modal, Popover, Select, Space, Switch, Table, Tabs, Tooltip } from 'antd'; // @Components import { ActionLink, CenteredError, CenteredSpin, CodeInline, CodeSnippet, handleError } from '../components'; import { getCurlDocumentation, getEmbeddedHtml, getNPMDocumentation } from '../../commons/api-documentation'; import TagsInput from '../TagsInput/TagsInput'; import { LabelWithTooltip } from 'ui/components/LabelWithTooltip/LabelWithTooltip'; // @Store import { apiKeysStore, UserApiKey } from 'stores/apiKeys'; // @Services import { useServices } from 'hooks/useServices'; // @Icons import CodeFilled from '@ant-design/icons/lib/icons/CodeFilled'; import PlusOutlined from '@ant-design/icons/lib/icons/PlusOutlined'; import DeleteFilled from '@ant-design/icons/lib/icons/DeleteFilled'; import ExclamationCircleOutlined from '@ant-design/icons/lib/icons/ExclamationCircleOutlined'; // @Utils import { copyToClipboard as copyToClipboardUtility } from '../../commons/utils'; // @Hooks import useLoader from 'hooks/useLoader'; // @Styles import './ApiKeys.less'; import { default as JitsuClientLibraryCard, jitsuClientLibraries } from '../JitsuClientLibrary/JitsuClientLibrary'; import { Code } from '../Code/Code'; /** * What's displayed as loading? * - number - index of key, * - "NEW" - new button, * - null - nothing */ type LoadingState = | number | 'NEW' | null; function generateNewKeyWithConfirmation(onConfirm: () => void) { Modal.confirm({ title: 'Please confirm deletion of destination', icon: <ExclamationCircleOutlined />, content: "Are you sure you want to delete generate new key? Previously generated key will be lost and you'll need to reconfigure ALL clients", okText: 'Generate new key', cancelText: 'Cancel', onOk: onConfirm, onCancel: () => {} }); } const ApiKeysComponent: React.FC = () => { const keys = apiKeysStore.apiKeys; const [loading, setLoading] = useState<LoadingState>(null); const [documentationDrawerKey, setDocumentationDrawerKey] = useState<UserApiKey>(null); const handleDeleteKey = (key: UserApiKey): Promise<void> => { return flowResult(apiKeysStore.deleteApiKey(key)); } const handleEditKeys = async(newKeys: UserApiKey | UserApiKey[], loading: LoadingState) => { setLoading(loading); try { await flowResult(apiKeysStore.editApiKeys(newKeys)); } catch (e) { message.error("Can't generate new token: " + e.message); console.log(e); } finally { setLoading(null); } } const copyToClipboard = (value) => { copyToClipboardUtility(value); message.success('Key copied to clipboard'); } const editNote = async(rowIndex, val?) => { let note = prompt( 'Enter key description (set to empty to delete)', val || '' ); if (note !== null && note !== undefined) { const updatedKey = { ...keys[rowIndex] } updatedKey.comment = note === '' ? undefined : note; await handleEditKeys(updatedKey, rowIndex); } }; const header = ( <div className="flex flex-row mb-5 items-start justify between"> <div className="flex-grow flex text-secondaryText"> Jitsu supports many <Popover trigger="click" placement="bottom" title={null} content={<div className="w-96 flex-wrap flex justify-center"> {Object.values(jitsuClientLibraries).map(props => <div className="mx-3 my-4" key={props.name}><JitsuClientLibraryCard {...props} /></div>)} </div>}>{'\u00A0'}<a>languages and frameworks</a>{'\u00A0'}</Popover>! </div> <div className="flex-shrink"> <Button type="primary" size="large" icon={<PlusOutlined />} loading={'NEW' === loading} onClick={async() => { setLoading( 'NEW' ); try { await flowResult(apiKeysStore.generateAddApiKey()); message.info('New Api key has been saved!'); } catch (error) { message.error(`Failed to add new token: ${error.message || error}`) } finally { setLoading( null ); } }} >Generate New Key</Button> </div> </div> ); const columns = [ { width: '250px', className: 'api-keys-column-id', dataIndex: 'uid', key: 'uid', render: (text, row: UserApiKey, index) => { return ( <> <span className="font-mono text-sm">{text}</span> {row.comment ? ( <div className="text-secondaryText"> <b>Note</b>: {row.comment} ( <a onClick={async() => editNote(index, row.comment)}>edit</a> ) </div> ) : ( <> <div> (<a onClick={async() => editNote(index)}>add note</a>) </div> </> )} </> ); }, title: ( <LabelWithTooltip documentation={'Unique ID of the key'} render="ID" /> ) }, { width: '250px', className: 'api-keys-column-js-auth', dataIndex: 'jsAuth', key: 'jsAuth', render: (text, row, index) => { return ( <span> <Input className={'api-keys-key-input'} type="text" value={text} /> <Space> <ActionLink onClick={() => copyToClipboard(text)}> Copy To Clipboard </ActionLink> <Observer> {() => ( <ActionLink onClick={() => { generateNewKeyWithConfirmation(() => { const updatedKey = { ...keys[index] }; updatedKey.jsAuth = apiKeysStore.generateApiToken('js'); handleEditKeys(updatedKey, index); message.info('New key has been generated and saved'); }); }} > Generate New Key </ActionLink> )} </Observer> </Space> </span> ); }, title: ( <LabelWithTooltip documentation={ <> Client Api Key. Should be used with{' '} <a href="https://jitsu.com/docs/sending-data/javascript-reference"> JS client </a> . </> } render="Client Secret" /> ) }, { width: '250px', className: 'api-keys-column-s2s-auth', dataIndex: 'serverAuth', key: 'serverAuth', render: (text, row, index) => { return ( <span> <Input className="api-keys-key-input" type="text" value={text} /> <Space> <ActionLink onClick={() => copyToClipboard(text)}> Copy To Clipboard </ActionLink> <Observer> {() => ( <ActionLink onClick={() => { generateNewKeyWithConfirmation(() => { const updatedKey = { ...keys[index] }; updatedKey.serverAuth = apiKeysStore.generateApiToken('s2s'); handleEditKeys(updatedKey, index); message.info('New key has been generated and saved'); }); }} > Generate New Key </ActionLink> )} </Observer> </Space> </span> ); }, title: ( <LabelWithTooltip documentation={ <> Server Api Key. Should be used with{' '} <a href="https://docs.eventnative.org/api">backend Api calls</a> . </> } render="Server Secret" /> ) }, { className: 'api-keys-column-origins', dataIndex: 'origins', key: 'origins', render: (text, row, index) => { return ( <span> <TagsInput newButtonText="Add Origin" value={keys[index].origins} onChange={(value) => { const updatedKey = { ...keys[index] }; updatedKey.origins = [...value]; handleEditKeys(updatedKey, index); message.info('New origin has been added and saved'); }} /> </span> ); }, title: ( <LabelWithTooltip documentation={ <> JavaScript origins. If set, only calls from those hosts will be accepted. Wildcards are supported as (*.abc.com). If you want to whitelist domain abc.com and all subdomains, add abc.com and *.abc.com. If list is empty, traffic will be accepted from all domains </> } render="Origins" /> ) }, { width: '140px', className: 'api-keys-column-actions', title: 'Actions', dataIndex: 'actions', render: (text, row: UserApiKey, index) => { return ( <> <Tooltip trigger={['hover']} title={'Show integration documentation'} > <a onClick={() => setDocumentationDrawerKey(row)}><CodeFilled /></a> </Tooltip> <Tooltip trigger={['hover']} title="Delete key"> <a onClick={() => { Modal.confirm({ title: 'Are you sure?', content: 'Key will be deleted completely. There will be no way to restore it!', onOk: () => handleDeleteKey(keys[index]), onCancel: () => {} }); }} > <DeleteFilled /> </a> </Tooltip> </> ); } } ]; return ( <> {header} <Table pagination={false} className="api-keys-table" columns={columns} dataSource={keys.map((t) => { return { ...t, key: t.uid }; })} /> <Drawer width="70%" visible={!!documentationDrawerKey} onClose={() => setDocumentationDrawerKey(null)}> {documentationDrawerKey && <KeyDocumentation token={documentationDrawerKey} />} </Drawer> </> ); } export function getDomainsSelectionByEnv(env: string) { return env === 'heroku' ? [location.protocol + '//' + location.host] : []; } type KeyDocumentationProps = { token: UserApiKey; displayDomainDropdown?: boolean; }; export const KeyDocumentation: React.FC<KeyDocumentationProps> = function({ token, displayDomainDropdown = true }) { const [segment, setSegmentEnabled] = useState<boolean>(false); const services = useServices(); const staticDomains = getDomainsSelectionByEnv(services.features.environment); console.log( `As per ${services.features.environment} available static domains are: ` + staticDomains ); const [selectedDomain, setSelectedDomain] = useState<string | null>( staticDomains.length > 0 ? staticDomains[0] : null ); const [error, domains] = services.features.enableCustomDomains ? useLoader(async() => { const result = await services.storageService.get( 'custom_domains', services.activeProject.id ); const customDomains = result?.domains?.map((domain) => 'https://' + domain.name) || []; const newDomains = [...customDomains, 'https://t.jitsu.com']; setSelectedDomain(newDomains[0]); return newDomains; }) : [null, staticDomains]; if (error) { handleError(error, 'Failed to load data from server'); return <CenteredError error={error} />; } else if (!domains) { return <CenteredSpin />; } console.log(`Currently selected domain is: ${selectedDomain}`); const exampleSwitches = ( <div className="api-keys-doc-embed-switches"> <Space> <LabelWithTooltip documentation={ <> Check if you want to intercept events from Segment ( <a href="https://jitsu.com/docs/sending-data/js-sdk/snippet#intercepting-segment-events"> Read more </a> ) </> } render="Intercept Segment events" /> <Switch size="small" checked={segment} onChange={() => setSegmentEnabled(!segment)} /> </Space> </div> ); const documentationDomain = selectedDomain || services.features.jitsuBaseUrl || 'REPLACE_WITH_JITSU_DOMAIN'; return ( <Tabs className="api-keys-documentation-tabs pt-8" defaultActiveKey="1" tabBarExtraContent={ <> {domains.length > 0 && displayDomainDropdown && ( <> <LabelWithTooltip documentation="Domain" render="Domain" />:{' '} <Select defaultValue={domains[0]} onChange={(value) => setSelectedDomain(value)} > {domains.map((domain) => { return <Select.Option value={domain}>{domain.replace('https://', '')}</Select.Option>; })} </Select> </> )} </> } > <Tabs.TabPane tab="Embed JavaScript" key="1"> <p className="api-keys-documentation-tab-description"> Easiest way to start tracking events within your web app is to add following snippet to <CodeInline>&lt;head&gt;</CodeInline> section of your html file.{' '} <a href="https://jitsu.com/docs/sending-data/js-sdk/">Read more</a>{' '} about JavaScript integration on our documentation website </p> <Code className="bg-bgSecondary py-3 px-5 rounded-xl mb-2" language="html"> {getEmbeddedHtml(segment, token.jsAuth, documentationDomain)} </Code> {exampleSwitches} </Tabs.TabPane> <Tabs.TabPane tab="Use NPM/YARN" key="2"> <p className="api-keys-documentation-tab-description"> Use <CodeInline>npm install --save @jitsu/sdk-js</CodeInline> or{' '} <CodeInline>yarn add @jitsu/sdk-js</CodeInline>. Read more{' '} <a href="https://jitsu.com/docs/sending-data/js-sdk/package"> about configuration properties </a> </p> <Code className="bg-bgSecondary py-3 px-5 rounded-xl mb-2" language="javascript"> {getNPMDocumentation(token.jsAuth, documentationDomain)} </Code> </Tabs.TabPane> <Tabs.TabPane tab="Server to server" key="3"> <p className="api-keys-documentation-tab-description"> Events can be send directly to Api end-point. In that case, server secret should be used. Please, see curl example: </p> <Code className="bg-bgSecondary py-3 px-5 rounded-xl mb-2" language="bash"> {getCurlDocumentation(token.serverAuth, documentationDomain)} </Code> </Tabs.TabPane> </Tabs> ); }; const ApiKeys = observer(ApiKeysComponent); ApiKeys.displayName = 'ApiKeys'; export default ApiKeys;
the_stack
import { FTIndexType, FTSchemaField, FTCreateParameters, FTSearchParameters, FTAggregateParameters, FTFieldType, FTFieldOptions, FTSugAddParameters, FTSugGetParameters, FTSpellCheck } from "./redisearch.types"; import { CommandData } from "../module.base"; export class SearchCommander { /** * Creating an index with a given spec * @param index The index of the schema * @param indexType The index type of the schema * @param schemaFields The filter set after the 'SCHEMA' argument * @param parameters The additional parameters of the spec * @returns 'OK' or error */ create(index: string, indexType: FTIndexType, schemaFields: FTSchemaField[], parameters?: FTCreateParameters): CommandData { let args: string[] = [index, 'ON', indexType] if(parameters !== undefined) { if(parameters.prefix !== undefined) { args.push('PREFIX') if(parameters.prefix.num !== undefined) { args.push(`${parameters.prefix.num}`) } else if(Array.isArray(parameters.prefix.prefixes)) { args.push(`${parameters.prefix.prefixes.length}`) } else { args.push("1") } args = args.concat(parameters.prefix.prefixes); } if(parameters.filter !== undefined) args = args.concat(['FILTER', parameters.filter]) if(parameters.language !== undefined) args = args.concat(['LANGUAGE', parameters.language]); if(parameters.languageField !== undefined) args = args.concat(['LANGUAGE_FIELD', parameters.languageField]) if(parameters.score !== undefined) args = args.concat(['SCORE', parameters.score]) if(parameters.scoreField !== undefined) args = args.concat(['SCORE_FIELD', parameters.scoreField]) if(parameters.payloadField !== undefined) args = args.concat(['PAYLOAD_FIELD', parameters.payloadField]) if(parameters.maxTextFields !== undefined) args = args.concat(['MAXTEXTFIELDS', `${parameters.maxTextFields}`]) if(parameters.temporary !== undefined) args = args.concat(['TEMPORARY', `${parameters.temporary}`]) if(parameters.noOffsets === true) args.push('NOOFFSETS') if(parameters.nohl === true) args.push('NOHL') if(parameters.noFields === true) args.push('NOFIELDS') if(parameters.noFreqs === true) args.push('NOFREQS') if(parameters.stopwords !== undefined) { args.push('STOPWORDS') if(parameters.stopwords.num !== undefined) { args.push(`${parameters.stopwords.num}`) } else if(Array.isArray(parameters.stopwords.stopwords)) { args.push(`${parameters.stopwords.stopwords.length}`) } else { args.push("1") } args = args.concat(parameters.stopwords.stopwords); } if(parameters.skipInitialScan === true) args.push('SKIPINITIALSCAN') } args.push('SCHEMA'); for(const field of schemaFields) { args.push(field.name) if(field.as !== undefined) args = args.concat(['AS', field.as]) args.push(field.type); if(field.nostem === true) args.push('NOSTEM'); if(field.weight !== undefined) args = args.concat(['WEIGHT', `${field.weight}`]) if(field.phonetic !== undefined) args = args.concat(['PHONETIC', field.phonetic]) if(field.separator !== undefined) args = args.concat(['SEPARATOR', field.separator]) if(field.sortable === true) args.push('SORTABLE') if(field.noindex === true) args.push('NOINDEX') if(field.unf === true) args.push('UNF') if(field.caseSensitive === true) args.push('CASESENSITIVE') } return { command: 'FT.CREATE', args: args } } /** * Searching the index with a textual query * @param index The index * @param query The query * @param parameters The additional optional parameter * @returns Array reply, where the first element is the total number of results, and then pairs of document id, and a nested array of field/value. */ search(index: string, query: string, parameters?: FTSearchParameters): CommandData { let args: string[] = [index, query]; if(parameters !== undefined) { if(parameters.noContent === true) args.push('NOCONTENT') if(parameters.verbatim === true) args.push('VERBATIM') if(parameters.noStopWords === true) args.push('NOSTOPWORDS') if(parameters.withScores === true) args.push('WITHSCORES') if(parameters.withPayloads === true) args.push('WITHPAYLOADS') if(parameters.withSortKeys === true) args.push('WITHSORTKEYS') if(parameters.filter !== undefined) { for(const filterItem of parameters.filter) { args = args.concat(['FILTER', filterItem.field, `${filterItem.min}`, `${filterItem.max}`]) } } if(parameters.geoFilter !== undefined) args = args.concat([ 'GEOFILTER', parameters.geoFilter.field, `${parameters.geoFilter.lon}`, `${parameters.geoFilter.lat}`, `${parameters.geoFilter.radius}`, parameters.geoFilter.measurement ]) if(parameters.inKeys !== undefined) { args.push('INKEYS') if(parameters.inKeys.num !== undefined) { args.push(`${parameters.inKeys.num}`) } else if(Array.isArray(parameters.inKeys.keys)) { args.push(`${parameters.inKeys.keys.length}`) } else { args.push("1") } args = args.concat(parameters.inKeys.keys); } if(parameters.inFields !== undefined) { args.push('INFIELDS'); if(parameters.inFields.num !== undefined) { args.push(`${parameters.inFields.num}`) } else if(Array.isArray(parameters.inFields.fields)) { args.push(`${parameters.inFields.fields.length}`) } else { args.push("1") } args = args.concat(parameters.inFields.fields); } if(parameters.return !== undefined) { args = args.concat([ 'RETURN', parameters.return.num !== undefined ? `${parameters.return.num}` : `${parameters.return.fields.length}`, ]).concat( ...parameters.return.fields.map( (field) => { if(field.as !== undefined) { return [field.field, 'AS', field.as]; } return [field.field]; }, ) ); } if(parameters.summarize !== undefined) { args.push('SUMMARIZE') if(parameters.summarize.fields !== undefined) { args.push('FIELDS') if(parameters.summarize.fields.num !== undefined) { args.push(`${parameters.summarize.fields.num}`) } else if(Array.isArray(parameters.summarize.fields.fields)) { args.push(`${parameters.summarize.fields.fields.length}`) } else { args.push("1") } args = args.concat(parameters.summarize.fields.fields) } if(parameters.summarize.frags !== undefined) args = args.concat(['FRAGS', `${parameters.summarize.frags}`]) if(parameters.summarize.len !== undefined) args = args.concat(['LEN', `${parameters.summarize.len}`]) if(parameters.summarize.separator !== undefined) args = args.concat(['SEPARATOR', parameters.summarize.separator]) } if(parameters.highlight !== undefined) { args.push('HIGHLIGHT') if(parameters.highlight.fields !== undefined) { args.push('FIELDS'); if(parameters.highlight.fields.num !== undefined) { args.push(`${parameters.highlight.fields.num}`) } else if(Array.isArray(parameters.highlight.fields.fields)) { args.push(`${parameters.highlight.fields.fields.length}`) } else { args.push("1") } args = args.concat(parameters.highlight.fields.fields); } if(parameters.highlight.tags !== undefined) { args.push('TAGS') args = args.concat([parameters.highlight.tags.open, parameters.highlight.tags.close]) } } if(parameters.slop !== undefined) args = args.concat(['SLOP', `${parameters.slop}`]) if(parameters.inOrder === true) args.push('INORDER') if(parameters.language !== undefined) args = args.concat(['LANGUAGE', parameters.language]) if(parameters.expander !== undefined) args = args.concat(['EXPANDER', parameters.expander]) if(parameters.scorer !== undefined) args = args.concat(['SCORER', parameters.scorer]) if(parameters.explainScore === true) args.push('EXPLAINSCORE') if(parameters.payload) args = args.concat(['PAYLOAD', parameters.payload]) if(parameters.sortBy !== undefined) args = args.concat(['SORTBY', parameters.sortBy.field, parameters.sortBy.sort]) if(parameters.limit !== undefined) args = args.concat(['LIMIT', `${parameters.limit.first}`, `${parameters.limit.num}`]) } return { command: 'FT.SEARCH', args: args } } /** * Runs a search query on an index, and performs aggregate transformations on the results, extracting statistics etc from them * @param index The index * @param query The query * @param parameters The additional optional parameters * @returns Array Response. Each row is an array and represents a single aggregate result */ aggregate(index: string, query: string, parameters?: FTAggregateParameters): CommandData { let args: string[] = [index, query]; if(parameters !== undefined) { if(parameters.load !== undefined) { args.push('LOAD') if(parameters.load.nargs !== undefined) args.push(parameters.load.nargs); if(parameters.load.properties !== undefined) parameters.load.properties.forEach(property => { args.push(property); }) } if(parameters.apply !== undefined) { parameters.apply.forEach(apply => { args.push('APPLY'); args.push(apply.expression); if(apply.as) args = args.concat(['AS', apply.as]); }) } if(parameters.groupby !== undefined) { args.push('GROUPBY') if(parameters.groupby.nargs !== undefined) args.push(parameters.groupby.nargs); if(parameters.groupby.properties !== undefined) { parameters.groupby.properties.forEach((property) => { args.push(property); }) } } if(parameters.reduce !== undefined) { parameters.reduce.forEach(reduce => { args.push('REDUCE') if(reduce.function !== undefined) args.push(reduce.function); if(reduce.nargs !== undefined) args.push(reduce.nargs); if(reduce.args) reduce.args.forEach(arg => { args.push(arg); }) if(reduce.as !== undefined) args = args.concat(['AS', reduce.as]); }) } if(parameters.sortby !== undefined) { args.push('SORTBY') if(parameters.sortby.nargs !== undefined) args.push(parameters.sortby.nargs); if(parameters.sortby.properties) parameters.sortby.properties.forEach(property => { args.push(property.property); args.push(property.sort); }) if(parameters.sortby.max !== undefined) args = args.concat(['MAX', `${parameters.sortby.max}`]); } if(parameters.expressions !== undefined) { parameters.expressions.forEach(expression => { args.push('APPLY'); args.push(expression.expression); if(expression.as) args = args.concat(['AS', expression.as]); }) } if(parameters.limit !== undefined) { args.push('LIMIT') if(parameters.limit.offset !== undefined) args.push(parameters.limit.offset) if(parameters.limit.numberOfResults !== undefined) args.push(`${parameters.limit.numberOfResults}`); } } return { command: 'FT.AGGREGATE', args: args } } /** * Retrieving the execution plan for a complex query * @param index The index * @param query The query * @returns Returns the execution plan for a complex query */ explain(index: string, query: string): CommandData { return { command: 'FT.EXPLAIN', args: [index, query] } } /** * Retrieving the execution plan for a complex query but formatted for easier reading without using redis-cli --raw * @param index The index * @param query The query * @returns A string representing the execution plan. */ explainCLI(index: string, query: string): CommandData { return { command: 'FT.EXPLAINCLI', args: [index, query] } } /** * Adding a new field to the index * @param index The index * @param field The field name * @param fieldType The field type * @param options The additional optional parameters * @returns 'OK' or error */ alter(index: string, field: string, fieldType: FTFieldType, options?: FTFieldOptions): CommandData { let args = [index, 'SCHEMA', 'ADD', field, fieldType] if(options !== undefined) { if(options.nostem === true) args.push('NOSTEM') if(options.weight !== undefined) args = args.concat(['WEIGHT', `${options.weight}`]) if(options.phonetic !== undefined) args = args.concat(['PHONETIC', options.phonetic]) if(options.separator !== undefined) args = args.concat(['SEPARATOR', options.separator]) if(options.sortable === true) args.push('SORTABLE') if(options.noindex === true) args.push('NOINDEX') if(options.unf === true) args.push('UNF') if(options.caseSensitive === true) args.push('CASESENSITIVE') } return { command: 'FT.ALTER', args: args } } /** * Deleting the index * @param index The index * @param deleteHash If set, the drop operation will delete the actual document hashes. * @returns 'OK' or error */ dropindex(index: string, deleteHash = false): CommandData { const args = [index]; if(deleteHash === true) args.push('DD') return { command: 'FT.DROPINDEX', args: args } } /** * Adding alias fron an index * @param name The alias name * @param index The alias index * @returns 'OK' or error */ aliasadd(name: string, index: string): CommandData { return { command: 'FT.ALIASADD', args: [name, index] } } /** * Updating alias index * @param name The alias name * @param index The alias index * @returns 'OK' or error */ aliasupdate(name: string, index: string): CommandData { return { command: 'FT.ALIASUPDATE', args: [name, index] } } /** * Deleting alias fron an index * @param name The alias name * @returns 'OK' or error */ aliasdel(name: string): CommandData { return { command: 'FT.ALIASDEL', args: [name] } } /** * Retrieving the distinct tags indexed in a Tag field * @param index The index * @param field The field name * @returns The distinct tags indexed in a Tag field */ tagvals(index: string, field: string): CommandData { return { command: 'FT.TAGVALS', args: [index, field] } } /** * Adds a suggestion string to an auto-complete suggestion dictionary * @param key The key * @param suggestion The suggestion * @param score The score * @param options The additional optional parameters * @returns The current size of the suggestion dictionary */ sugadd(key: string, suggestion: string, score: number, options?: FTSugAddParameters): CommandData { let args = [key, suggestion, score]; if(options !== undefined) { if(options.incr === true) args.push('INCR'); if(options.payload !== undefined) args = args.concat(['PAYLOAD', options.payload]); } return { command: 'FT.SUGADD', args: args } } /** * Retrieving completion suggestions for a prefix * @param key The key * @param prefix The prefix of the suggestion * @param options The additional optional parameter * @returns A list of the top suggestions matching the prefix, optionally with score after each entry */ sugget(key: string, prefix: string, options?: FTSugGetParameters): CommandData { let args = [key, prefix]; if(options !== undefined) { if(options.fuzzy === true) args.push('FUZZY'); if(options.max !== undefined) args = args.concat(['MAX', `${options.max}`]); if(options.withScores === true) args.push('WITHSCORES'); if(options.withPayloads === true) args.push('WITHPAYLOADS'); } return { command: 'FT.SUGGET', args: args } } /** * Deleting a string from a suggestion index * @param key The key * @param suggestion The suggestion */ sugdel(key: string, suggestion: string): CommandData { return { command: 'FT.SUGDEL', args: [key, suggestion] } } /** * Retrieving the size of an auto-complete suggestion dictionary * @param key The key */ suglen(key: string): CommandData { return { command: 'FT.SUGLEN', args: [key] } } /** * Updating a synonym group * @param index The index * @param groupId The group id * @param terms A list of terms * @param skipInitialScan If set, we do not scan and index. * @returns 'OK' */ synupdate(index: string, groupId: number, terms: string[], skipInitialScan = false): CommandData { let args = [index, groupId]; if(skipInitialScan === true) args.push('SKIPINITIALSCAN'); args = args.concat(terms); return { command: 'FT.SYNUPDATE', args: args } } /** * Dumps the contents of a synonym group * @param index The index * @returns A list of synonym terms and their synonym group ids. */ syndump(index: string): CommandData { return { command: 'FT.SYNDUMP', args: [index] } } /** * Performs spelling correction on a query * @param index The index * @param query The query * @param options The additional optional parameters * @returns An array, in which each element represents a misspelled term from the query */ spellcheck(index: string, query: string, options?: FTSpellCheck): CommandData { let args = [index, query]; if(options !== undefined) { if(options.distance !== undefined) args = args.concat(['DISTANCE', `${options.distance}`]); if(options.terms !== undefined) { args.push('TERMS'); for(const term of options.terms) { args = args.concat([term.type, term.dict]); } } } return { command: 'FT.SPELLCHECK', args: args } } /** * Adding terms to a dictionary * @param dict The dictionary * @param terms A list of terms * @returns The number of new terms that were added */ dictadd(dict: string, terms: string[]): CommandData { return { command: 'FT.DICTADD', args: [dict].concat(terms) } } /** * Deleting terms from a dictionary * @param dict The dictionary * @param terms A list of terms * @returns The number of terms that were deleted */ dictdel(dict: string, terms: string[]): CommandData { return { command: 'FT.DICTDEL', args: [dict].concat(terms) } } /** * Dumps all terms in the given dictionary * @param dict The dictionary * @returns An array, where each element is term */ dictdump(dict: string): CommandData { return { command: 'FT.DICTDUMP', args: [dict] } } /** * Retrieving infromation and statistics on the index * @param index The index * @returns A nested array of keys and values. */ info(index: string): CommandData { return { command: 'FT.INFO', args: [index] } } /** * Retrieves, describes and sets runtime configuration options * @param command The command type * @param option The option * @param value In case of 'SET' command, a valid value to set * @returns If 'SET' command, returns 'OK' for valid runtime-settable option names and values. If 'GET' command, returns a string with the current option's value. */ config(command: 'GET' | 'SET' | 'HELP', option: string, value?: string): CommandData { const args = [command, option]; if(command === 'SET'){ args.push(value); } return { command: 'FT.CONFIG', args: args } } }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace Formmsdyn_iotsettings_Information { interface Header extends DevKit.Controls.IHeader { /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface tab__EDDC3EA8_B755_416E_8D97_C3B1FEE65AAD_Sections { _E07187A8_1C2C_40FF_8C3A_05845B3A09F2: DevKit.Controls.Section; _EDDC3EA8_B755_416E_8D97_C3B1FEE65AAD_SECTION_2: DevKit.Controls.Section; } interface tab_AlertAggregationRulesTab_Sections { AlertAggregationRulesSection: DevKit.Controls.Section; tab_3_section_2: DevKit.Controls.Section; } interface tab_General_Sections { Command_Settings_Section: DevKit.Controls.Section; Deployment: DevKit.Controls.Section; Other_Section: DevKit.Controls.Section; tab_2_section_2: DevKit.Controls.Section; } interface tab_IoTProviderSettingsTab_Sections { DefaultIoTProviderInstanceSection: DevKit.Controls.Section; IoTProviderSettingsEmptySection: DevKit.Controls.Section; } interface tab_SuggestionsTab_Sections { ModelStatusSection: DevKit.Controls.Section; SuggestionsEmptySection: DevKit.Controls.Section; SuggestionsSection: DevKit.Controls.Section; } interface tab__EDDC3EA8_B755_416E_8D97_C3B1FEE65AAD extends DevKit.Controls.ITab { Section: tab__EDDC3EA8_B755_416E_8D97_C3B1FEE65AAD_Sections; } interface tab_AlertAggregationRulesTab extends DevKit.Controls.ITab { Section: tab_AlertAggregationRulesTab_Sections; } interface tab_General extends DevKit.Controls.ITab { Section: tab_General_Sections; } interface tab_IoTProviderSettingsTab extends DevKit.Controls.ITab { Section: tab_IoTProviderSettingsTab_Sections; } interface tab_SuggestionsTab extends DevKit.Controls.ITab { Section: tab_SuggestionsTab_Sections; } interface Tabs { _EDDC3EA8_B755_416E_8D97_C3B1FEE65AAD: tab__EDDC3EA8_B755_416E_8D97_C3B1FEE65AAD; AlertAggregationRulesTab: tab_AlertAggregationRulesTab; General: tab_General; IoTProviderSettingsTab: tab_IoTProviderSettingsTab; SuggestionsTab: tab_SuggestionsTab; } interface Body { Tab: Tabs; /** This value will be used to specify the command name when sending device commands. Default property value is "CommandName" when this field is unspecified. */ msdyn_CommandNameProperty: DevKit.Controls.String; /** This value will be used to specify the command parameters when sending device commands. Default property value is "Parameters" when this field is unspecified. */ msdyn_CommandParametersProperty: DevKit.Controls.String; /** The IoT Provider Instance to which IoT Devices should belong by default. */ msdyn_DefaultIoTProviderInstance: DevKit.Controls.Lookup; msdyn_DeploymentAppURL: DevKit.Controls.String; /** To specify the interval of scheduled device data pulls */ msdyn_devicedatapullfrequency: DevKit.Controls.Integer; /** IoT suggestions provide you insights on priority level and incident type associated with an alert. */ msdyn_EnableIoTSuggestions: DevKit.Controls.Boolean; /** IoT suggestions provide you insights on priority level and incident type associated with an alert. */ msdyn_EnableIoTSuggestions_1: DevKit.Controls.Boolean; /** When this option is enabled, all Connected Field Service background processes will be processed through flows instead of the historic Connected Field Service workflows. */ msdyn_EnhancedBackgroundProcessing: DevKit.Controls.Boolean; /** Select the columns that will be used to determine the aggregation of similar IoT alerts. */ msdyn_IoTAlertAggregationRule: DevKit.Controls.String; /** The name of the custom entity. */ msdyn_name: DevKit.Controls.String; /** The next scheduled running time for device data pull */ msdyn_NextDeviceDataPullTime: DevKit.Controls.DateTime; /** To turn on/off scheduled device data pulls, default is off */ msdyn_ScheduledDeviceDataPull: DevKit.Controls.Boolean; } } class Formmsdyn_iotsettings_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyn_iotsettings_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form msdyn_iotsettings_Information */ Body: DevKit.Formmsdyn_iotsettings_Information.Body; /** The Header section of form msdyn_iotsettings_Information */ Header: DevKit.Formmsdyn_iotsettings_Information.Header; } class msdyn_iotsettingsApi { /** * DynamicsCrm.DevKit msdyn_iotsettingsApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the record. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the record was modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who modified the record. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** This value will be used to specify the command name when sending device commands. Default property value is "CommandName" when this field is unspecified. */ msdyn_CommandNameProperty: DevKit.WebApi.StringValue; /** This value will be used to specify the command parameters when sending device commands. Default property value is "Parameters" when this field is unspecified. */ msdyn_CommandParametersProperty: DevKit.WebApi.StringValue; /** The IoT Provider Instance to which IoT Devices should belong by default. */ msdyn_DefaultIoTProviderInstance: DevKit.WebApi.LookupValue; /** This field is used to know the source of IoT for this organization. Example : IoT Suite or IoT Central or Others. */ msdyn_defaultiotsource: DevKit.WebApi.OptionSetValue; msdyn_DeploymentAppURL: DevKit.WebApi.StringValue; /** To specify the interval of scheduled device data pulls */ msdyn_devicedatapullfrequency: DevKit.WebApi.IntegerValue; /** IoT suggestions provide you insights on priority level and incident type associated with an alert. */ msdyn_EnableIoTSuggestions: DevKit.WebApi.BooleanValue; /** When this option is enabled, all Connected Field Service background processes will be processed through flows instead of the historic Connected Field Service workflows. */ msdyn_EnhancedBackgroundProcessing: DevKit.WebApi.BooleanValue; /** Select the columns that will be used to determine the aggregation of similar IoT alerts. */ msdyn_IoTAlertAggregationRule: DevKit.WebApi.StringValue; /** Unique identifier for entity instances */ msdyn_iotsettingsId: DevKit.WebApi.GuidValue; /** The name of the custom entity. */ msdyn_name: DevKit.WebApi.StringValue; /** The next scheduled running time for device data pull */ msdyn_NextDeviceDataPullTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** To turn on/off scheduled device data pulls, default is off */ msdyn_ScheduledDeviceDataPull: DevKit.WebApi.BooleanValue; msdyn_ShowWelcome: DevKit.WebApi.BooleanValue; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Status of the IoTSettings */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the IoTSettings */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace msdyn_iotsettings { enum msdyn_defaultiotsource { /** 192350002 */ Azure_IoT_Central, /** 192350001 */ Azure_IoT_Suite, /** 192350000 */ Other } enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { Room, Client, generateId } from "colyseus"; import { ExampleRoomState, ExampleNetworkedEntity, ExampleNetworkedUser } from "./schema/ExampleRoomState"; const logger = require("../helpers/logger"); export class MyRoom extends Room<ExampleRoomState> { clientEntities = new Map<string, string[]>(); serverTime: number = 0; roomOptions: any; /** * Callback for when the room is created */ async onCreate(options: any) { console.log("\n*********************** MyRoom Created ***********************"); console.log(options); console.log("***********************\n"); this.maxClients = 25; this.roomOptions = options; // // Set state schema // this.setState(new ExampleRoomState()); // // The patch-rate is the frequency which state mutations are sent to all clients. (in milliseconds) // 1000 / 20 means 20 times per second (50 milliseconds) // this.setPatchRate(1000 / 20); // // Set the callback for the "customMethod" message // https://docs.colyseus.io/server/room/#onmessage-type-callback // this.onMessage("customMethod", (client: Client, request: any) => { // Implement your logic here }); // Set the callback for the "entityUpdate" message this.onMessage("entityUpdate", (client: Client, entityUpdateArray: any) => { if (this.state.networkedEntities.has(`${entityUpdateArray[0]}`) === false) return; this.onEntityUpdate(client.sessionId, entityUpdateArray); }); // // Set the callback for the "removeFunctionCall" message // this.onMessage("remoteFunctionCall", (client: Client, RFCMessage: any) => { //Confirm Sending Client is Owner if (this.state.networkedEntities.has(`${RFCMessage.entityId}`) === false) return; RFCMessage.clientId = client.sessionId; // Broadcast the "remoteFunctionCall" to all clients except the one the message originated from this.broadcast("onRFC", RFCMessage, RFCMessage.target == 0 ? {} : { except: client }); }); // // Set the callback for the "setAttribute" message to set an entity or user attribute // this.onMessage("setAttribute", (client: Client, attributeUpdateMessage: any) => { if (attributeUpdateMessage == null || (attributeUpdateMessage.entityId == null && attributeUpdateMessage.userId == null) || attributeUpdateMessage.attributesToSet == null) { return; // Invalid Attribute Update Message } // Set entity attribute if (attributeUpdateMessage.entityId) { //Check if this client owns the object if (this.state.networkedEntities.has(`${attributeUpdateMessage.entityId}`) === false) return; this.state.networkedEntities.get(`${attributeUpdateMessage.entityId}`).timestamp = parseFloat(this.serverTime.toString()); let entityAttributes = this.state.networkedEntities.get(`${attributeUpdateMessage.entityId}`).attributes; for (let index = 0; index < Object.keys(attributeUpdateMessage.attributesToSet).length; index++) { let key = Object.keys(attributeUpdateMessage.attributesToSet)[index]; let value = attributeUpdateMessage.attributesToSet[key]; entityAttributes.set(key, value); } } // Set user attribute else if (attributeUpdateMessage.userId) { //Check is this client ownes the object if (this.state.networkedUsers.has(`${attributeUpdateMessage.userId}`) === false) { logger.error(`Set Attribute - User Attribute - Room does not have networked user with Id - \"${attributeUpdateMessage.userId}\"`); return; } this.state.networkedUsers.get(`${attributeUpdateMessage.userId}`).timestamp = parseFloat(this.serverTime.toString()); let userAttributes = this.state.networkedUsers.get(`${attributeUpdateMessage.userId}`).attributes; for (let index = 0; index < Object.keys(attributeUpdateMessage.attributesToSet).length; index++) { let key = Object.keys(attributeUpdateMessage.attributesToSet)[index]; let value = attributeUpdateMessage.attributesToSet[key]; userAttributes.set(key, value); } } }); // // Set the callback for the "removeEntity" message // this.onMessage("removeEntity", (client: Client, removeId: string) => { if (this.state.networkedEntities.has(removeId)) { this.state.networkedEntities.delete(removeId); } }); // // Set the callback for the "createEntity" message // this.onMessage("createEntity", (client: Client, creationMessage: any) => { // Generate new UID for the entity let entityViewID = generateId(); let newEntity = new ExampleNetworkedEntity().assign({ id: entityViewID, ownerId: client.sessionId, timestamp: this.serverTime }); if (creationMessage.creationId != null) newEntity.creationId = creationMessage.creationId; newEntity.timestamp = parseFloat(this.serverTime.toString()); for (let key in creationMessage.attributes) { if (key === "creationPos") { newEntity.xPos = parseFloat(creationMessage.attributes[key][0]); newEntity.yPos = parseFloat(creationMessage.attributes[key][1]); newEntity.zPos = parseFloat(creationMessage.attributes[key][2]); } else if (key === "creationRot") { newEntity.xRot = parseFloat(creationMessage.attributes[key][0]); newEntity.yRot = parseFloat(creationMessage.attributes[key][1]); newEntity.zRot = parseFloat(creationMessage.attributes[key][2]); newEntity.wRot = parseFloat(creationMessage.attributes[key][3]); } else { newEntity.attributes.set(key, creationMessage.attributes[key].toString()); } } // Add the entity to the room state's networkedEntities map this.state.networkedEntities.set(entityViewID, newEntity); // Add the entity to the client entities collection if (this.clientEntities.has(client.sessionId)) { this.clientEntities.get(client.sessionId).push(entityViewID); } else { this.clientEntities.set(client.sessionId, [entityViewID]); } }); // Set the callback for the "ping" message for tracking server-client latency this.onMessage("ping", (client: Client) => { client.send(0, { serverTime: this.serverTime }); }); this.setSimulationInterval((dt) => this.onGameLoop(dt)); } // Callback when a client has joined the room onJoin(client: Client, options: any) { logger.info(`Client joined!- ${client.sessionId} ***`); let newNetworkedUser = new ExampleNetworkedUser().assign({ sessionId: client.sessionId, }); this.state.networkedUsers.set(client.sessionId, newNetworkedUser); client.send("onJoin", newNetworkedUser); } onGameLoop(dt: number) { this.serverTime += dt; // // This is your game loop. // Run your game logic here. // } /** * Callback for the "entityUpdate" message from the client to update an entity * @param {*} clientID * @param {*} data */ onEntityUpdate(clientID: string, data: any) { if (this.state.networkedEntities.has(`${data[0]}`) === false) return; let stateToUpdate = this.state.networkedEntities.get(data[0]); let startIndex = 1; if (data[1] === "attributes") startIndex = 2; for (let i = startIndex; i < data.length; i += 2) { const property = data[i]; let updateValue = data[i + 1]; if (updateValue === "inc") { updateValue = data[i + 2]; updateValue = parseFloat(stateToUpdate.attributes.get(property)) + parseFloat(updateValue); i++; // inc i once more since we had a inc; } if (startIndex == 2) { stateToUpdate.attributes.set(property, updateValue.toString()); } else { (stateToUpdate as any)[property] = updateValue; } } stateToUpdate.timestamp = parseFloat(this.serverTime.toString()); } // // Callback when a client has left the room // https://docs.colyseus.io/server/room/#onleave-client-consented // // Read about handling reconnection: // https://docs.colyseus.io/server/room/#allowreconnection-client-seconds // async onLeave(client: Client, consented: boolean) { let networkedUser = this.state.networkedUsers.get(client.sessionId); if (networkedUser) { networkedUser.connected = false; } logger.silly(`*** User Leave - ${client.sessionId} ***`); // this.clientEntities is keyed by client.sessionId // this.state.networkedUsers is keyed by client.sessionid try { if (consented) { throw new Error("consented leave!"); } logger.info("let's wait for reconnection for client: " + client.sessionId); const newClient = await this.allowReconnection(client, 10); logger.info("reconnected! client: " + newClient.sessionId); } catch (e) { logger.info("disconnected! client: " + client.sessionId); logger.silly(`*** Removing Networked User and Entity ${client.sessionId} ***`); // remove user this.state.networkedUsers.delete(client.sessionId); // remove entities if (this.clientEntities.has(client.sessionId)) { let allClientEntities = this.clientEntities.get(client.sessionId); allClientEntities.forEach(element => { this.state.networkedEntities.delete(element); }); // remove the client from clientEntities this.clientEntities.delete(client.sessionId); } else { logger.error(`Can't remove entities for ${client.sessionId} - No entry in Client Entities!`); } } } onDispose() { console.log("*********************** MyRoom disposed ***********************"); } }
the_stack
'use strict'; import { GenericOAuth2Router } from '../common/generic-router'; import { AuthRequest, AuthResponse, IdentityProvider, EndpointDefinition, IdpOptions, CheckRefreshDecision, BooleanCallback, ExternalIdpConfig, TokenInfo, ErrorLink } from '../common/types'; import { OidcProfile, WickedUserInfo, Callback } from 'wicked-sdk'; const { debug, info, warn, error } = require('portal-env').Logger('portal-auth:external'); import * as wicked from 'wicked-sdk'; const Router = require('express').Router; const qs = require('querystring'); const request = require('request'); import { utils } from '../common/utils'; import { failMessage, failError, failOAuth, makeError } from '../common/utils-fail'; import { ExternalUserPassRequest, ExternalUserPassResponse, ExternalRefreshResponse, WickedApi } from 'wicked-sdk'; export class ExternalIdP implements IdentityProvider { private genericFlow: GenericOAuth2Router; private basePath: string; private authMethodId: string; private authMethodConfig: ExternalIdpConfig; private options: IdpOptions; constructor(basePath: string, authMethodId: string, authMethodConfig: ExternalIdpConfig, options: IdpOptions) { debug(`constructor(${basePath}, ${authMethodId}, ...)`); this.basePath = basePath; this.genericFlow = new GenericOAuth2Router(basePath, authMethodId); this.authMethodId = authMethodId; this.authMethodConfig = authMethodConfig; this.options = options; this.genericFlow.initIdP(this); } public getType(): string { return "external"; } public supportsPrompt(): boolean { return false; } public getRouter() { return this.genericFlow.getRouter(); } public authorizeWithUi(req, res, next, authRequest: AuthRequest) { // Render a login mask... const prefillUsername = authRequest.prefill_username; this.renderLogin(req, res, next, null, prefillUsername); } public authorizeByUserPass = async (user, pass, callback: Callback<AuthResponse>) => { debug('authorizeByUserPass()'); // loginUser returns an authResponse, so we can use that to verify that the user // does not interactively have to change his password. try { const authResponse = await this.loginUser(user, pass); return callback(null, authResponse); } catch (err) { return callback(err); } } public checkRefreshToken(tokenInfo: TokenInfo, apiInfo: WickedApi, callback: Callback<CheckRefreshDecision>) { debug('checkRefreshToken()'); const instance = this; // Decide whether it's okay to refresh this token or not. Ask the external IdP whether it's okay. // Only do that if it's a passthrough users API; in all other cases it does not make much sense, for the // following reason: the authenticated_userid is a wicked userId, and not the sub from the external IdP, // and thus we can't expect the external IdP to know whether to allow a refresh of this user or not. if (!apiInfo.passthroughUsers) { // Here we just say it's okay. return callback(null, { allowRefresh: true }); } // Passthrough users case - the external IdP gets an authenticated user id which it knows (by structure), // and thus it makes sense to ask the IdP whether a refresh is allowed. const postBody = { authenticated_userid: tokenInfo.authenticated_userid, authenticated_scope: tokenInfo.scope }; const uri = this.authMethodConfig.allowRefreshUrl; request.post({ uri, body: postBody, json: true }, function (err, response, responseBody) { if (err) { return callback(err); } try { const jsonResponse = utils.getJson(responseBody) as ExternalRefreshResponse; if (response.statusCode !== 200 || jsonResponse.error) { const err = makeError(`External IDP ${instance.authMethodId} returned an error or an unexpected status code (${response.statusCode})`, response.statusCode); if (jsonResponse.error) err.internalError = new Error(`Error: ${jsonResponse.error}, description. ${jsonResponse.error_description || '<no description>'}`); return callback(err); } return callback(null, { allowRefresh: jsonResponse.allow_refresh || false }); } catch (err) { error(err); return callback(err); } }); } public getErrorLinks(): ErrorLink { return null; } public endpoints(): EndpointDefinition[] { return [ { method: 'post', uri: '/login', handler: this.loginHandler } ]; } private loginHandler = async (req, res, next) => { debug(`POST ${this.authMethodId}/login`); debug('loginHandler()'); // When you're done with whatever (like verifying username and password, // or checking a callback from a 3rd party IdP), you must use the registered // generic flow implementation object (genericFlow from the constructor) to // pass back the same type of structure as in the authorizeByUserPass below. const body = req.body; const csrfToken = body._csrf; const expectedCsrfToken = utils.getAndDeleteCsrfToken(req, 'login'); const instance = this; if (!csrfToken || csrfToken !== expectedCsrfToken) return this.renderLogin(req, res, next, 'Suspected login forging detected (CSRF protection).'); const username = req.body.username; const password = req.body.password; debug(`username: ${username}, password: ${password}`); try { const authResponse = await this.loginUser(username, password); // Continue as normal instance.genericFlow.continueAuthorizeFlow(req, res, next, authResponse); } catch (err) { debug(err); // Delay redisplay of login page a little await utils.delay(500); instance.renderLogin(req, res, next, 'Username or password invalid.', username); } }; private renderLogin(req, res, next, flashMessage: string, prefillUsername?: string) { debug('renderLogin()'); const authRequest = utils.getAuthRequest(req, this.authMethodId); const authSession = utils.getSession(req, this.authMethodId); authSession.tmpAuthResponse = null; const instance = this; const viewModel = utils.createViewModel(req, instance.authMethodId, 'login'); viewModel.errorMessage = flashMessage; viewModel.disableSignup = true; delete viewModel.forgotPasswordUrl; if (this.authMethodConfig.forgotPasswordUrl) viewModel.forgotPasswordUrl = this.authMethodConfig.forgotPasswordUrl; if (prefillUsername) viewModel.prefillUsername = prefillUsername; if (this.authMethodConfig.usernamePrompt) viewModel.usernamePrompt = this.authMethodConfig.usernamePrompt; if (this.authMethodConfig.passwordPrompt) viewModel.usernamePrompt = this.authMethodConfig.passwordPrompt; utils.render(req, res, 'login', viewModel, authRequest); } private loginUser = async (username: string, password: string): Promise<AuthResponse> => { const instance = this; return new Promise<AuthResponse>(function (resolve, reject) { instance.loginUser_(username, password, function (err, authResponse) { err ? reject(err) : resolve(authResponse); }); }); } private loginUser_(username: string, password: string, callback: Callback<AuthResponse>) { debug('loginUser()'); // Ask the external service whether this is a good username/password combination const postBody: ExternalUserPassRequest = { username, password }; const uri = this.authMethodConfig.validateUserPassUrl; const instance = this; request.post({ uri, body: postBody, json: true }, function (err, res, responseBody) { if (err) return callback(err); try { const jsonResponse = utils.getJson(responseBody) as ExternalUserPassResponse; if (res.statusCode !== 200 || jsonResponse.error) { const err = makeError(`External IDP ${instance.authMethodId} returned an error or an unexpected status code (${res.statusCode})`, res.statusCode); if (jsonResponse.error) err.internalError = new Error(`Error: ${jsonResponse.error}, description. ${jsonResponse.error_description || '<no description>'}`); return callback(err); } return callback(null, instance.createAuthResponse(jsonResponse)); } catch (err) { error(err); return callback(err); } }) } private createAuthResponse(response: ExternalUserPassResponse): AuthResponse { if (!response.profile) throw makeError(`The external IdP ${this.authMethodId} did not return a profile property.`, 500); const profile = response.profile; if (!profile.sub) throw makeError(`The external IdP ${this.authMethodId} did not return a "sub" profile property.`, 500); if (!profile.email) throw makeError(`The external IdP ${this.authMethodId} did not return a "email" profile property.`, 500); return { userId: null, customId: `${this.authMethodId}:${profile.sub}`, defaultGroups: [], defaultProfile: profile }; } }
the_stack
import { t, Trans } from '@lingui/macro' import { DatePicker, Form, Modal, Select } from 'antd' import CurrencySymbol from 'components/shared/CurrencySymbol' import { FormItems } from 'components/shared/formItems' import { countDecimalPlaces, ModalMode, roundDown, validateEthAddress, validatePercentage, } from 'components/shared/formItems/formHelpers' import InputAccessoryButton from 'components/shared/InputAccessoryButton' import FormattedNumberInput from 'components/shared/inputs/FormattedNumberInput' import NumberSlider from 'components/shared/inputs/NumberSlider' import { ThemeContext } from 'contexts/themeContext' import { isAddress } from 'ethers/lib/utils' import { PayoutMod } from 'models/mods' import { useCallback, useContext, useEffect, useState } from 'react' import { fromWad, parseWad, percentToPerbicent, percentToPermyriad, permyriadToPercent, } from 'utils/formatNumber' import { amountSubFee } from 'utils/math' import { getAmountFromPercent, getPercentFromAmount } from 'utils/v1/payouts' import * as constants from '@ethersproject/constants' import * as moment from 'moment' import { BigNumber } from '@ethersproject/bignumber' import { useForm } from 'antd/lib/form/Form' import { CurrencyName } from 'constants/currency' import { EditingPayoutMod } from './types' type ModType = 'project' | 'address' type ProjectPayoutModsForm = { projectId: string handle: string beneficiary: string percent: number amount: number lockedUntil: moment.Moment } export const ProjectPayoutModsModal = ({ visible, mods, editingModIndex, target, feePercentage, targetIsInfinite, currencyName, onOk, onCancel, }: { visible: boolean mods: PayoutMod[] target: string editingModIndex: number | undefined feePercentage: string | undefined targetIsInfinite?: boolean currencyName: CurrencyName | undefined onOk: (mods: EditingPayoutMod[]) => void onCancel: VoidFunction }) => { const { theme: { colors }, } = useContext(ThemeContext) const [modalMode, setModalMode] = useState<ModalMode>('Add') //either 'Add', or 'Edit' const [editingModType, setEditingModType] = useState<ModType>('address') const [editingModHandle, setEditingModHandle] = useState<string | BigNumber>() const [, setEditingPercent] = useState<number>() const [form] = useForm<ProjectPayoutModsForm>() useEffect(() => { const loadSelectedMod = (mod: EditingPayoutMod) => { setModalMode('Edit') setEditingModType( BigNumber.from(mod.projectId ?? '0').gt(0) ? 'project' : 'address', ) setEditingModHandle(mod.handle ?? mod.projectId) const percent = parseFloat(permyriadToPercent(mod.percent)) setEditingPercent(percent) form.setFieldsValue({ ...mod, handle: mod.handle, beneficiary: mod.beneficiary, percent, projectId: mod.projectId?.toString(), amount: getAmountFromPercent(percent, target, feePercentage), lockedUntil: mod.lockedUntil ? moment.default(mod.lockedUntil * 1000) : undefined, }) } const resetModal = () => { form.resetFields() setModalMode('Add') setEditingModType('address') setEditingModHandle(undefined) setEditingPercent(undefined) } if (editingModIndex === undefined) { resetModal() return } const mod = mods[editingModIndex] loadSelectedMod(mod) }, [editingModIndex, feePercentage, form, mods, target]) const feePerbicent = percentToPerbicent(feePercentage) // Validates the amount and percentage (ensures percent !== 0 or > 100) const validatePayout = () => { return validatePercentage(form.getFieldValue('percent')) } // Validates new payout receiving address const validatePayoutAddress = () => { return validateEthAddress( form.getFieldValue('beneficiary'), mods, modalMode, editingModIndex, ) } const isPercentBeingRounded = () => { return countDecimalPlaces(form.getFieldValue('percent')) > 2 } const roundedDownAmount = useCallback(() => { const percent = roundDown(form.getFieldValue('percent'), 2) const targetSubFee = parseFloat( fromWad(amountSubFee(parseWad(target), feePerbicent)), ) return parseFloat(((percent * targetSubFee) / 100).toFixed(4)) }, [feePerbicent, form, target]) const onAmountChange = (newAmount: number | undefined) => { let newPercent = getPercentFromAmount(newAmount, target, feePercentage) setEditingPercent(newPercent) form.setFieldsValue({ amount: newAmount }) form.setFieldsValue({ percent: newPercent }) } const validateAndSave = async () => { await form.validateFields() const handle = form.getFieldValue('handle') const beneficiary = form.getFieldValue('beneficiary') const percent = percentToPermyriad(form.getFieldValue('percent')).toNumber() const _projectId = form.getFieldValue('projectId') const projectId = _projectId ? BigNumber.from(_projectId) : undefined const _lockedUntil = form.getFieldValue('lockedUntil') as | moment.Moment | undefined const lockedUntil = _lockedUntil ? Math.round(_lockedUntil.valueOf() / 1000) : undefined // Store handle in mod object only to repopulate handle input while editing const newMod = { beneficiary, percent, handle, lockedUntil, projectId } let modsToReturn = [...mods, newMod] if (editingModIndex !== undefined && editingModIndex < mods.length) { modsToReturn = mods.map((m, i) => i === editingModIndex ? { ...m, ...newMod } : m, ) } onOk(modsToReturn) return true } const discardAndClose = () => { onCancel() return true } return ( <Modal title={modalMode === 'Edit' ? t`Edit payout` : t`Add new payout`} visible={visible} onOk={validateAndSave} okText={modalMode === 'Edit' ? t`Save payout` : t`Add payout`} onCancel={discardAndClose} destroyOnClose > <Form form={form} layout="vertical" onKeyDown={e => { if (e.key === 'Enter') validateAndSave() }} > <Form.Item> <Select value={editingModType} onChange={type => { setEditingModType(type) if (type === 'address') form.setFieldsValue({ handle: undefined, projectId: undefined }) }} > <Select.Option value="address"> <Trans>Wallet address</Trans> </Select.Option> <Select.Option value="project"> <Trans>Juicebox project</Trans> </Select.Option> </Select> </Form.Item> {editingModType === 'address' ? ( <FormItems.EthAddress name="beneficiary" defaultValue={form.getFieldValue('beneficiary')} formItemProps={{ label: 'Address', rules: [ { validator: validatePayoutAddress, }, ], }} onAddressChange={beneficiary => form.setFieldsValue({ beneficiary }) } /> ) : ( <FormItems.ProjectHandleFormItem name="handle" requireState="exists" initialValue={editingModHandle} returnValue="id" onValueChange={id => form.setFieldsValue({ projectId: id })} formItemProps={{ label: t`Project handle`, }} required /> )} {editingModType === 'project' ? ( <FormItems.EthAddress name="beneficiary" defaultValue={form.getFieldValue('beneficiary')} formItemProps={{ label: t`Address`, extra: t`The address that should receive the tokens minted from paying this project.`, rules: [ { validator: () => { const address = form.getFieldValue('beneficiary') if (!address || !isAddress(address)) return Promise.reject('Address is required') else if (address === constants.AddressZero) return Promise.reject('Cannot use zero address.') else return Promise.resolve() }, }, ], }} onAddressChange={beneficiary => form.setFieldsValue({ beneficiary }) } /> ) : null} {/* Only show amount input if project has a funding target */} {!targetIsInfinite ? ( <Form.Item label="Amount" // Display message to user if the amount they inputted // will result in percentage with > 2 decimal places // and no error is present className="ant-form-item-extra-only" extra={ isPercentBeingRounded() && !(form.getFieldValue('percent') > 100) ? ( <div> <Trans> Will be rounded to{' '} <CurrencySymbol currency={currencyName} /> {roundedDownAmount()} </Trans> </div> ) : null } > <div style={{ display: 'flex', color: colors.text.primary, alignItems: 'center', }} > <FormattedNumberInput value={form.getFieldValue('amount')} placeholder={'0'} onChange={amount => onAmountChange(parseFloat(amount || '0'))} formItemProps={{ rules: [{ validator: validatePayout }], }} accessory={<InputAccessoryButton content={currencyName} />} /> </div> </Form.Item> ) : null} <Form.Item label={t`Percent`}> <div style={{ display: 'flex', alignItems: 'center' }}> <span style={{ flex: 1 }}> <NumberSlider onChange={(percent: number | undefined) => { let newAmount = getAmountFromPercent( percent ?? 0, target, feePercentage, ) form.setFieldsValue({ amount: newAmount }) form.setFieldsValue({ percent }) setEditingPercent(percent) }} step={0.01} defaultValue={form.getFieldValue('percent') || 0} sliderValue={form.getFieldValue('percent')} suffix="%" name="percent" formItemProps={{ rules: [{ validator: validatePayout }], }} /> </span> </div> </Form.Item> <Form.Item name="lockedUntil" label={t`Lock until`} extra={ <Trans> If locked, this split can't be edited or removed until the lock expires or the funding cycle is reconfigured. </Trans> } > <DatePicker /> </Form.Item> </Form> </Modal> ) }
the_stack
import { Site, SiteConfig, SiteSourceControl, StringDictionary } from "@azure/arm-appservice"; import { AppSettingsTreeItem, AppSettingTreeItem, DeleteLastServicePlanStep, DeleteSiteStep, DeploymentsTreeItem, DeploymentTreeItem, getFile, IDeleteSiteWizardContext, LogFilesTreeItem, ParsedSite, SiteFilesTreeItem } from "@microsoft/vscode-azext-azureappservice"; import { AzExtTreeItem, AzureWizard, DeleteConfirmationStep, IActionContext, ISubscriptionContext, nonNullValue, TreeItemIconPath } from "@microsoft/vscode-azext-utils"; import { ResolvedAppResourceBase } from "@microsoft/vscode-azext-utils/hostapi"; import { runFromPackageKey } from "../constants"; import { IParsedHostJson, parseHostJson } from "../funcConfig/host"; import { FuncVersion, latestGAVersion, tryParseFuncVersion } from "../FuncVersion"; import { localize } from "../localize"; import { createActivityContext } from "../utils/activityUtils"; import { envUtils } from "../utils/envUtils"; import { treeUtils } from "../utils/treeUtils"; import { ApplicationSettings, FuncHostRequest } from "./IProjectTreeItem"; import { matchesAnyPart, ProjectResource, ProjectSource } from "./projectContextValues"; import { RemoteFunctionsTreeItem } from "./remoteProject/RemoteFunctionsTreeItem"; import { SlotsTreeItem } from "./SlotsTreeItem"; import { SlotTreeItem } from "./SlotTreeItem"; export function isResolvedFunctionApp(ti: unknown): ti is ResolvedAppResourceBase { return (ti as unknown as ResolvedFunctionAppResource).instance === ResolvedFunctionAppResource.instance; } export class ResolvedFunctionAppResource implements ResolvedAppResourceBase { public site: ParsedSite; private _subscription: ISubscriptionContext; public logStreamPath: string = ''; public appSettingsTreeItem: AppSettingsTreeItem; public deploymentsNode: DeploymentsTreeItem | undefined; public readonly source: ProjectSource = ProjectSource.Remote; public static instance = 'resolvedFunctionApp'; public readonly instance = ResolvedFunctionAppResource.instance; public contextValuesToAdd?: string[] | undefined; public maskedValuesToAdd: string[] = []; private _slotsTreeItem: SlotsTreeItem; private _functionsTreeItem: RemoteFunctionsTreeItem | undefined; private _logFilesTreeItem: LogFilesTreeItem; private _siteFilesTreeItem: SiteFilesTreeItem; private _cachedVersion: FuncVersion | undefined; private _cachedHostJson: IParsedHostJson | undefined; private _cachedIsConsumption: boolean | undefined; public static pickSlotContextValue: RegExp = new RegExp(/azFuncSlot(?!s)/); public static productionContextValue: string = 'azFuncProductionSlot'; public static slotContextValue: string = 'azFuncSlot'; commandId?: string | undefined; tooltip?: string | undefined; commandArgs?: unknown[] | undefined; public constructor(subscription: ISubscriptionContext, site: Site) { this.site = new ParsedSite(site, subscription); this._subscription = subscription; this.contextValuesToAdd = [this.site.isSlot ? ResolvedFunctionAppResource.slotContextValue : ResolvedFunctionAppResource.productionContextValue]; const valuesToMask = [ this.site.siteName, this.site.slotName, this.site.defaultHostName, this.site.resourceGroup, this.site.planName, this.site.planResourceGroup, this.site.kuduHostName, this.site.gitUrl, this.site.rawSite.repositorySiteName, ...(this.site.rawSite.hostNames || []), ...(this.site.rawSite.enabledHostNames || []) ]; for (const v of valuesToMask) { if (v) { this.maskedValuesToAdd.push(v); } } } public get name(): string { return this.label; } public get label(): string { return this.site.slotName ?? this.site.fullName; } public get id(): string { return this.site.id; } public get logStreamLabel(): string { return this.site.fullName; } public async getHostRequest(): Promise<FuncHostRequest> { return { url: this.site.defaultHostUrl }; } public get description(): string | undefined { return this._state?.toLowerCase() !== 'running' ? this._state : undefined; } public get iconPath(): TreeItemIconPath { const proxyTree: SlotTreeItem = this as unknown as SlotTreeItem; return treeUtils.getIconPath(proxyTree.contextValue); } private get _state(): string | undefined { return this.site.rawSite.state; } public hasMoreChildrenImpl(): boolean { return false; } /** * NOTE: We need to be extra careful in this method because it blocks many core scenarios (e.g. deploy) if the tree item is listed as invalid */ public async refreshImpl(context: IActionContext): Promise<void> { this._cachedVersion = undefined; this._cachedHostJson = undefined; this._cachedIsConsumption = undefined; const client = await this.site.createClient(context); this.site = new ParsedSite(nonNullValue(await client.getSite(), 'site'), this._subscription); } public async getVersion(context: IActionContext): Promise<FuncVersion> { let result: FuncVersion | undefined = this._cachedVersion; if (result === undefined) { let version: FuncVersion | undefined; try { const client = await this.site.createClient(context); const appSettings: StringDictionary = await client.listApplicationSettings(); version = tryParseFuncVersion(appSettings.properties && appSettings.properties.FUNCTIONS_EXTENSION_VERSION); } catch { // ignore and use default } result = version || latestGAVersion; this._cachedVersion = result; } return result; } public async getHostJson(context: IActionContext): Promise<IParsedHostJson> { let result: IParsedHostJson | undefined = this._cachedHostJson; if (!result) { // eslint-disable-next-line @typescript-eslint/no-explicit-any let data: any; try { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment data = JSON.parse((await getFile(context, this.site, 'site/wwwroot/host.json')).data); } catch { // ignore and use default } const version: FuncVersion = await this.getVersion(context); result = parseHostJson(data, version); this._cachedHostJson = result; } return result; } public async getApplicationSettings(context: IActionContext): Promise<ApplicationSettings> { const client = await this.site.createClient(context); const appSettings: StringDictionary = await client.listApplicationSettings(); return appSettings.properties || {}; } public async setApplicationSetting(context: IActionContext, key: string, value: string): Promise<void> { const client = await this.site.createClient(context); const settings: StringDictionary = await client.listApplicationSettings(); if (!settings.properties) { settings.properties = {}; } settings.properties[key] = value; await client.updateApplicationSettings(settings); } public async getIsConsumption(context: IActionContext): Promise<boolean> { let result: boolean | undefined = this._cachedIsConsumption; if (result === undefined) { try { const client = await this.site.createClient(context); result = await client.getIsConsumption(context); } catch { // ignore and use default result = true; } this._cachedIsConsumption = result; } return result; } public async loadMoreChildrenImpl(_clearCache: boolean, context: IActionContext): Promise<AzExtTreeItem[]> { const client = await this.site.createClient(context); const siteConfig: SiteConfig = await client.getSiteConfig(); const sourceControl: SiteSourceControl = await client.getSourceControl(); const proxyTree: SlotTreeItem = this as unknown as SlotTreeItem; this.deploymentsNode = new DeploymentsTreeItem(proxyTree, { site: this.site, siteConfig, sourceControl, contextValuesToAdd: ['azFunc'] }); this.appSettingsTreeItem = new AppSettingsTreeItem(proxyTree, this.site, { contextValuesToAdd: ['azFunc'] }); this._siteFilesTreeItem = new SiteFilesTreeItem(proxyTree, { site: this.site, isReadOnly: true, contextValuesToAdd: ['azFunc'] }); this._logFilesTreeItem = new LogFilesTreeItem(proxyTree, { site: this.site, contextValuesToAdd: ['azFunc'] }); if (!this._functionsTreeItem) { this._functionsTreeItem = await RemoteFunctionsTreeItem.createFunctionsTreeItem(context, proxyTree); } const children: AzExtTreeItem[] = [this._functionsTreeItem, this.appSettingsTreeItem, this._siteFilesTreeItem, this._logFilesTreeItem, this.deploymentsNode]; if (!this.site.isSlot) { this._slotsTreeItem = new SlotsTreeItem(proxyTree); children.push(this._slotsTreeItem); } return children; } // eslint-disable-next-line @typescript-eslint/require-await public async pickTreeItemImpl(expectedContextValues: (string | RegExp)[]): Promise<AzExtTreeItem | undefined> { if (!this.site.isSlot) { for (const expectedContextValue of expectedContextValues) { switch (expectedContextValue) { case SlotsTreeItem.contextValue: case ResolvedFunctionAppResource.slotContextValue: return this._slotsTreeItem; default: } } } for (const expectedContextValue of expectedContextValues) { if (expectedContextValue instanceof RegExp) { const appSettingsContextValues = [AppSettingsTreeItem.contextValue, AppSettingTreeItem.contextValue]; if (matchContextValue(expectedContextValue, appSettingsContextValues)) { return this.appSettingsTreeItem; } const deploymentsContextValues = [DeploymentsTreeItem.contextValueConnected, DeploymentsTreeItem.contextValueUnconnected, DeploymentTreeItem.contextValue]; if (matchContextValue(expectedContextValue, deploymentsContextValues)) { return this.deploymentsNode; } if (matchContextValue(expectedContextValue, [ResolvedFunctionAppResource.slotContextValue])) { return this._slotsTreeItem; } } if (typeof expectedContextValue === 'string') { // DeploymentTreeItem.contextValue is a RegExp, but the passed in contextValue can be a string so check for a match if (DeploymentTreeItem.contextValue.test(expectedContextValue)) { return this.deploymentsNode; } } else if (matchesAnyPart(expectedContextValue, ProjectResource.Functions, ProjectResource.Function)) { return this._functionsTreeItem; } } return undefined; } public compareChildrenImpl(): number { return 0; // already sorted } public async isReadOnly(context: IActionContext): Promise<boolean> { const client = await this.site.createClient(context); const appSettings: StringDictionary = await client.listApplicationSettings(); return [runFromPackageKey, 'WEBSITE_RUN_FROM_ZIP'].some(key => appSettings.properties && envUtils.isEnvironmentVariableSet(appSettings.properties[key])); } public async deleteTreeItemImpl(context: IActionContext): Promise<void> { const wizardContext: IDeleteSiteWizardContext = Object.assign(context, { site: this.site, ...(await createActivityContext()) }); const confirmationMessage = localize('deleteConfirmation', 'Are you sure you want to delete function app "{0}"?', this.site.fullName); const wizard = new AzureWizard(wizardContext, { title: localize('deleteSwa', 'Delete Function App "{0}"', this.label), promptSteps: [new DeleteConfirmationStep(confirmationMessage), new DeleteLastServicePlanStep()], executeSteps: [new DeleteSiteStep()] }); await wizard.prompt(); await wizard.execute(); } } function matchContextValue(expectedContextValue: RegExp | string, matches: (string | RegExp)[]): boolean { if (expectedContextValue instanceof RegExp) { return matches.some((match) => { if (match instanceof RegExp) { return expectedContextValue.toString() === match.toString(); } return expectedContextValue.test(match); }); } else { return matches.some((match) => { if (match instanceof RegExp) { return match.test(expectedContextValue); } return expectedContextValue === match; }); } }
the_stack
import { CloudErrorMapper, BaseResourceMapper } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export const CloudError = CloudErrorMapper; export const BaseResource = BaseResourceMapper; export const Resource: msRest.CompositeMapper = { serializedName: "Resource", type: { name: "Composite", className: "Resource", modelProperties: { id: { readOnly: true, serializedName: "id", type: { name: "String" } }, name: { readOnly: true, serializedName: "name", type: { name: "String" } }, location: { required: true, serializedName: "location", type: { name: "String" } }, type: { readOnly: true, serializedName: "type", type: { name: "String" } }, tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } } } } }; export const WebServiceKeys: msRest.CompositeMapper = { serializedName: "WebServiceKeys", type: { name: "Composite", className: "WebServiceKeys", modelProperties: { primary: { serializedName: "primary", type: { name: "String" } }, secondary: { serializedName: "secondary", type: { name: "String" } } } } }; export const RealtimeConfiguration: msRest.CompositeMapper = { serializedName: "RealtimeConfiguration", type: { name: "Composite", className: "RealtimeConfiguration", modelProperties: { maxConcurrentCalls: { serializedName: "maxConcurrentCalls", constraints: { InclusiveMaximum: 200, InclusiveMinimum: 4 }, type: { name: "Number" } } } } }; export const DiagnosticsConfiguration: msRest.CompositeMapper = { serializedName: "DiagnosticsConfiguration", type: { name: "Composite", className: "DiagnosticsConfiguration", modelProperties: { level: { required: true, serializedName: "level", type: { name: "String" } }, expiry: { serializedName: "expiry", type: { name: "DateTime" } } } } }; export const StorageAccount: msRest.CompositeMapper = { serializedName: "StorageAccount", type: { name: "Composite", className: "StorageAccount", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, key: { serializedName: "key", type: { name: "String" } } } } }; export const MachineLearningWorkspace: msRest.CompositeMapper = { serializedName: "MachineLearningWorkspace", type: { name: "Composite", className: "MachineLearningWorkspace", modelProperties: { id: { required: true, serializedName: "id", type: { name: "String" } } } } }; export const CommitmentPlan: msRest.CompositeMapper = { serializedName: "CommitmentPlan", type: { name: "Composite", className: "CommitmentPlan", modelProperties: { id: { required: true, serializedName: "id", type: { name: "String" } } } } }; export const ColumnSpecification: msRest.CompositeMapper = { serializedName: "ColumnSpecification", type: { name: "Composite", className: "ColumnSpecification", modelProperties: { type: { required: true, serializedName: "type", type: { name: "String" } }, format: { serializedName: "format", type: { name: "String" } }, enum: { serializedName: "enum", type: { name: "Sequence", element: { type: { name: "Object" } } } }, xMsIsnullable: { serializedName: "x-ms-isnullable", type: { name: "Boolean" } }, xMsIsordered: { serializedName: "x-ms-isordered", type: { name: "Boolean" } } } } }; export const TableSpecification: msRest.CompositeMapper = { serializedName: "TableSpecification", type: { name: "Composite", className: "TableSpecification", modelProperties: { title: { serializedName: "title", type: { name: "String" } }, description: { serializedName: "description", type: { name: "String" } }, type: { required: true, serializedName: "type", defaultValue: 'object', type: { name: "String" } }, format: { serializedName: "format", type: { name: "String" } }, properties: { serializedName: "properties", type: { name: "Dictionary", value: { type: { name: "Composite", className: "ColumnSpecification" } } } } } } }; export const ServiceInputOutputSpecification: msRest.CompositeMapper = { serializedName: "ServiceInputOutputSpecification", type: { name: "Composite", className: "ServiceInputOutputSpecification", modelProperties: { title: { serializedName: "title", type: { name: "String" } }, description: { serializedName: "description", type: { name: "String" } }, type: { required: true, serializedName: "type", defaultValue: 'object', type: { name: "String" } }, properties: { required: true, serializedName: "properties", type: { name: "Dictionary", value: { type: { name: "Composite", className: "TableSpecification" } } } } } } }; export const ExampleRequest: msRest.CompositeMapper = { serializedName: "ExampleRequest", type: { name: "Composite", className: "ExampleRequest", modelProperties: { inputs: { serializedName: "inputs", type: { name: "Dictionary", value: { type: { name: "Sequence", element: { type: { name: "Sequence", element: { type: { name: "Object" } } } } } } } }, globalParameters: { serializedName: "globalParameters", type: { name: "Dictionary", value: { type: { name: "Object" } } } } } } }; export const BlobLocation: msRest.CompositeMapper = { serializedName: "BlobLocation", type: { name: "Composite", className: "BlobLocation", modelProperties: { uri: { required: true, serializedName: "uri", type: { name: "String" } }, credentials: { serializedName: "credentials", type: { name: "String" } } } } }; export const InputPort: msRest.CompositeMapper = { serializedName: "InputPort", type: { name: "Composite", className: "InputPort", modelProperties: { type: { serializedName: "type", defaultValue: 'Dataset', type: { name: "String" } } } } }; export const OutputPort: msRest.CompositeMapper = { serializedName: "OutputPort", type: { name: "Composite", className: "OutputPort", modelProperties: { type: { serializedName: "type", defaultValue: 'Dataset', type: { name: "String" } } } } }; export const ModeValueInfo: msRest.CompositeMapper = { serializedName: "ModeValueInfo", type: { name: "Composite", className: "ModeValueInfo", modelProperties: { interfaceString: { serializedName: "interfaceString", type: { name: "String" } }, parameters: { serializedName: "parameters", type: { name: "Sequence", element: { type: { name: "Composite", className: "ModuleAssetParameter" } } } } } } }; export const ModuleAssetParameter: msRest.CompositeMapper = { serializedName: "ModuleAssetParameter", type: { name: "Composite", className: "ModuleAssetParameter", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, parameterType: { serializedName: "parameterType", type: { name: "String" } }, modeValuesInfo: { serializedName: "modeValuesInfo", type: { name: "Dictionary", value: { type: { name: "Composite", className: "ModeValueInfo" } } } } } } }; export const AssetItem: msRest.CompositeMapper = { serializedName: "AssetItem", type: { name: "Composite", className: "AssetItem", modelProperties: { name: { required: true, serializedName: "name", type: { name: "String" } }, id: { serializedName: "id", type: { name: "String" } }, type: { required: true, serializedName: "type", type: { name: "String" } }, locationInfo: { required: true, serializedName: "locationInfo", type: { name: "Composite", className: "BlobLocation" } }, inputPorts: { serializedName: "inputPorts", type: { name: "Dictionary", value: { type: { name: "Composite", className: "InputPort" } } } }, outputPorts: { serializedName: "outputPorts", type: { name: "Dictionary", value: { type: { name: "Composite", className: "OutputPort" } } } }, metadata: { serializedName: "metadata", type: { name: "Dictionary", value: { type: { name: "String" } } } }, parameters: { serializedName: "parameters", type: { name: "Sequence", element: { type: { name: "Composite", className: "ModuleAssetParameter" } } } } } } }; export const WebServiceParameter: msRest.CompositeMapper = { serializedName: "WebServiceParameter", type: { name: "Composite", className: "WebServiceParameter", modelProperties: { value: { serializedName: "value", type: { name: "Object" } }, certificateThumbprint: { serializedName: "certificateThumbprint", type: { name: "String" } } } } }; export const WebServiceProperties: msRest.CompositeMapper = { serializedName: "WebServiceProperties", type: { name: "Composite", polymorphicDiscriminator: { serializedName: "packageType", clientName: "packageType" }, uberParent: "WebServiceProperties", className: "WebServiceProperties", modelProperties: { title: { serializedName: "title", type: { name: "String" } }, description: { serializedName: "description", type: { name: "String" } }, createdOn: { readOnly: true, serializedName: "createdOn", type: { name: "DateTime" } }, modifiedOn: { readOnly: true, serializedName: "modifiedOn", type: { name: "DateTime" } }, provisioningState: { readOnly: true, serializedName: "provisioningState", type: { name: "String" } }, keys: { serializedName: "keys", type: { name: "Composite", className: "WebServiceKeys" } }, readOnly: { serializedName: "readOnly", type: { name: "Boolean" } }, swaggerLocation: { readOnly: true, serializedName: "swaggerLocation", type: { name: "String" } }, exposeSampleData: { serializedName: "exposeSampleData", type: { name: "Boolean" } }, realtimeConfiguration: { serializedName: "realtimeConfiguration", type: { name: "Composite", className: "RealtimeConfiguration" } }, diagnostics: { serializedName: "diagnostics", type: { name: "Composite", className: "DiagnosticsConfiguration" } }, storageAccount: { serializedName: "storageAccount", type: { name: "Composite", className: "StorageAccount" } }, machineLearningWorkspace: { serializedName: "machineLearningWorkspace", type: { name: "Composite", className: "MachineLearningWorkspace" } }, commitmentPlan: { serializedName: "commitmentPlan", type: { name: "Composite", className: "CommitmentPlan" } }, input: { serializedName: "input", type: { name: "Composite", className: "ServiceInputOutputSpecification" } }, output: { serializedName: "output", type: { name: "Composite", className: "ServiceInputOutputSpecification" } }, exampleRequest: { serializedName: "exampleRequest", type: { name: "Composite", className: "ExampleRequest" } }, assets: { serializedName: "assets", type: { name: "Dictionary", value: { type: { name: "Composite", className: "AssetItem" } } } }, parameters: { serializedName: "parameters", type: { name: "Dictionary", value: { type: { name: "Composite", className: "WebServiceParameter" } } } }, payloadsInBlobStorage: { serializedName: "payloadsInBlobStorage", type: { name: "Boolean" } }, payloadsLocation: { serializedName: "payloadsLocation", type: { name: "Composite", className: "BlobLocation" } }, packageType: { required: true, serializedName: "packageType", type: { name: "String" } } } } }; export const WebService: msRest.CompositeMapper = { serializedName: "WebService", type: { name: "Composite", className: "WebService", modelProperties: { ...Resource.type.modelProperties, properties: { required: true, serializedName: "properties", type: { name: "Composite", className: "WebServiceProperties" } } } } }; export const GraphNode: msRest.CompositeMapper = { serializedName: "GraphNode", type: { name: "Composite", className: "GraphNode", modelProperties: { assetId: { serializedName: "assetId", type: { name: "String" } }, inputId: { serializedName: "inputId", type: { name: "String" } }, outputId: { serializedName: "outputId", type: { name: "String" } }, parameters: { serializedName: "parameters", type: { name: "Dictionary", value: { type: { name: "Composite", className: "WebServiceParameter" } } } } } } }; export const GraphEdge: msRest.CompositeMapper = { serializedName: "GraphEdge", type: { name: "Composite", className: "GraphEdge", modelProperties: { sourceNodeId: { serializedName: "sourceNodeId", type: { name: "String" } }, sourcePortId: { serializedName: "sourcePortId", type: { name: "String" } }, targetNodeId: { serializedName: "targetNodeId", type: { name: "String" } }, targetPortId: { serializedName: "targetPortId", type: { name: "String" } } } } }; export const GraphParameterLink: msRest.CompositeMapper = { serializedName: "GraphParameterLink", type: { name: "Composite", className: "GraphParameterLink", modelProperties: { nodeId: { required: true, serializedName: "nodeId", type: { name: "String" } }, parameterKey: { required: true, serializedName: "parameterKey", type: { name: "String" } } } } }; export const GraphParameter: msRest.CompositeMapper = { serializedName: "GraphParameter", type: { name: "Composite", className: "GraphParameter", modelProperties: { description: { serializedName: "description", type: { name: "String" } }, type: { required: true, serializedName: "type", type: { name: "String" } }, links: { required: true, serializedName: "links", type: { name: "Sequence", element: { type: { name: "Composite", className: "GraphParameterLink" } } } } } } }; export const GraphPackage: msRest.CompositeMapper = { serializedName: "GraphPackage", type: { name: "Composite", className: "GraphPackage", modelProperties: { nodes: { serializedName: "nodes", type: { name: "Dictionary", value: { type: { name: "Composite", className: "GraphNode" } } } }, edges: { serializedName: "edges", type: { name: "Sequence", element: { type: { name: "Composite", className: "GraphEdge" } } } }, graphParameters: { serializedName: "graphParameters", type: { name: "Dictionary", value: { type: { name: "Composite", className: "GraphParameter" } } } } } } }; export const WebServicePropertiesForGraph: msRest.CompositeMapper = { serializedName: "Graph", type: { name: "Composite", polymorphicDiscriminator: WebServiceProperties.type.polymorphicDiscriminator, uberParent: "WebServiceProperties", className: "WebServicePropertiesForGraph", modelProperties: { ...WebServiceProperties.type.modelProperties, packageProperty: { serializedName: "package", type: { name: "Composite", className: "GraphPackage" } } } } }; export const AsyncOperationErrorInfo: msRest.CompositeMapper = { serializedName: "AsyncOperationErrorInfo", type: { name: "Composite", className: "AsyncOperationErrorInfo", modelProperties: { code: { readOnly: true, serializedName: "code", type: { name: "String" } }, target: { readOnly: true, serializedName: "target", type: { name: "String" } }, message: { readOnly: true, serializedName: "message", type: { name: "String" } }, details: { readOnly: true, serializedName: "details", type: { name: "Sequence", element: { type: { name: "Composite", className: "AsyncOperationErrorInfo" } } } } } } }; export const AsyncOperationStatus: msRest.CompositeMapper = { serializedName: "AsyncOperationStatus", type: { name: "Composite", className: "AsyncOperationStatus", modelProperties: { id: { readOnly: true, serializedName: "id", type: { name: "String" } }, name: { readOnly: true, serializedName: "name", type: { name: "String" } }, provisioningState: { readOnly: true, serializedName: "provisioningState", type: { name: "String" } }, startTime: { readOnly: true, serializedName: "startTime", type: { name: "DateTime" } }, endTime: { readOnly: true, serializedName: "endTime", type: { name: "DateTime" } }, percentComplete: { readOnly: true, serializedName: "percentComplete", type: { name: "Number" } }, errorInfo: { readOnly: true, serializedName: "errorInfo", type: { name: "Composite", className: "AsyncOperationErrorInfo" } } } } }; export const OperationDisplayInfo: msRest.CompositeMapper = { serializedName: "OperationDisplayInfo", type: { name: "Composite", className: "OperationDisplayInfo", modelProperties: { description: { readOnly: true, serializedName: "description", type: { name: "String" } }, operation: { readOnly: true, serializedName: "operation", type: { name: "String" } }, provider: { readOnly: true, serializedName: "provider", type: { name: "String" } }, resource: { readOnly: true, serializedName: "resource", type: { name: "String" } } } } }; export const OperationEntity: msRest.CompositeMapper = { serializedName: "OperationEntity", type: { name: "Composite", className: "OperationEntity", modelProperties: { name: { readOnly: true, serializedName: "name", type: { name: "String" } }, display: { serializedName: "display", type: { name: "Composite", className: "OperationDisplayInfo" } } } } }; export const OperationEntityListResult: msRest.CompositeMapper = { serializedName: "OperationEntityListResult", type: { name: "Composite", className: "OperationEntityListResult", modelProperties: { value: { readOnly: true, serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "OperationEntity" } } } } } } }; export const PaginatedWebServicesList: msRest.CompositeMapper = { serializedName: "PaginatedWebServicesList", type: { name: "Composite", className: "PaginatedWebServicesList", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "WebService" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } }; export const discriminators = { 'WebServiceProperties' : WebServiceProperties, 'WebServiceProperties.Graph' : WebServicePropertiesForGraph };
the_stack
export default class RTC extends Listenable { /** * Exposes the private helper for converting a WebRTC MediaStream to a * JitsiLocalTrack. * * @param {Array<Object>} tracksInfo * @returns {Array<JitsiLocalTrack>} */ static newCreateLocalTracks(tracksInfo: Array<any>): Array<JitsiLocalTrack>; /** * Creates the local MediaStreams. * @param {object} [options] Optional parameters. * @param {array} options.devices The devices that will be requested. * @param {string} options.resolution Resolution constraints. * @param {string} options.cameraDeviceId * @param {string} options.micDeviceId * @returns {*} Promise object that will receive the new JitsiTracks */ static obtainAudioAndVideoPermissions(options?: { devices: any[]; resolution: string; cameraDeviceId: string; micDeviceId: string; }): any; /** * * @param eventType * @param listener */ static addListener(eventType: any, listener: any): void; /** * * @param eventType * @param listener */ static removeListener(eventType: any, listener: any): void; /** * * @param options */ static init(options?: {}): void; /** * */ static getPCConstraints(isP2P: any): any; /** * * @param elSelector * @param stream */ static attachMediaStream(elSelector: any, stream: any): any; /** * Returns the id of the given stream. * @param {MediaStream} stream */ static getStreamID(stream: any): any; /** * Returns the id of the given track. * @param {MediaStreamTrack} track */ static getTrackID(track: any): any; /** * Returns true if retrieving the list of input devices is supported * and false if not. */ static isDeviceListAvailable(): boolean; /** * Returns true if changing the input (camera / microphone) or output * (audio) device is supported and false if not. * @param {string} [deviceType] Type of device to change. Default is * undefined or 'input', 'output' - for audio output device change. * @returns {boolean} true if available, false otherwise. */ static isDeviceChangeAvailable(deviceType?: string): boolean; /** * Returns whether the current execution environment supports WebRTC (for * use within this library). * * @returns {boolean} {@code true} if WebRTC is supported in the current * execution environment (for use within this library); {@code false}, * otherwise. */ static isWebRtcSupported(): boolean; /** * Returns currently used audio output device id, '' stands for default * device * @returns {string} */ static getAudioOutputDevice(): string; /** * Returns list of available media devices if its obtained, otherwise an * empty array is returned/ * @returns {array} list of available media devices. */ static getCurrentlyAvailableMediaDevices(): any[]; /** * Returns event data for device to be reported to stats. * @returns {MediaDeviceInfo} device. */ static getEventDataForActiveDevice(device: any): any; /** * Sets current audio output device. * @param {string} deviceId Id of 'audiooutput' device from * navigator.mediaDevices.enumerateDevices(). * @returns {Promise} resolves when audio output is changed, is rejected * otherwise */ static setAudioOutputDevice(deviceId: string): Promise<any>; /** * Returns <tt>true<tt/> if given WebRTC MediaStream is considered a valid * "user" stream which means that it's not a "receive only" stream nor a * "mixed" JVB stream. * * Clients that implement Unified Plan, such as Firefox use recvonly * "streams/channels/tracks" for receiving remote stream/tracks, as opposed * to Plan B where there are only 3 channels: audio, video and data. * * @param {MediaStream} stream The WebRTC MediaStream instance. * @returns {boolean} */ static isUserStream(stream: any): boolean; /** * Returns <tt>true<tt/> if a WebRTC MediaStream identified by given stream * ID is considered a valid "user" stream which means that it's not a * "receive only" stream nor a "mixed" JVB stream. * * Clients that implement Unified Plan, such as Firefox use recvonly * "streams/channels/tracks" for receiving remote stream/tracks, as opposed * to Plan B where there are only 3 channels: audio, video and data. * * @param {string} streamId The id of WebRTC MediaStream. * @returns {boolean} */ static isUserStreamById(streamId: string): boolean; /** * Allows to receive list of available cameras/microphones. * @param {function} callback Would receive array of devices as an * argument. */ static enumerateDevices(callback: Function): void; /** * A method to handle stopping of the stream. * One point to handle the differences in various implementations. * @param {MediaStream} mediaStream MediaStream object to stop. */ static stopMediaStream(mediaStream: any): void; /** * Returns whether the desktop sharing is enabled or not. * @returns {boolean} */ static isDesktopSharingEnabled(): boolean; /** * * @param conference * @param options */ constructor(conference: any, options?: {}); conference: any; /** * A map of active <tt>TraceablePeerConnection</tt>. * @type {Map.<number, TraceablePeerConnection>} */ peerConnections: Map<number, TraceablePeerConnection>; localTracks: any[]; options: {}; /** * Removes any listeners and stored state from this {@code RTC} instance. * * @returns {void} */ destroy(): void; /** * Initializes the bridge channel of this instance. * At least one of both, peerconnection or wsUrl parameters, must be * given. * @param {RTCPeerConnection} [peerconnection] WebRTC peer connection * instance. * @param {string} [wsUrl] WebSocket URL. */ initializeBridgeChannel(peerconnection?: any, wsUrl?: string): void; /** * Should be called when current media session ends and after the * PeerConnection has been closed using PeerConnection.close() method. */ onCallEnded(): void; /** * Sets the maximum video size the local participant should receive from * remote participants. Will cache the value and send it through the channel * once it is created. * * @param {number} maxFrameHeightPixels the maximum frame height, in pixels, * this receiver is willing to receive. * @returns {void} */ setReceiverVideoConstraint(maxFrameHeight: any): void; /** * Elects the participants with the given ids to be the selected * participants in order to always receive video for this participant (even * when last n is enabled). If there is no channel we store it and send it * through the channel once it is created. * * @param {Array<string>} ids - The user ids. * @throws NetworkError or InvalidStateError or Error if the operation * fails. * @returns {void} */ selectEndpoints(ids: Array<string>): void; /** * Elects the participant with the given id to be the pinned participant in * order to always receive video for this participant (even when last n is * enabled). * @param {stirng} id The user id. * @throws NetworkError or InvalidStateError or Error if the operation * fails. */ pinEndpoint(id: any): void; /** * Creates new <tt>TraceablePeerConnection</tt> * @param {SignalingLayer} signaling The signaling layer that will * provide information about the media or participants which is not * carried over SDP. * @param {object} iceConfig An object describing the ICE config like * defined in the WebRTC specification. * @param {boolean} isP2P Indicates whether or not the new TPC will be used * in a peer to peer type of session. * @param {object} options The config options. * @param {boolean} options.enableInsertableStreams - Set to true when the insertable streams constraints is to be * enabled on the PeerConnection. * @param {boolean} options.disableSimulcast If set to 'true' will disable * the simulcast. * @param {boolean} options.disableRtx If set to 'true' will disable the * RTX. * @param {boolean} options.disableH264 If set to 'true' H264 will be * disabled by removing it from the SDP. * @param {boolean} options.preferH264 If set to 'true' H264 will be * preferred over other video codecs. * @param {boolean} options.startSilent If set to 'true' no audio will be sent or received. * @return {TraceablePeerConnection} */ createPeerConnection(signaling: any, iceConfig: object, isP2P: boolean, options: { enableInsertableStreams: boolean; disableSimulcast: boolean; disableRtx: boolean; disableH264: boolean; preferH264: boolean; startSilent: boolean; }): TraceablePeerConnection; /** * * @param track */ addLocalTrack(track: any): void; /** * Returns the current value for "lastN" - the amount of videos are going * to be delivered. When set to -1 for unlimited or all available videos. * @return {number} */ getLastN(): number; /** * @return {Object} The sender video constraints signaled from the brridge. */ getSenderVideoConstraints(): any; /** * Get local video track. * @returns {JitsiLocalTrack|undefined} */ getLocalVideoTrack(): JitsiLocalTrack | undefined; /** * Get local audio track. * @returns {JitsiLocalTrack|undefined} */ getLocalAudioTrack(): JitsiLocalTrack | undefined; /** * Returns the local tracks of the given media type, or all local tracks if * no specific type is given. * @param {MediaType} [mediaType] Optional media type filter. * (audio or video). */ getLocalTracks(mediaType?: typeof MediaType): any[]; /** * Obtains all remote tracks currently known to this RTC module instance. * @param {MediaType} [mediaType] The remote tracks will be filtered * by their media type if this argument is specified. * @return {Array<JitsiRemoteTrack>} */ getRemoteTracks(mediaType?: typeof MediaType): Array<any>; /** * Set mute for all local audio streams attached to the conference. * @param value The mute value. * @returns {Promise} */ setAudioMute(value: any): Promise<any>; /** * * @param track */ removeLocalTrack(track: any): void; /** * Removes all JitsiRemoteTracks associated with given MUC nickname * (resource part of the JID). Returns array of removed tracks. * * @param {string} Owner The resource part of the MUC JID. * @returns {JitsiRemoteTrack[]} */ removeRemoteTracks(owner: any): any[]; /** * Closes the currently opened bridge channel. */ closeBridgeChannel(): void; /** * * @param {TraceablePeerConnection} tpc * @param {number} ssrc * @param {number} audioLevel * @param {boolean} isLocal */ setAudioLevel(tpc: TraceablePeerConnection, ssrc: number, audioLevel: number, isLocal: boolean): void; /** * Sends message via the bridge channel. * @param {string} to The id of the endpoint that should receive the * message. If "" the message will be sent to all participants. * @param {object} payload The payload of the message. * @throws NetworkError or InvalidStateError or Error if the operation * fails or there is no data channel created. */ sendChannelMessage(to: string, payload: object): void; /** * Selects a new value for "lastN". The requested amount of videos are going * to be delivered after the value is in effect. Set to -1 for unlimited or * all available videos. * @param {number} value the new value for lastN. */ setLastN(value: number): void; /** * Indicates if the endpoint id is currently included in the last N. * @param {string} id The endpoint id that we check for last N. * @returns {boolean} true if the endpoint id is in the last N or if we * don't have bridge channel support, otherwise we return false. */ isInLastN(id: string): boolean; } import Listenable from "../util/Listenable"; import TraceablePeerConnection from "./TraceablePeerConnection"; import BridgeChannel from "./BridgeChannel"; import JitsiLocalTrack from "./JitsiLocalTrack"; import * as MediaType from "../../service/RTC/MediaType";
the_stack
import { resolve } from 'path'; import * as fs from 'fs-extra'; import { rollup, watch, Plugin, OutputPlugin, TreeshakingOptions, RollupWatchOptions, RollupBuild, RollupOutput, } from 'rollup'; import nodeResolve from '@rollup/plugin-node-resolve'; import commonjs from '@rollup/plugin-commonjs'; import json from '@rollup/plugin-json'; import rollupTypescript from 'rollup-plugin-typescript2'; import replace from '@rollup/plugin-replace'; import sourcemaps from 'rollup-plugin-sourcemaps'; import { terser } from 'rollup-plugin-terser'; import { clearLine, clearConsole, convertPkgNameToKebabCase, convertKebabCaseToPascalCase, } from './utils'; import { logTsError, logError } from './errorUtils'; ///////////////////////////////////// // create rollup config interface CreateRollupConfig { (input: { tsconfigPath?: string; addUmdBuild: boolean; kebabCasePkgName: string; pkgJsonSideEffects: boolean; pkgJsonPeerDependencyKeys: string[]; pkgJsonUmdGlobalDependencies?: { [key: string]: string }; }): { buildPluginsDefault: Plugin[]; buildPluginsWithNodeEnvDevelopment: Plugin[]; buildPluginsWithNodeEnvProduction: Plugin[]; outputPluginsDefault: OutputPlugin[]; outputPluginsProduction: OutputPlugin[]; treeshakeOptions: TreeshakingOptions; umdNameForPkg?: string; umdExternalDependencies?: string[]; umdDependencyGlobals?: { [key: string]: string }; }; } export const createRollupConfig: CreateRollupConfig = ({ tsconfigPath, addUmdBuild, kebabCasePkgName, pkgJsonSideEffects, pkgJsonPeerDependencyKeys, pkgJsonUmdGlobalDependencies, }) => { const buildPluginsDefault: Plugin[] = [ nodeResolve({ preferBuiltins: true }), commonjs(), json(), rollupTypescript({ // verbosity: 3, // use to debug tsconfigDefaults: { compilerOptions: { target: 'ES2018', // types: [] eliminates global type pollution in builds // and ensures that the only types allowed // are explicitly set in tsconfig or are imported into source files types: [], // generate *.d.ts files by default declaration: true, // enforces convention that all files to be included in the build are in the src directory // this doesn't prevent other non-build files like *.mock.ts from being outside the src directory rootDir: './src', }, // include rollpkg types that stub process.env.NODE_ENV and __DEV__ // so they can be used without polluting the global type space with all node types etc include: ['src', './node_modules/rollpkg/configs/types'], // exclude tests, mocks and snapshots exclude: [ '**/__tests__', '**/__mocks__', '**/__snapshots__', '**/*.test.*', '**/*.spec.*', '**/*.mock.*', ], }, tsconfig: tsconfigPath, tsconfigOverride: { compilerOptions: { // rollup requires module to be es2015 or esnext module: 'ESNext', // always generate source maps which are used by rollup to create the actual source map // without this rollup creates blank source maps // note that the tsconfig "inlineSources" option has no effect on how rollup generates source maps // as rollup has it's own inline sources option, "sourcemapExcludeSources" which defaults to false sourceMap: true, }, }, include: ['**/*.ts+(|x)', '**/*.js+(|x)'], }), sourcemaps(), replace({ __DEV__: "process.env.NODE_ENV !== 'production'", preventAssignment: true, }), ]; const buildPluginsWithNodeEnvDevelopment: Plugin[] = [ ...buildPluginsDefault, replace({ 'process.env.NODE_ENV': JSON.stringify('development'), preventAssignment: true, }), ]; const buildPluginsWithNodeEnvProduction: Plugin[] = [ ...buildPluginsDefault, replace({ 'process.env.NODE_ENV': JSON.stringify('production'), preventAssignment: true, }), ]; const outputPluginsDefault: OutputPlugin[] = []; const outputPluginsProduction: OutputPlugin[] = [ terser({ format: { comments: false } }), ]; const treeshakeOptions: TreeshakingOptions = { annotations: true, moduleSideEffects: pkgJsonSideEffects, propertyReadSideEffects: pkgJsonSideEffects, tryCatchDeoptimization: pkgJsonSideEffects, unknownGlobalSideEffects: pkgJsonSideEffects, }; let umdExternalDependencies; let umdDependencyGlobals: { [key: string]: string } | undefined; let umdNameForPkg; if (addUmdBuild) { // umdExternalDependencies is an array of external module ids that rollup // will not include in the build umdExternalDependencies = pkgJsonUmdGlobalDependencies ? Object.keys(pkgJsonUmdGlobalDependencies) : pkgJsonPeerDependencyKeys; // umdDependencyGlobals is an object where the keys are the module ids (the umdExternalDependencies list) // and the values are what those modules will be available in the global scope as // for example { 'react-dom': 'ReactDOM' } because react-dom will be available on the window as ReactDOM if (pkgJsonUmdGlobalDependencies) { umdDependencyGlobals = pkgJsonUmdGlobalDependencies; } else { pkgJsonPeerDependencyKeys.forEach((peerDep) => { umdDependencyGlobals = {}; umdDependencyGlobals[peerDep] = convertKebabCaseToPascalCase( convertPkgNameToKebabCase(peerDep), ); }); } umdNameForPkg = convertKebabCaseToPascalCase(kebabCasePkgName); } return { buildPluginsDefault, buildPluginsWithNodeEnvDevelopment, buildPluginsWithNodeEnvProduction, outputPluginsDefault, outputPluginsProduction, treeshakeOptions, umdNameForPkg, umdExternalDependencies, umdDependencyGlobals, }; }; ///////////////////////////////////// ///////////////////////////////////// // rollup watch interface RollupWatch { (input: { kebabCasePkgName: string; pkgJsonDependencyKeys: string[]; pkgJsonPeerDependencyKeys: string[]; entryFile: string; treeshakeOptions: TreeshakingOptions; buildPluginsDefault: Plugin[]; outputPluginsDefault: OutputPlugin[]; }): void; } export const rollupWatch: RollupWatch = ({ kebabCasePkgName, pkgJsonDependencyKeys, pkgJsonPeerDependencyKeys, entryFile, treeshakeOptions, buildPluginsDefault, outputPluginsDefault, }) => { // exit 0 from watch mode on ctrl-c (SIGINT) etc so can chain npm scripts: rollpkg watch && ... // the ... will run after rollpkg watch only if it exits 0 const exitWatch = () => { clearLine(); console.log('ROLLPKG WATCH END 👀👋', '\n'); process.exit(0); }; process.on('SIGINT', exitWatch); process.on('SIGTERM', exitWatch); process.on('SIGBREAK', exitWatch); const esmWatchOptions: RollupWatchOptions = { external: [...pkgJsonDependencyKeys, ...pkgJsonPeerDependencyKeys], input: entryFile, treeshake: treeshakeOptions, plugins: buildPluginsDefault, output: { file: `dist/${kebabCasePkgName}.esm.js`, format: 'esm', sourcemap: true, plugins: outputPluginsDefault, }, }; // in watch mode only create esm build const watcher = watch(esmWatchOptions); const earth = ['🌎', '🌏', '🌍']; let currentEarth = 2; const rotateEarth = () => { if (currentEarth === 2) currentEarth = 0; else { currentEarth = currentEarth + 1; } return earth[currentEarth]; }; watcher.on('event', (event) => { switch (event.code) { case 'START': break; case 'BUNDLE_START': clearConsole(); console.log(`${rotateEarth()} Rollpkg building...`, '\n'); break; case 'BUNDLE_END': clearConsole(); console.log(`${earth[currentEarth]} Rollpkg build successful!`, '\n'); console.log('Watching for changes...', '\n'); break; case 'END': break; case 'ERROR': clearConsole(); if (event.error.plugin === 'rpt2') { logTsError({ message: event.error.message }); } else { logError({ fullError: event.error }); } console.log('Watching for changes...', '\n'); break; } }); }; ///////////////////////////////////// ///////////////////////////////////// // create rollup bundles interface CreateBundles { (input: { entryFile: string; pkgJsonDependencyKeys: string[]; pkgJsonPeerDependencyKeys: string[]; umdExternalDependencies?: string[]; treeshakeOptions: TreeshakingOptions; buildPluginsDefault: Plugin[]; buildPluginsWithNodeEnvDevelopment: Plugin[]; buildPluginsWithNodeEnvProduction: Plugin[]; addUmdBuild: boolean; }): Promise<[RollupBuild, RollupBuild, RollupBuild?, RollupBuild?]>; } export const createBundles: CreateBundles = ({ entryFile, pkgJsonDependencyKeys, pkgJsonPeerDependencyKeys, umdExternalDependencies, treeshakeOptions, buildPluginsDefault, buildPluginsWithNodeEnvDevelopment, buildPluginsWithNodeEnvProduction, addUmdBuild, }) => Promise.all([ // default bundle - used for esm and cjs dev builds rollup({ external: [...pkgJsonDependencyKeys, ...pkgJsonPeerDependencyKeys], input: entryFile, treeshake: treeshakeOptions, plugins: buildPluginsDefault, }), // cjs production build rollup({ external: [...pkgJsonDependencyKeys, ...pkgJsonPeerDependencyKeys], input: entryFile, treeshake: treeshakeOptions, plugins: buildPluginsWithNodeEnvProduction, }), // umd development build addUmdBuild ? rollup({ external: umdExternalDependencies, input: entryFile, treeshake: treeshakeOptions, plugins: buildPluginsWithNodeEnvDevelopment, }) : undefined, // umd production build addUmdBuild ? rollup({ external: umdExternalDependencies, input: entryFile, treeshake: treeshakeOptions, plugins: buildPluginsWithNodeEnvProduction, }) : undefined, ]); ///////////////////////////////////// ///////////////////////////////////// // write rollup bundles interface WriteBundles { (input: { cwd: string; kebabCasePkgName: string; bundleDefault: RollupBuild; bundleCjsProd: RollupBuild; bundleUmdDev?: RollupBuild; bundleUmdProd?: RollupBuild; outputPluginsDefault: OutputPlugin[]; outputPluginsProduction: OutputPlugin[]; umdNameForPkg?: string; umdDependencyGlobals?: { [key: string]: string }; }): Promise< [ RollupOutput, RollupOutput, RollupOutput, void, RollupOutput?, RollupOutput?, ] >; } export const writeBundles: WriteBundles = ({ cwd, kebabCasePkgName, bundleDefault, bundleCjsProd, bundleUmdDev, bundleUmdProd, outputPluginsDefault, outputPluginsProduction, umdNameForPkg, umdDependencyGlobals, }) => { // prettier-ignore const cjsEntryContent = `'use strict'; if (process.env.NODE_ENV === 'production') { module.exports = require('./${kebabCasePkgName}.cjs.production.js'); } else { module.exports = require('./${kebabCasePkgName}.cjs.development.js'); } `; return Promise.all([ // esm build bundleDefault.write({ file: `dist/${kebabCasePkgName}.esm.js`, format: 'esm', sourcemap: true, sourcemapExcludeSources: false, plugins: outputPluginsDefault, }), // cjs development build bundleDefault.write({ file: `dist/${kebabCasePkgName}.cjs.development.js`, format: 'cjs', sourcemap: true, sourcemapExcludeSources: false, plugins: outputPluginsDefault, }), // cjs production build bundleCjsProd.write({ file: `dist/${kebabCasePkgName}.cjs.production.js`, format: 'cjs', sourcemap: true, sourcemapExcludeSources: false, plugins: outputPluginsProduction, }), // cjs entry file fs.writeFile( resolve(cwd, 'dist', `${kebabCasePkgName}.cjs.js`), cjsEntryContent, 'utf8', ), bundleUmdDev ? bundleUmdDev.write({ file: `dist/${kebabCasePkgName}.umd.development.js`, format: 'umd', name: umdNameForPkg, globals: umdDependencyGlobals, sourcemap: true, sourcemapExcludeSources: false, plugins: outputPluginsDefault, }) : undefined, bundleUmdProd ? bundleUmdProd.write({ file: `dist/${kebabCasePkgName}.umd.production.js`, format: 'umd', name: umdNameForPkg, globals: umdDependencyGlobals, sourcemap: true, sourcemapExcludeSources: false, plugins: outputPluginsProduction, }) : undefined, ]); }; /////////////////////////////////////
the_stack
import { deepStrictEqual, notStrictEqual, rejects, strictEqual } from 'assert'; // FoalTS import { Config, ConfigTypeError, createService } from '../core'; import { SESSION_DEFAULT_ABSOLUTE_TIMEOUT, SESSION_DEFAULT_INACTIVITY_TIMEOUT } from './constants'; import { Session } from './session'; import { SessionState } from './session-state.interface'; import { SessionStore } from './session-store'; function createState(): SessionState { return { content: {}, createdAt: 0, flash: { hello2: 'world' }, id: '', updatedAt: 0, userId: null, }; } describe('Session', () => { class ConcreteSessionStore extends SessionStore { saveCalledWith: { state: SessionState, maxInactivity: number } | undefined; // read updateCalledWith: { state: SessionState, maxInactivity: number } | undefined; destroyCalledWith: string | undefined; // clear cleanUpExpiredSessionsCalledWith: { maxInactivity: number, maxLifeTime: number } | undefined; async save(state: SessionState, maxInactivity: number): Promise<void> { // This line is required to test the use of "await". await new Promise(resolve => setTimeout(() => resolve(), 0)); this.saveCalledWith = { state, maxInactivity }; } read(id: string): Promise<SessionState | null> { throw new Error('Method not implemented.'); } async update(state: SessionState, maxInactivity: number): Promise<void> { // This line is required to test the use of "await". await new Promise(resolve => setTimeout(() => resolve(), 0)); this.updateCalledWith = { state, maxInactivity }; } async destroy(id: string): Promise<void> { // This line is required to test the use of "await". await new Promise(resolve => setTimeout(() => resolve(), 0)); this.destroyCalledWith = id; } clear(): Promise<void> { throw new Error('Method not implemented.'); } async cleanUpExpiredSessions(maxInactivity: number, maxLifeTime: number): Promise<void> { // These lines are required to test the use of "await". await new Promise(resolve => setTimeout(() => resolve(), 0)); await new Promise(resolve => setTimeout(() => resolve(), 0)); this.cleanUpExpiredSessionsCalledWith = { maxInactivity, maxLifeTime }; } } let store: ConcreteSessionStore; beforeEach(() => { store = createService(ConcreteSessionStore); }); describe('has a "userId" property that', () => { it('should return the user ID.', () => { const session = new Session( store, { ...createState(), userId: 3 }, { exists: true } ); strictEqual(session.userId, 3); }); }); describe('has a "isExpired" property that', () => { afterEach(() => { Config.remove('settings.session.expirationTimeouts.inactivity'); Config.remove('settings.session.expirationTimeouts.absolute'); }); it('should return false is the session has not expired.', () => { const session = new Session( store, { ...createState(), createdAt: Math.floor(Date.now() / 1000), updatedAt: Math.floor(Date.now() / 1000), }, { exists: true } ); strictEqual(session.isExpired, false); }); it('should return true is the session has expired (inactivity, default timeout).', () => { const session = new Session( store, { ...createState(), createdAt: Math.floor(Date.now() / 1000), updatedAt: Math.floor(Date.now() / 1000) - SESSION_DEFAULT_INACTIVITY_TIMEOUT, }, { exists: true } ); strictEqual(session.isExpired, true); }); it('should return true is the session has expired (absolute, default timeout).', () => { const session = new Session( store, { ...createState(), createdAt: Math.floor(Date.now() / 1000) - SESSION_DEFAULT_ABSOLUTE_TIMEOUT, updatedAt: Math.floor(Date.now() / 1000), }, { exists: true } ); strictEqual(session.isExpired, true); }); it('should return true is the session has expired (inactivity, custom timeout).', () => { const timeout = Math.floor(SESSION_DEFAULT_INACTIVITY_TIMEOUT / 2); Config.set('settings.session.expirationTimeouts.inactivity', timeout); const session = new Session( store, { ...createState(), createdAt: Math.floor(Date.now() / 1000), updatedAt: Math.floor(Date.now() / 1000) - timeout, }, { exists: true } ); strictEqual(session.isExpired, true); }); it('should return true is the session has expired (absolute, custom timeout).', () => { const timeout = Math.floor(SESSION_DEFAULT_ABSOLUTE_TIMEOUT / 2); Config.set('settings.session.expirationTimeouts.absolute', timeout); const session = new Session( store, { ...createState(), createdAt: Math.floor(Date.now() / 1000) - timeout, updatedAt: Math.floor(Date.now() / 1000), }, { exists: true } ); strictEqual(session.isExpired, true); }); }); describe('has an "expirationTime" property that', () => { afterEach(() => { Config.remove('settings.session.expirationTimeouts.inactivity'); Config.remove('settings.session.expirationTimeouts.absolute'); }); describe('should return the session expiration time in seconds', () => { // Note: SESSION_DEFAULT_INACTIVITY_TIMEOUT is always << SESSION_DEFAULT_ABSOLUTE_TIMEOUT. it('when updatedAt + timeout < createdAt + timeout.', () => { const state: SessionState = { ...createState(), createdAt: 1, updatedAt: 1, }; const session = new Session( store, state, { exists: true }, ); strictEqual(session.expirationTime, state.updatedAt + SESSION_DEFAULT_INACTIVITY_TIMEOUT); }); it('when updatedAt + timeout < createdAt + timeout (custom timeout).', () => { const timeout = Math.floor(SESSION_DEFAULT_INACTIVITY_TIMEOUT / 2); Config.set('settings.session.expirationTimeouts.inactivity', timeout); const state: SessionState = { ...createState(), createdAt: 1, updatedAt: 1, }; const session = new Session( store, state, { exists: true }, ); strictEqual(session.expirationTime, state.updatedAt + timeout); }); it('when createdAt + timeout < updatedAt + timeout.', () => { const state: SessionState = { ...createState(), createdAt: 1, updatedAt: 1 + SESSION_DEFAULT_ABSOLUTE_TIMEOUT, }; const session = new Session( store, state, { exists: true }, ); strictEqual(session.expirationTime, state.createdAt + SESSION_DEFAULT_ABSOLUTE_TIMEOUT); }); it('when createdAt + timeout < updatedAt + timeout (custom timeout).', () => { const timeout = Math.floor(SESSION_DEFAULT_ABSOLUTE_TIMEOUT / 2); Config.set('settings.session.expirationTimeouts.absolute', timeout); const state: SessionState = { ...createState(), createdAt: 1, updatedAt: 1 + timeout, }; const session = new Session( store, state, { exists: true }, ); strictEqual(session.expirationTime, state.createdAt + timeout); }); }); context('given the "commit" has been called', () => { it('should return an increased expiration timeout.', async () => { const state: SessionState = { ...createState(), createdAt: Math.trunc(Date.now() / 1000 - SESSION_DEFAULT_ABSOLUTE_TIMEOUT / 2), updatedAt: Math.trunc(Date.now() / 1000 - SESSION_DEFAULT_INACTIVITY_TIMEOUT / 2), }; const session = new Session( store, state, { exists: true }, ); strictEqual(session.expirationTime, state.updatedAt + SESSION_DEFAULT_INACTIVITY_TIMEOUT); await session.commit(); strictEqual(session.expirationTime, Math.trunc(Date.now() / 1000) + SESSION_DEFAULT_INACTIVITY_TIMEOUT); }); }); }); describe('has a "get" method that', () => { it('should return the value of the key given in the param "state.content" during instantiation.', () => { const session = new Session( store, { ...createState(), content: { foo: 'bar' }, }, { exists: true } ); strictEqual(session.get('foo'), 'bar'); }); it('should return the value of the key given in the param "state.flash" during instantiation.', () => { const session = new Session( store, { ...createState(), flash: { hello: 'world' }, }, { exists: true } ); strictEqual(session.get('hello'), 'world'); }); it('should return the default value if the key does not exist in neither "state.flash" or "state.content".', () => { const session = new Session( store, { ...createState(), content: { foo: 'bar' }, flash: { hello: 'world' }, }, { exists: true } ); strictEqual(session.get<string>('foobar', 'barfoo'), 'barfoo'); }); it( 'should return undefined if there is no default value and if the key does not exist' + ' in neither "state.flash" or "state.content".', () => { const session = new Session( store, { ...createState(), content: { foo: 'bar' }, flash: { hello: 'world' }, }, { exists: true } ); strictEqual(session.get('foobar'), undefined); } ); it('should return the value of the key provided with the "set" method.', () => { const session = new Session( store, { ...createState(), }, { exists: true } ); strictEqual(session.get<string>('foo'), undefined); session.set('foo', 'bar'); strictEqual(session.get<string>('foo'), 'bar'); }); }); describe('has a "getToken" method that', () => { it('should return the session ID.', () => { const sessionID = 'zMd0TkVoMlj7qrJ54+G3idn0plDwQGqS/n6VVwKC4qM='; const session = new Session( store, { ...createState(), id: sessionID, }, { exists: true } ); const token = session.getToken(); strictEqual( token, sessionID ); }); }); describe('has a "regenerateID" that', () => { it('should regenerate the session ID with a random string.', async () => { const sessionID = 'a'; const session = new Session( store, { ...createState(), id: sessionID, }, { exists: true } ); strictEqual(session.getToken(), sessionID); await session.regenerateID(); notStrictEqual(session.getToken(), sessionID); notStrictEqual(session.getToken(), ''); strictEqual(typeof session.getToken(), 'string'); }); }); describe('has a "destroy" method that', () => { it('should call the "destroy" method of the store to destroy itself.', async () => { const sessionID = 'a'; const session = new Session( store, { ...createState(), id: sessionID, }, { exists: true } ); await session.destroy(); strictEqual(store.destroyCalledWith, sessionID); }); }); describe('has a "isDestroyed" property that', () => { it('should return false if the session has NOT been destroyed.', () => { const session = new Session( store, { ...createState(), }, { exists: true } ); strictEqual(session.isDestroyed, false); }); it('should return true if the session has been destroyed.', async () => { const session = new Session( store, { ...createState(), }, { exists: true } ); await session.destroy(); strictEqual(session.isDestroyed, true); }); }); describe('has a "commit" method that', () => { // Warning: only immutable objects must be used in these tests. let session: Session; function shouldSaveOrUpdateTheSession( calledWithPropertyName: 'saveCalledWith'|'updateCalledWith', state: SessionState|(() => SessionState) ) { it('with the proper id, userId, content and createdAt values.', async () => { await session.commit(); state = typeof state === 'function' ? state() : state; // tslint:disable-next-line strictEqual(store[calledWithPropertyName]?.state.id, state.id); // tslint:disable-next-line strictEqual(store[calledWithPropertyName]?.state.userId, state.userId); // tslint:disable-next-line deepStrictEqual(store[calledWithPropertyName]?.state.content, state.content); // tslint:disable-next-line strictEqual(store[calledWithPropertyName]?.state.createdAt, state.createdAt); }); it('with the proper userId modified with the "setUser" method (number).', async () => { // Use 0 here to detect errors on falsy values. const user = { id: 0 }; session.setUser(user); await session.commit(); // tslint:disable-next-line strictEqual(store[calledWithPropertyName]?.state.userId, user.id); }); it('with the proper userId modified with the "setUser" method (string).', async () => { // Use empty string here to detect errors on falsy values. const user = { id: '' }; session.setUser(user); await session.commit(); // tslint:disable-next-line strictEqual(store[calledWithPropertyName]?.state.userId, user.id); }); it('with the proper userId modified with the "setUser" method (toString).', async () => { const user = { id: { toString() { return 1; }} }; session.setUser(user); await session.commit(); // tslint:disable-next-line strictEqual(store[calledWithPropertyName]?.state.userId, 1); }); it('with the proper userId modified with the "setUser" method (_id).', async () => { const user = { _id: 'xxx' }; session.setUser(user as any); await session.commit(); // tslint:disable-next-line strictEqual(store[calledWithPropertyName]?.state.userId, user._id); }); it('with the proper content modified with the "set" method.', async () => { session.set('foo', 'bar'); await session.commit(); // tslint:disable-next-line deepStrictEqual(store[calledWithPropertyName]?.state.content, { foo: 'bar' }); // tslint:disable-next-line deepStrictEqual(store[calledWithPropertyName]?.state.flash, {}); }); it('with the proper flash content modified with the "set" method.', async () => { session.set('hello', 'world', { flash: true }); await session.commit(); state = typeof state === 'function' ? state() : state; // tslint:disable-next-line deepStrictEqual(store[calledWithPropertyName]?.state.content, state.content); // tslint:disable-next-line deepStrictEqual(store[calledWithPropertyName]?.state.flash, { hello: 'world' }); }); it('with the proper updatedAt value (in seconds).', async () => { const dateBefore = Math.floor(Date.now() / 1000); await session.commit(); const dateAfter = Math.floor(Date.now() / 1000) + 1; const calledWith = store[calledWithPropertyName]; if (!calledWith) { throw new Error('SessionStore.update should have been called.'); } const updatedAt = calledWith.state.updatedAt; strictEqual(Number.isInteger(updatedAt), true, `${updatedAt} should be an integer`); strictEqual(dateBefore <= updatedAt, true, `${updatedAt} should older than dateBefore`); strictEqual(dateAfter >= updatedAt, true, `${updatedAt} should newer than dateBefore`); const max = 2147483647; const tenYears = 60 * 60 * 24 * 365 * 10; strictEqual(updatedAt < max, true, `${updatedAt} should be less than 4 bytes.`); strictEqual(updatedAt + tenYears < max, true, `${updatedAt} should be less than 4 bytes within 10 years.`); }); describe('providing an idle timeout', () => { afterEach(() => Config.remove('settings.session.expirationTimeouts.inactivity')); it('from the framework default values.', async () => { await session.commit(); // tslint:disable-next-line strictEqual(store[calledWithPropertyName]?.maxInactivity, SESSION_DEFAULT_INACTIVITY_TIMEOUT); }); it('from the configuration.', async () => { Config.set('settings.session.expirationTimeouts.inactivity', 1); await session.commit(); // tslint:disable-next-line strictEqual(store[calledWithPropertyName]?.maxInactivity, 1); }); it('and should throw an error if the configuration value is not a number.', async () => { Config.set('settings.session.expirationTimeouts.inactivity', 'a'); await rejects( () => session.commit(), new ConfigTypeError('settings.session.expirationTimeouts.inactivity', 'number', 'string') ); }); it('and should throw an error if the configuration value is negative.', async () => { Config.set('settings.session.expirationTimeouts.inactivity', -1); await rejects( () => session.commit(), new Error('[CONFIG] The value of settings.session.expirationTimeouts.inactivity must be a positive number.') ); }); }); } function shouldSaveTheSession(state: SessionState|(() => SessionState)): void { describe('should save the session', () => { shouldSaveOrUpdateTheSession('saveCalledWith', state); }); } function shouldUpdateTheSession(state: SessionState|(() => SessionState)): void { describe('should update the session', () => { shouldSaveOrUpdateTheSession('updateCalledWith', state); }); } function shouldDestroyTheSession(id: string): void { it('should destroy the session.', async () => { await session.commit(); deepStrictEqual(store.destroyCalledWith, id); }); } function shouldNotSaveTheSession(): void { it('should NOT save the session.', async () => { await session.commit(); strictEqual(store.saveCalledWith, undefined); }); } function shouldNotUpdateTheSession(): void { it('should NOT update the session.', async () => { await session.commit(); strictEqual(store.updateCalledWith, undefined); }); } function shouldNotDestroyTheSession(): void { it('should NOT destroy the session.', async () => { await session.commit(); strictEqual(store.destroyCalledWith, undefined); }); } context('given the session has been created with exists=true', () => { beforeEach(async () => { session = new Session( store, { ...createState() }, { exists: true } ); }); shouldNotSaveTheSession(); shouldUpdateTheSession({ ...createState(), }); shouldNotDestroyTheSession(); }); context('given the session has been created with exists=false', () => { context('and the session has not been commited yet', () => { beforeEach(async () => { session = new Session( store, { ...createState() }, { exists: false } ); }); shouldSaveTheSession({ ...createState() }); shouldNotUpdateTheSession(); shouldNotDestroyTheSession(); }); context('and the session has already been commited', () => { beforeEach(async () => { session = new Session( store, { ...createState() }, { exists: false } ); await session.commit(); store.saveCalledWith = undefined; }); shouldNotSaveTheSession(); shouldUpdateTheSession({ ...createState() }); shouldNotDestroyTheSession(); }); }); context('given the session ID has been re-generated', () => { context('and the session has not been commited yet', () => { const firstID = 'xxx'; let secondID: string = ''; beforeEach(async () => { session = new Session( store, { ...createState(), id: firstID }, { exists: false } ); await session.regenerateID(); secondID = session.getToken(); }); shouldDestroyTheSession(firstID); shouldSaveTheSession(() => ({ ...createState(), id: secondID, })); shouldNotUpdateTheSession(); }); context('and the session has already been commited', () => { const firstID = 'xxx'; let secondID: string = ''; beforeEach(async () => { session = new Session( store, { ...createState(), id: firstID }, { exists: false } ); await session.regenerateID(); secondID = session.getToken(); await session.commit(); store.saveCalledWith = undefined; store.destroyCalledWith = undefined; }); shouldNotDestroyTheSession(); shouldNotSaveTheSession(); shouldUpdateTheSession(() => ({ ...createState(), id: secondID, })); }); }); context('given the "destroy" method has been called', () => { beforeEach(async () => { session = new Session( store, { ...createState() }, { exists: true } ); await session.destroy(); }); it('should throw an error.', async () => { await rejects( () => session.commit(), { message: 'Impossible to commit the session. Session already destroyed.' } ); }); }); describe('should periodically clean up the expired sessions', () => { beforeEach(async () => { session = new Session( store, { ...createState() }, { exists: true } ); }); afterEach(() => { Config.remove('settings.session.garbageCollector.periodicity'); Config.remove('settings.session.expirationTimeouts.inactivity'); Config.remove('settings.session.expirationTimeouts.absolute'); }); it('with a frequency defined in the configuration (periodicity = 1).', async () => { Config.set('settings.session.garbageCollector.periodicity', 1); await session.commit(); deepStrictEqual(store.cleanUpExpiredSessionsCalledWith, { maxInactivity: SESSION_DEFAULT_INACTIVITY_TIMEOUT, maxLifeTime: SESSION_DEFAULT_ABSOLUTE_TIMEOUT, }); }); it('with a frequency defined in the configuration (periodicity = 1 000 000 000).', async () => { Config.set('settings.session.garbageCollector.periodicity', 1000000000); await session.commit(); strictEqual(store.cleanUpExpiredSessionsCalledWith, undefined); }); it('and should throw an error if the periodicity provided in the configuration is not a number.', async () => { Config.set('settings.session.garbageCollector.periodicity', 'a'); await rejects( () => session.commit(), new ConfigTypeError('settings.session.garbageCollector.periodicity', 'number', 'string') ); }); it('with idle and absolute timeouts defined in the configuration.', async () => { Config.set('settings.session.garbageCollector.periodicity', 1); Config.set('settings.session.expirationTimeouts.inactivity', 15); Config.set('settings.session.expirationTimeouts.absolute', 30); await session.commit(); deepStrictEqual(store.cleanUpExpiredSessionsCalledWith, { maxInactivity: 15, maxLifeTime: 30, }); }); it( 'and should throw an error if the inactivity timeout provided in the configuration is not a number.', async () => { Config.set('settings.session.expirationTimeouts.inactivity', 'a'); await rejects( () => session.commit(), new ConfigTypeError('settings.session.expirationTimeouts.inactivity', 'number', 'string') ); } ); it('and should throw an error the inactivity timeout provided in the configuration is negative.', async () => { Config.set('settings.session.expirationTimeouts.inactivity', -1); await rejects( () => session.commit(), new Error('[CONFIG] The value of settings.session.expirationTimeouts.inactivity must be a positive number.') ); }); it( 'and should throw an error if the absolute timeout provided in the configuration is not a number.', async () => { Config.set('settings.session.expirationTimeouts.absolute', 'a'); await rejects( () => session.commit(), new ConfigTypeError('settings.session.expirationTimeouts.absolute', 'number', 'string') ); } ); it('and should throw an error the inactivity timeout provided in the configuration is negative.', async () => { Config.set('settings.session.expirationTimeouts.absolute', -1); await rejects( () => session.commit(), new Error('[CONFIG] The value of settings.session.expirationTimeouts.absolute must be a positive number.') ); }); it( 'and should throw an error if the absolute timeout provided in the configuration is lower ' + 'than the inactivity timeout.', async () => { Config.set('settings.session.expirationTimeouts.inactivity', 2); Config.set('settings.session.expirationTimeouts.absolute', 1); await rejects( () => session.commit(), new Error( '[CONFIG] The value of settings.session.expirationTimeouts.absolute must be greater than *.inactivity.' ) ); } ); }); }); });
the_stack
// @Filename:privacyVarDeclFile_externalModule.ts class privateClass { } export class publicClass { } export interface publicInterfaceWithPrivatePropertyTypes { myProperty: privateClass; // Error } export interface publicInterfaceWithPublicPropertyTypes { myProperty: publicClass; } interface privateInterfaceWithPrivatePropertyTypes { myProperty: privateClass; } interface privateInterfaceWithPublicPropertyTypes { myProperty: publicClass; } export class publicClassWithWithPrivatePropertyTypes { static myPublicStaticProperty: privateClass; // Error private static myPrivateStaticProperty: privateClass; myPublicProperty: privateClass; // Error private myPrivateProperty: privateClass; } export class publicClassWithWithPublicPropertyTypes { static myPublicStaticProperty: publicClass; private static myPrivateStaticProperty: publicClass; myPublicProperty: publicClass; private myPrivateProperty: publicClass; } class privateClassWithWithPrivatePropertyTypes { static myPublicStaticProperty: privateClass; private static myPrivateStaticProperty: privateClass; myPublicProperty: privateClass; private myPrivateProperty: privateClass; } class privateClassWithWithPublicPropertyTypes { static myPublicStaticProperty: publicClass; private static myPrivateStaticProperty: publicClass; myPublicProperty: publicClass; private myPrivateProperty: publicClass; } export var publicVarWithPrivatePropertyTypes: privateClass; // Error export var publicVarWithPublicPropertyTypes: publicClass; var privateVarWithPrivatePropertyTypes: privateClass; var privateVarWithPublicPropertyTypes: publicClass; export declare var publicAmbientVarWithPrivatePropertyTypes: privateClass; // Error export declare var publicAmbientVarWithPublicPropertyTypes: publicClass; declare var privateAmbientVarWithPrivatePropertyTypes: privateClass; declare var privateAmbientVarWithPublicPropertyTypes: publicClass; export interface publicInterfaceWithPrivateModulePropertyTypes { myProperty: privateModule.publicClass; // Error } export class publicClassWithPrivateModulePropertyTypes { static myPublicStaticProperty: privateModule.publicClass; // Error myPublicProperty: privateModule.publicClass; // Error } export var publicVarWithPrivateModulePropertyTypes: privateModule.publicClass; // Error export declare var publicAmbientVarWithPrivateModulePropertyTypes: privateModule.publicClass; // Error interface privateInterfaceWithPrivateModulePropertyTypes { myProperty: privateModule.publicClass; } class privateClassWithPrivateModulePropertyTypes { static myPublicStaticProperty: privateModule.publicClass; myPublicProperty: privateModule.publicClass; } var privateVarWithPrivateModulePropertyTypes: privateModule.publicClass; declare var privateAmbientVarWithPrivateModulePropertyTypes: privateModule.publicClass; export module publicModule { class privateClass { } export class publicClass { } export interface publicInterfaceWithPrivatePropertyTypes { myProperty: privateClass; // Error } export interface publicInterfaceWithPublicPropertyTypes { myProperty: publicClass; } interface privateInterfaceWithPrivatePropertyTypes { myProperty: privateClass; } interface privateInterfaceWithPublicPropertyTypes { myProperty: publicClass; } export class publicClassWithWithPrivatePropertyTypes { static myPublicStaticProperty: privateClass; // Error private static myPrivateStaticProperty: privateClass; myPublicProperty: privateClass; // Error private myPrivateProperty: privateClass; } export class publicClassWithWithPublicPropertyTypes { static myPublicStaticProperty: publicClass; private static myPrivateStaticProperty: publicClass; myPublicProperty: publicClass; private myPrivateProperty: publicClass; } class privateClassWithWithPrivatePropertyTypes { static myPublicStaticProperty: privateClass; private static myPrivateStaticProperty: privateClass; myPublicProperty: privateClass; private myPrivateProperty: privateClass; } class privateClassWithWithPublicPropertyTypes { static myPublicStaticProperty: publicClass; private static myPrivateStaticProperty: publicClass; myPublicProperty: publicClass; private myPrivateProperty: publicClass; } export var publicVarWithPrivatePropertyTypes: privateClass; // Error export var publicVarWithPublicPropertyTypes: publicClass; var privateVarWithPrivatePropertyTypes: privateClass; var privateVarWithPublicPropertyTypes: publicClass; export declare var publicAmbientVarWithPrivatePropertyTypes: privateClass; // Error export declare var publicAmbientVarWithPublicPropertyTypes: publicClass; declare var privateAmbientVarWithPrivatePropertyTypes: privateClass; declare var privateAmbientVarWithPublicPropertyTypes: publicClass; export interface publicInterfaceWithPrivateModulePropertyTypes { myProperty: privateModule.publicClass; // Error } export class publicClassWithPrivateModulePropertyTypes { static myPublicStaticProperty: privateModule.publicClass; // Error myPublicProperty: privateModule.publicClass; // Error } export var publicVarWithPrivateModulePropertyTypes: privateModule.publicClass; // Error export declare var publicAmbientVarWithPrivateModulePropertyTypes: privateModule.publicClass; // Error interface privateInterfaceWithPrivateModulePropertyTypes { myProperty: privateModule.publicClass; } class privateClassWithPrivateModulePropertyTypes { static myPublicStaticProperty: privateModule.publicClass; myPublicProperty: privateModule.publicClass; } var privateVarWithPrivateModulePropertyTypes: privateModule.publicClass; declare var privateAmbientVarWithPrivateModulePropertyTypes: privateModule.publicClass; } module privateModule { class privateClass { } export class publicClass { } export interface publicInterfaceWithPrivatePropertyTypes { myProperty: privateClass; } export interface publicInterfaceWithPublicPropertyTypes { myProperty: publicClass; } interface privateInterfaceWithPrivatePropertyTypes { myProperty: privateClass; } interface privateInterfaceWithPublicPropertyTypes { myProperty: publicClass; } export class publicClassWithWithPrivatePropertyTypes { static myPublicStaticProperty: privateClass; private static myPrivateStaticProperty: privateClass; myPublicProperty: privateClass; private myPrivateProperty: privateClass; } export class publicClassWithWithPublicPropertyTypes { static myPublicStaticProperty: publicClass; private static myPrivateStaticProperty: publicClass; myPublicProperty: publicClass; private myPrivateProperty: publicClass; } class privateClassWithWithPrivatePropertyTypes { static myPublicStaticProperty: privateClass; private static myPrivateStaticProperty: privateClass; myPublicProperty: privateClass; private myPrivateProperty: privateClass; } class privateClassWithWithPublicPropertyTypes { static myPublicStaticProperty: publicClass; private static myPrivateStaticProperty: publicClass; myPublicProperty: publicClass; private myPrivateProperty: publicClass; } export var publicVarWithPrivatePropertyTypes: privateClass; export var publicVarWithPublicPropertyTypes: publicClass; var privateVarWithPrivatePropertyTypes: privateClass; var privateVarWithPublicPropertyTypes: publicClass; export declare var publicAmbientVarWithPrivatePropertyTypes: privateClass; export declare var publicAmbientVarWithPublicPropertyTypes: publicClass; declare var privateAmbientVarWithPrivatePropertyTypes: privateClass; declare var privateAmbientVarWithPublicPropertyTypes: publicClass; export interface publicInterfaceWithPrivateModulePropertyTypes { myProperty: privateModule.publicClass; } export class publicClassWithPrivateModulePropertyTypes { static myPublicStaticProperty: privateModule.publicClass; myPublicProperty: privateModule.publicClass; } export var publicVarWithPrivateModulePropertyTypes: privateModule.publicClass; export declare var publicAmbientVarWithPrivateModulePropertyTypes: privateModule.publicClass; interface privateInterfaceWithPrivateModulePropertyTypes { myProperty: privateModule.publicClass; } class privateClassWithPrivateModulePropertyTypes { static myPublicStaticProperty: privateModule.publicClass; myPublicProperty: privateModule.publicClass; } var privateVarWithPrivateModulePropertyTypes: privateModule.publicClass; declare var privateAmbientVarWithPrivateModulePropertyTypes: privateModule.publicClass; } // @Filename: privacyVarDeclFile_GlobalFile.ts class publicClassInGlobal { } interface publicInterfaceWithPublicPropertyTypesInGlobal { myProperty: publicClassInGlobal; } class publicClassWithWithPublicPropertyTypesInGlobal { static myPublicStaticProperty: publicClassInGlobal; private static myPrivateStaticProperty: publicClassInGlobal; myPublicProperty: publicClassInGlobal; private myPrivateProperty: publicClassInGlobal; } var publicVarWithPublicPropertyTypesInGlobal: publicClassInGlobal; declare var publicAmbientVarWithPublicPropertyTypesInGlobal: publicClassInGlobal; module publicModuleInGlobal { class privateClass { } export class publicClass { } module privateModule { class privateClass { } export class publicClass { } export interface publicInterfaceWithPrivatePropertyTypes { myProperty: privateClass; } export interface publicInterfaceWithPublicPropertyTypes { myProperty: publicClass; } interface privateInterfaceWithPrivatePropertyTypes { myProperty: privateClass; } interface privateInterfaceWithPublicPropertyTypes { myProperty: publicClass; } export class publicClassWithWithPrivatePropertyTypes { static myPublicStaticProperty: privateClass; private static myPrivateStaticProperty: privateClass; myPublicProperty: privateClass; private myPrivateProperty: privateClass; } export class publicClassWithWithPublicPropertyTypes { static myPublicStaticProperty: publicClass; private static myPrivateStaticProperty: publicClass; myPublicProperty: publicClass; private myPrivateProperty: publicClass; } class privateClassWithWithPrivatePropertyTypes { static myPublicStaticProperty: privateClass; private static myPrivateStaticProperty: privateClass; myPublicProperty: privateClass; private myPrivateProperty: privateClass; } class privateClassWithWithPublicPropertyTypes { static myPublicStaticProperty: publicClass; private static myPrivateStaticProperty: publicClass; myPublicProperty: publicClass; private myPrivateProperty: publicClass; } export var publicVarWithPrivatePropertyTypes: privateClass; export var publicVarWithPublicPropertyTypes: publicClass; var privateVarWithPrivatePropertyTypes: privateClass; var privateVarWithPublicPropertyTypes: publicClass; export declare var publicAmbientVarWithPrivatePropertyTypes: privateClass; export declare var publicAmbientVarWithPublicPropertyTypes: publicClass; declare var privateAmbientVarWithPrivatePropertyTypes: privateClass; declare var privateAmbientVarWithPublicPropertyTypes: publicClass; export interface publicInterfaceWithPrivateModulePropertyTypes { myProperty: privateModule.publicClass; } export class publicClassWithPrivateModulePropertyTypes { static myPublicStaticProperty: privateModule.publicClass; myPublicProperty: privateModule.publicClass; } export var publicVarWithPrivateModulePropertyTypes: privateModule.publicClass; export declare var publicAmbientVarWithPrivateModulePropertyTypes: privateModule.publicClass; interface privateInterfaceWithPrivateModulePropertyTypes { myProperty: privateModule.publicClass; } class privateClassWithPrivateModulePropertyTypes { static myPublicStaticProperty: privateModule.publicClass; myPublicProperty: privateModule.publicClass; } var privateVarWithPrivateModulePropertyTypes: privateModule.publicClass; declare var privateAmbientVarWithPrivateModulePropertyTypes: privateModule.publicClass; } export interface publicInterfaceWithPrivatePropertyTypes { myProperty: privateClass; // Error } export interface publicInterfaceWithPublicPropertyTypes { myProperty: publicClass; } interface privateInterfaceWithPrivatePropertyTypes { myProperty: privateClass; } interface privateInterfaceWithPublicPropertyTypes { myProperty: publicClass; } export class publicClassWithWithPrivatePropertyTypes { static myPublicStaticProperty: privateClass; // Error private static myPrivateStaticProperty: privateClass; myPublicProperty: privateClass; // Error private myPrivateProperty: privateClass; } export class publicClassWithWithPublicPropertyTypes { static myPublicStaticProperty: publicClass; private static myPrivateStaticProperty: publicClass; myPublicProperty: publicClass; private myPrivateProperty: publicClass; } class privateClassWithWithPrivatePropertyTypes { static myPublicStaticProperty: privateClass; private static myPrivateStaticProperty: privateClass; myPublicProperty: privateClass; private myPrivateProperty: privateClass; } class privateClassWithWithPublicPropertyTypes { static myPublicStaticProperty: publicClass; private static myPrivateStaticProperty: publicClass; myPublicProperty: publicClass; private myPrivateProperty: publicClass; } export var publicVarWithPrivatePropertyTypes: privateClass; // Error export var publicVarWithPublicPropertyTypes: publicClass; var privateVarWithPrivatePropertyTypes: privateClass; var privateVarWithPublicPropertyTypes: publicClass; export declare var publicAmbientVarWithPrivatePropertyTypes: privateClass; // Error export declare var publicAmbientVarWithPublicPropertyTypes: publicClass; declare var privateAmbientVarWithPrivatePropertyTypes: privateClass; declare var privateAmbientVarWithPublicPropertyTypes: publicClass; export interface publicInterfaceWithPrivateModulePropertyTypes { myProperty: privateModule.publicClass; // Error } export class publicClassWithPrivateModulePropertyTypes { static myPublicStaticProperty: privateModule.publicClass; // Error myPublicProperty: privateModule.publicClass; // Error } export var publicVarWithPrivateModulePropertyTypes: privateModule.publicClass; // Error export declare var publicAmbientVarWithPrivateModulePropertyTypes: privateModule.publicClass; // Error interface privateInterfaceWithPrivateModulePropertyTypes { myProperty: privateModule.publicClass; } class privateClassWithPrivateModulePropertyTypes { static myPublicStaticProperty: privateModule.publicClass; myPublicProperty: privateModule.publicClass; } var privateVarWithPrivateModulePropertyTypes: privateModule.publicClass; declare var privateAmbientVarWithPrivateModulePropertyTypes: privateModule.publicClass; }
the_stack
import { InfoPageDisplayConfig, InfoTabElementVector2 } from "~/data/config/overlayConfig"; import InfoSidePage from "~/data/infoSidePage"; import PlayerInfoTab from "~/data/playerInfoTab"; import PlaceholderConversion from "~/PlaceholderConversion"; import IngameScene from "~/scenes/IngameScene"; import Utils from "~/util/Utils"; import Vector2 from "~/util/Vector2"; import variables from "~/variables"; import { VisualElement } from "./VisualElement"; export default class InfoPageVisual extends VisualElement { BackgroundRect: Phaser.GameObjects.Rectangle | null = null; BackgroundImage: Phaser.GameObjects.Image | null = null; BackgroundVideo: Phaser.GameObjects.Video | null = null; ImgMask!: Phaser.Display.Masks.BitmapMask; GeoMask!: Phaser.Display.Masks.GeometryMask; MaskImage!: Phaser.GameObjects.Sprite; MaskGeo!: Phaser.GameObjects.Graphics; Title: Phaser.GameObjects.Text | null = null; PlayerTabs: PlayerTabIndicator[]; static CurrentInfoType: string = ''; constructor(scene: IngameScene, cfg: InfoPageDisplayConfig) { super(scene, cfg.Position, "infoPage"); this.CreateTextureListeners(); //Mask if (cfg.Background.UseAlpha) { this.MaskImage = scene.make.sprite({ x: cfg.Position.X - cfg.Background.Size.X, y: cfg.Position.Y, key: 'infoPageMask', add: false }); this.MaskImage.setOrigin(0, 0); this.MaskImage.setDisplaySize(cfg.Background.Size.X, cfg.Background.Size.Y); this.ImgMask = this.MaskImage.createBitmapMask(); } else { this.MaskGeo = scene.make.graphics({add: false}); this.MaskGeo.fillStyle(0xffffff); this.MaskGeo.fillRect(cfg.Position.X, cfg.Position.Y, cfg.Background.Size.X, cfg.Background.Size.Y); this.GeoMask = this.MaskGeo.createGeometryMask(); this.MaskGeo.setPosition(cfg.Position.X - cfg.Background.Size.X, 0); } /* //Background if (cfg.Background.UseVideo) { this.scene.load.video('infoBgVideo', 'frontend/backgrounds/InfoPage.mp4'); } else if (cfg.Background.UseImage) { this.scene.load.image('infoBg', 'frontend/backgrounds/InfoPage.png'); } else { this.BackgroundRect = this.scene.add.rectangle(cfg.Position.X, cfg.Position.Y, cfg.Background.Size.X, cfg.Background.Size.Y, Phaser.Display.Color.RGBStringToColor(cfg.Background.FallbackColor).color); this.BackgroundRect.setOrigin(0, 0); this.BackgroundRect.depth = -1; this.BackgroundRect.setMask(cfg.Background.UseAlpha ? this.ImgMask : this.GeoMask); this.AddVisualComponent(this.BackgroundRect); } */ //Title if (cfg.Title.Enabled) { this.Title = scene.add.text(cfg.Position.X + cfg.Title.Position.XP.X, cfg.Position.Y + cfg.Title.Position.XP.Y, 'Info Tab', { fontFamily: cfg.Title.Font.Name, fontSize: cfg.Title.Font.Size, color: cfg.Title.Font.Color, fontStyle: cfg.Title.Font.Style, align: cfg.Title.Font.Align }); this.Title.setOrigin(0.5, 0); this.Title.setDepth(2); this.AddVisualComponent(this.Title); this.Title.setMask(InfoPageVisual.GetConfig().Background.UseAlpha ? this.ImgMask : this.GeoMask); } this.PlayerTabs = []; //Load Resources if (cfg.Background.UseImage || cfg.Background.UseVideo) { this.scene.load.start(); } this.Init(); } UpdateValues(newValues: InfoSidePage): void { if (newValues.Title === undefined || newValues.Title === null || newValues.Title == '') { if (this.isActive) { this.Stop(); } return; } if (this.Title !== null && this.Title !== undefined) this.Title.text = newValues.Title; InfoPageVisual.CurrentInfoType = newValues.Players[0].ExtraInfo[1]; this.UpdatePlayerTabs(newValues); this.Start(); } UpdatePlayerTabs(cfg: InfoSidePage): void { if (this.PlayerTabs.length === 0) { //init player tabs console.log(cfg); var i = 0; cfg.Players.forEach(pt => { this.PlayerTabs.push(new PlayerTabIndicator(pt, InfoPageVisual.GetConfig(), this.scene, i++)); }); return; } //update player tabs var i = 0; cfg.Players.forEach(pt => { this.PlayerTabs[i++].UpdateValues(pt); }); } UpdateConfig(newConfig: InfoPageDisplayConfig): void { //Position this.position = newConfig.Position; //Background if (!newConfig.Background.UseAlpha) { this.MaskGeo.clear(); this.MaskGeo.fillStyle(0xffffff); this.MaskGeo.fillRect(newConfig.Position.X, newConfig.Position.Y, newConfig.Background.Size.X, newConfig.Background.Size.Y); } //Background Image if (newConfig.Background.UseImage) { if (this.BackgroundVideo !== undefined && this.BackgroundVideo !== null) { this.RemoveVisualComponent(this.BackgroundVideo); this.BackgroundVideo?.destroy(); this.BackgroundVideo = null; this.scene.cache.video.remove('infoBgVideo'); } if (this.BackgroundRect !== undefined && this.BackgroundRect !== null) { this.RemoveVisualComponent(this.BackgroundRect); this.BackgroundRect.destroy(); this.BackgroundRect = null; } //Load Texture only if it does not already exist if (this.BackgroundImage === null || this.BackgroundImage === undefined) { this.scene.load.image('infoBg', 'frontend/backgrounds/InfoPage.png'); } } //Background Video else if (newConfig.Background.UseVideo) { if (this.BackgroundRect !== undefined && this.BackgroundRect !== null) { this.RemoveVisualComponent(this.BackgroundRect); this.BackgroundRect.destroy(); this.BackgroundRect = null; } if (this.BackgroundImage !== undefined && this.BackgroundImage !== null) { this.RemoveVisualComponent(this.BackgroundImage); this.BackgroundImage?.destroy(); this.BackgroundImage = null; this.scene.textures.remove('infoBg'); } //Load Video only if it does not already exist if (this.BackgroundVideo === null || this.BackgroundVideo === undefined) { this.scene.load.video('infoBgVideo', 'frontend/backgrounds/InfoPage.mp4'); } } //Background Color else { if (this.BackgroundImage !== undefined && this.BackgroundImage !== null) { this.RemoveVisualComponent(this.BackgroundImage); this.BackgroundImage?.destroy(); this.BackgroundImage = null; this.scene.textures.remove('infoBg'); } if (this.BackgroundVideo !== undefined && this.BackgroundVideo !== null) { this.RemoveVisualComponent(this.BackgroundVideo); this.BackgroundVideo?.destroy(); this.BackgroundVideo = null; this.scene.cache.video.remove('infoBgVideo'); } if (this.BackgroundRect === null || this.BackgroundRect === undefined) { this.BackgroundRect = this.scene.add.rectangle(newConfig.Position.X, newConfig.Position.Y, newConfig.Background.Size.X, newConfig.Background.Size.Y, Phaser.Display.Color.RGBStringToColor(newConfig.Background.FallbackColor).color32); this.BackgroundRect.setOrigin(0, 0); this.BackgroundRect.setDepth(1); this.BackgroundRect.setMask(InfoPageVisual.GetConfig().Background.UseAlpha ? this.ImgMask : this.GeoMask); this.AddVisualComponent(this.BackgroundRect); } this.BackgroundRect.setPosition(newConfig.Position.X, newConfig.Position.Y); this.BackgroundRect.setDisplaySize(newConfig.Background.Size.X, newConfig.Background.Size.Y); this.BackgroundRect.setFillStyle(Phaser.Display.Color.RGBStringToColor(newConfig.Background.FallbackColor).color, 1); } //Title if (newConfig.Title.Enabled) { if (InfoPageVisual.GetConfig().Title.Enabled) { this.Title?.setPosition(newConfig.Position.X + InfoPageVisual.GetCurrentElementVector2(newConfig.Title.Position).X, newConfig.Position.Y + InfoPageVisual.GetCurrentElementVector2(newConfig.Title.Position).Y); this.UpdateTextStyle(this.Title!, newConfig.Title.Font); } else { this.Title = this.scene.add.text(newConfig.Position.X + InfoPageVisual.GetCurrentElementVector2(newConfig.Title.Position).X, newConfig.Position.Y + InfoPageVisual.GetCurrentElementVector2(newConfig.Title.Position).Y, 'Info Tab', { fontFamily: newConfig.Title.Font.Name, fontSize: newConfig.Title.Font.Size, color: newConfig.Title.Font.Color, fontStyle: newConfig.Title.Font.Style, align: newConfig.Title.Font.Align }); this.Title.setOrigin(0.5, 0); this.Title.setDepth(2); this.Title.setMask(InfoPageVisual.GetConfig().Background.UseAlpha ? this.ImgMask : this.GeoMask); this.AddVisualComponent(this.Title); } } else if (!(this.Title === null || this.Title === undefined)) { this.RemoveVisualComponent(this.Title); this.Title.destroy(); this.Title = null; } //Player Tabs if (this.PlayerTabs.length !== 0) { this.PlayerTabs.forEach(tab => { tab.UpdateConfig(newConfig) }); } this.scene.load.start(); } Load(): void { //Load in constructor } Start(): void { if (this.isActive || this.isShowing) return; var ctx = this; this.isShowing = true; this.UpdateConfig(InfoPageVisual.GetConfig()); this.currentAnimation[0] = ctx.scene.tweens.add({ targets: [ctx.MaskGeo, ctx.MaskImage], props: { x: { from: InfoPageVisual.GetConfig().Position.X - InfoPageVisual.GetConfig().Background.Size.X, to: 0, duration: 1000, ease: 'Cubic.easeInOut' } }, paused: false, yoyo: false, onComplete: function () { ctx.PlayerTabs.forEach(pt => pt.Start()); setTimeout(() => { ctx.isActive = true; ctx.isShowing = false; //Force Images to show incase some race condition prevented it earlier ctx.PlayerTabs.forEach(pt => { if(pt.Image !== null && pt.Image !== undefined) { pt.Image.setAlpha(1); } }) }, 500); } }); } Stop(): void { if (!this.isActive || this.isHiding) return; this.isActive = false; this.isHiding = true; var ctx = this; ctx.PlayerTabs.forEach(pt => pt.Stop()); this.currentAnimation[0] = ctx.scene.tweens.add({ targets: [ctx.MaskGeo, ctx.MaskImage], props: { x: { from: 0, to: ctx.position.X - InfoPageVisual.GetConfig().Background.Size.X, duration: 1000, ease: 'Cubic.easeInOut' } }, paused: false, yoyo: false, delay: 500, onComplete: function () { ctx.isHiding = false; } }); } static GetConfig(): InfoPageDisplayConfig { return IngameScene.Instance.overlayCfg!.InfoPage; } CreateTextureListeners(): void { //Background Image support this.scene.load.on(`filecomplete-image-infoBg`, () => { this.BackgroundImage = this.scene.make.sprite({ x: InfoPageVisual.GetConfig()!.Position.X, y: InfoPageVisual.GetConfig()!.Position.Y, key: 'infoBg', add: true }); this.BackgroundImage.setOrigin(0, 0); this.BackgroundImage.setDepth(1); this.BackgroundImage.setMask(InfoPageVisual.GetConfig()?.Background.UseAlpha ? this.ImgMask : this.GeoMask); this.AddVisualComponent(this.BackgroundImage); if (!this.isActive && !this.isShowing) { this.BackgroundImage.alpha = 0; } }); //Background Video support this.scene.load.on(`filecomplete-video-infoBgVideo`, () => { if (this.BackgroundVideo !== undefined && this.BackgroundVideo !== null) { this.RemoveVisualComponent(this.BackgroundVideo); this.BackgroundVideo.destroy(); } // @ts-ignore this.BackgroundVideo = this.scene.add.video(InfoPageVisual.GetConfig()!.Position.X, InfoPageVisual.GetConfig()!.Position.Y, 'infoBgVideo', false, true); this.BackgroundVideo.setOrigin(0, 0); this.BackgroundVideo.setMask(InfoPageVisual.GetConfig().Background.UseAlpha ? this.ImgMask : this.GeoMask); this.BackgroundVideo.setLoop(true); this.BackgroundVideo.setDepth(1); this.BackgroundVideo.play(); this.AddVisualComponent(this.BackgroundVideo); if (!this.isActive && !this.isShowing) { this.BackgroundVideo.alpha = 0; } }); } static GetCurrentElementVector2(pos: InfoTabElementVector2, infoType: string = 'current'): Vector2 { if (infoType === 'current') { infoType = InfoPageVisual.CurrentInfoType; } switch (infoType) { case 'gold': return pos.Gold; case 'cspm': return pos.CSPM; case 'exp': return pos.XP; default: return new Vector2(0, 0); } } } export class PlayerTabIndicator { Scene: IngameScene; TopSeparator: Phaser.GameObjects.Sprite | null = null; PlayerName: string; Image: Phaser.GameObjects.Sprite | null = null; Name: Phaser.GameObjects.Text | null = null; ProgressBarTotal: Phaser.GameObjects.Rectangle | null = null; ProgresssBarCompleted: Phaser.GameObjects.Rectangle | null = null; MinVal: Phaser.GameObjects.Text | null = null; MaxVal: Phaser.GameObjects.Text | null = null; CurVal: Phaser.GameObjects.Text | null = null; MainVal: Phaser.GameObjects.Text | null = null; Row: number; BaseOffset: number; Id: string; CurrentInfo: PlayerInfoTab; Config = IngameScene.Instance.overlayCfg?.InfoPage; VisualComponents: any[] = []; constructor(tabInfo: PlayerInfoTab, cfg: InfoPageDisplayConfig, scene: IngameScene, row: number) { this.Scene = scene; this.Row = row; this.BaseOffset = cfg.Position.Y + cfg.TitleHeight; this.CurrentInfo = tabInfo; this.Id = `${this.Row}_champIcon`; this.CreateTextureListeners(); var ProgressColor = Phaser.Display.Color.IntegerToColor(tabInfo.ExtraInfo[2] === "ORDER" ? variables.fallbackBlue : variables.fallbackRed); if (cfg.TabConfig.ProgressBar.UseTeamColors && this.Scene.state?.blueColor !== undefined && this.Scene.state.blueColor !== '') { ProgressColor = Phaser.Display.Color.RGBStringToColor(tabInfo.ExtraInfo[2] === "ORDER" ? this.Scene.state?.blueColor : this.Scene.state?.redColor); } else { ProgressColor = Phaser.Display.Color.RGBStringToColor(tabInfo.ExtraInfo[2] === "ORDER" ? cfg.TabConfig.ProgressBar.OrderColor : cfg.TabConfig.ProgressBar.OrderColor); } var TextColor = Phaser.Display.Color.IntegerToColor(0xffffff); if (cfg.TabConfig.UseTeamColorsText && this.Scene.state?.blueColor !== undefined && this.Scene.state.blueColor !== '') { TextColor = Phaser.Display.Color.RGBStringToColor(tabInfo.ExtraInfo[2] === "ORDER" ? this.Scene.state?.blueColor : this.Scene.state?.redColor); } if (cfg.TabConfig.Separator.Enabled) { this.TopSeparator = scene.make.sprite({ x: cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.Separator.Position, InfoPageVisual.CurrentInfoType).X, y: this.BaseOffset + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.Separator.Position, InfoPageVisual.CurrentInfoType).Y + row * cfg.TabConfig.TabSize.Y, key: 'infoPageSeparator', add: false }); this.TopSeparator.setOrigin(0, 0); this.TopSeparator.setDepth(2); this.VisualComponents.push(this.TopSeparator); } if (cfg.TabConfig.PlayerName.Enabled) { this.Name = scene.add.text(cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.PlayerName.Position, InfoPageVisual.CurrentInfoType).X, this.BaseOffset + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.PlayerName.Position, InfoPageVisual.CurrentInfoType).Y + row * cfg.TabConfig.TabSize.Y, tabInfo.PlayerName, { fontFamily: cfg.TabConfig.PlayerName.Font.Name, fontSize: cfg.TabConfig.PlayerName.Font.Size, color: cfg.TabConfig.UseTeamColorsText ? this.ColorToRGBString(TextColor) : cfg.TabConfig.PlayerName.Font.Color, fontStyle: cfg.TabConfig.PlayerName.Font.Style, align: cfg.TabConfig.PlayerName.Font.Align }); this.Name.setDepth(2); this.VisualComponents.push(this.Name); } if (cfg.TabConfig.ProgressBar.Enabled) { this.ProgressBarTotal = this.Scene.add.rectangle(cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Position).X, this.BaseOffset + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Position, InfoPageVisual.CurrentInfoType).Y + row * cfg.TabConfig.TabSize.Y, InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Size, InfoPageVisual.CurrentInfoType).X, InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Size).Y, Phaser.Display.Color.RGBStringToColor(cfg.TabConfig.ProgressBar.DefaultColor).color); this.ProgressBarTotal.setOrigin(0, 0); this.ProgressBarTotal.setDepth(2); this.ProgresssBarCompleted = this.Scene.add.rectangle(cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Position).X, this.BaseOffset + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Position, InfoPageVisual.CurrentInfoType).Y + row * cfg.TabConfig.TabSize.Y, InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Size, InfoPageVisual.CurrentInfoType).X * ((tabInfo.Values.CurrentValue - tabInfo.Values.MinValue) / (tabInfo.Values.MaxValue - tabInfo.Values.MinValue)), InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Size, InfoPageVisual.CurrentInfoType).Y, ProgressColor.color); this.ProgresssBarCompleted.setOrigin(0, 0); this.ProgresssBarCompleted.setDepth(2); this.ProgresssBarCompleted.setFillStyle(ProgressColor.color); this.VisualComponents.push(this.ProgressBarTotal, this.ProgresssBarCompleted); } if (cfg.TabConfig.MinValue.Enabled) { this.MinVal = scene.add.text(cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.MinValue.Position, InfoPageVisual.CurrentInfoType).X, this.BaseOffset + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.MinValue.Position, InfoPageVisual.CurrentInfoType).Y + row * cfg.TabConfig.TabSize.Y, tabInfo.Values.MinValue + '', { fontFamily: cfg.TabConfig.MinValue.Font.Name, fontSize: cfg.TabConfig.MinValue.Font.Size, color: cfg.TabConfig.UseTeamColorsText ? this.ColorToRGBString(TextColor) : cfg.TabConfig.MinValue.Font.Color, fontStyle: cfg.TabConfig.MinValue.Font.Style, align: cfg.TabConfig.MinValue.Font.Align }); if (cfg.TabConfig.MinValue.Font.Align === "right" || cfg.TabConfig.MinValue.Font.Align === "Right") this.MinVal.setOrigin(1, 0); if (cfg.TabConfig.MinValue.Font.Align === "left" || cfg.TabConfig.MinValue.Font.Align === "Left") this.MinVal.setOrigin(0, 0); this.MinVal.setDepth(2); this.VisualComponents.push(this.MinVal); } if (cfg.TabConfig.MaxValue.Enabled) { this.MaxVal = scene.add.text(cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.MaxValue.Position, InfoPageVisual.CurrentInfoType).X, this.BaseOffset + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.MaxValue.Position, InfoPageVisual.CurrentInfoType).Y + row * cfg.TabConfig.TabSize.Y, tabInfo.Values.MaxValue + '', { fontFamily: cfg.TabConfig.MaxValue.Font.Name, fontSize: cfg.TabConfig.MaxValue.Font.Size, color: cfg.TabConfig.UseTeamColorsText ? this.ColorToRGBString(TextColor) : cfg.TabConfig.MaxValue.Font.Color, fontStyle: cfg.TabConfig.MaxValue.Font.Style, align: cfg.TabConfig.MaxValue.Font.Align }); if (cfg.TabConfig.MaxValue.Font.Align === "right" || cfg.TabConfig.MaxValue.Font.Align === "Right") this.MaxVal.setOrigin(1, 0); if (cfg.TabConfig.MaxValue.Font.Align === "left" || cfg.TabConfig.MaxValue.Font.Align === "Left") this.MaxVal.setOrigin(0, 0); this.MaxVal.setDepth(2); this.VisualComponents.push(this.MaxVal); } if (cfg.TabConfig.CurrentValue.Enabled) { this.MainVal = scene.add.text(cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.CurrentValue.Position, InfoPageVisual.CurrentInfoType).X, this.BaseOffset + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.CurrentValue.Position, InfoPageVisual.CurrentInfoType).Y + row * cfg.TabConfig.TabSize.Y, tabInfo.ExtraInfo[0], { fontFamily: cfg.TabConfig.CurrentValue.Font.Name, fontSize: cfg.TabConfig.CurrentValue.Font.Size, color: cfg.TabConfig.UseTeamColorsText ? this.ColorToRGBString(TextColor) : cfg.TabConfig.CurrentValue.Font.Color, fontStyle: cfg.TabConfig.CurrentValue.Font.Style, align: cfg.TabConfig.CurrentValue.Font.Align }); this.MainVal.setOrigin(0.5, 0); this.MainVal.setDepth(2); this.VisualComponents.push(this.MainVal); } this.PlayerName = tabInfo.PlayerName; this.GetActiveVisualComponents().forEach(vc => { vc.alpha = 0; }); this.LoadIcon(tabInfo.IconPath, row); } LoadIcon(iconLoc: string, row: number): void { iconLoc = PlaceholderConversion.MakeUrlAbsolute(iconLoc.replace('Cache', '/cache').replace('\\', '/')); if (this.Image !== undefined && this.Image !== null) { this.Image.destroy(); } if (this.Scene.textures.exists(this.Id)) { this.Scene.textures.remove(this.Id); } if (!InfoPageVisual.GetConfig()?.TabConfig.ChampIcon.Enabled) { return; } this.Scene.load.image(this.Id, iconLoc); this.Scene.load.start(); } UpdateValues(tabInfo: PlayerInfoTab): void { this.CurrentInfo = tabInfo; let width = InfoPageVisual.GetCurrentElementVector2(InfoPageVisual.GetConfig()!.TabConfig.ProgressBar.Size, InfoPageVisual.CurrentInfoType).X; var newWidth = width * ((tabInfo.Values.CurrentValue - tabInfo.Values.MinValue) / (tabInfo.Values.MaxValue - tabInfo.Values.MinValue)); if (newWidth > width) newWidth = width; if (newWidth < 0) newWidth = 0; if (this.PlayerName !== tabInfo.PlayerName) { this.LoadIcon(tabInfo.IconPath, this.Row) this.PlayerName = tabInfo.PlayerName; var ProgressColor = Phaser.Display.Color.IntegerToColor(tabInfo.ExtraInfo[2] === "ORDER" ? variables.fallbackBlue : variables.fallbackRed); if (InfoPageVisual.GetConfig()!.TabConfig.ProgressBar.UseTeamColors && this.Scene.state?.blueColor !== undefined && this.Scene.state.blueColor !== '') { ProgressColor = Phaser.Display.Color.RGBStringToColor(tabInfo.ExtraInfo[2] === "ORDER" ? this.Scene.state?.blueColor : this.Scene.state?.redColor); } else { ProgressColor = Phaser.Display.Color.RGBStringToColor(tabInfo.ExtraInfo[2] === "ORDER" ? InfoPageVisual.GetConfig()!.TabConfig.ProgressBar.OrderColor : InfoPageVisual.GetConfig()!.TabConfig.ProgressBar.OrderColor); } if (InfoPageVisual.GetConfig()!.TabConfig.ProgressBar.Enabled) { this.ProgresssBarCompleted!.width = newWidth; this.ProgresssBarCompleted!.setFillStyle(ProgressColor.color); } } else { var ctx = this; ctx.Scene.tweens.add({ targets: ctx.ProgresssBarCompleted, props: { width: { value: newWidth, duration: 500, ease: 'Cubic.easeInOut' } }, paused: false, yoyo: false }); } let min = ""; let max = ""; let cur = ""; switch (tabInfo.ExtraInfo[1]) { case "gold": //Dont show min as its always going to be 0 //min = Math.trunc(tabInfo.Values.MinValue) + ''; min = ''; max = Math.trunc(tabInfo.Values.CurrentValue) + ''; let val = Math.trunc(tabInfo.Values.CurrentValue); cur = Utils.ConvertGold(val); if (cur.includes('NaN')) { console.log(`${val} -> ${cur}`); } break; case 'cspm': min = tabInfo.Values.MinValue.toFixed(1); max = Math.trunc((tabInfo.ExtraInfo[0] as unknown as number)) + ''; cur = (tabInfo.Values.CurrentValue).toFixed(1); break; default: min = tabInfo.Values.MinValue + ''; max = tabInfo.Values.MaxValue + '' cur = tabInfo.ExtraInfo[0]; break; } if (InfoPageVisual.GetConfig()!.TabConfig.PlayerName.Enabled) this.Name!.text = tabInfo.PlayerName; if (InfoPageVisual.GetConfig()!.TabConfig.MinValue.Enabled) this.MinVal!.text = min; if (InfoPageVisual.GetConfig()!.TabConfig.MaxValue.Enabled) this.MaxVal!.text = max; if (InfoPageVisual.GetConfig()!.TabConfig.CurrentValue.Enabled) this.MainVal!.text = cur; } UpdateConfig(cfg: InfoPageDisplayConfig): void { var ProgressColor = Phaser.Display.Color.IntegerToColor(this.CurrentInfo.ExtraInfo[2] === "ORDER" ? variables.fallbackBlue : variables.fallbackRed); if (cfg.TabConfig.ProgressBar.UseTeamColors && this.Scene.state?.blueColor !== undefined && this.Scene.state.blueColor !== '') { ProgressColor = Phaser.Display.Color.RGBStringToColor(this.CurrentInfo.ExtraInfo[2] === "ORDER" ? this.Scene.state?.blueColor : this.Scene.state?.redColor); } else { ProgressColor = Phaser.Display.Color.RGBStringToColor(this.CurrentInfo.ExtraInfo[2] === "ORDER" ? cfg.TabConfig.ProgressBar.OrderColor : cfg.TabConfig.ProgressBar.OrderColor); } var TextColor = Phaser.Display.Color.IntegerToColor(0xffffff); if (cfg.TabConfig.UseTeamColorsText && this.Scene.state?.blueColor !== undefined && this.Scene.state.blueColor !== '') { TextColor = Phaser.Display.Color.RGBStringToColor(this.CurrentInfo.ExtraInfo[2] === "ORDER" ? this.Scene.state?.blueColor : this.Scene.state?.redColor); } if (cfg.TabConfig.Separator.Enabled) { if (this.TopSeparator !== null && this.TopSeparator !== undefined) { this.TopSeparator.setPosition(cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.Separator.Position, InfoPageVisual.CurrentInfoType).X, this.BaseOffset + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.Separator.Position, InfoPageVisual.CurrentInfoType).Y + this.Row * cfg.TabConfig.TabSize.Y); } else { this.TopSeparator = this.Scene.make.sprite({ x: cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.Separator.Position, InfoPageVisual.CurrentInfoType).X, y: this.BaseOffset + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.Separator.Position, InfoPageVisual.CurrentInfoType).Y + this.Row * cfg.TabConfig.TabSize.Y, key: 'infoPageSeparator', add: true }); this.TopSeparator.setOrigin(0, 0); this.TopSeparator.setDepth(2); this.VisualComponents.push(this.TopSeparator); } } if (!cfg.TabConfig.Separator.Enabled && InfoPageVisual.GetConfig()?.TabConfig.Separator.Enabled) { this.RemoveVisualComponent(this.TopSeparator); this.TopSeparator?.destroy(); this.TopSeparator = null; } if (cfg.TabConfig.PlayerName.Enabled) { if (this.Name !== null && this.Name !== undefined) { this.Name.setPosition(cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.PlayerName.Position, InfoPageVisual.CurrentInfoType).X, this.BaseOffset + 6 + this.Row * cfg.TabConfig.TabSize.Y); this.UpdateTextStyle(this.Name, cfg.TabConfig.PlayerName.Font); } else { this.Name = this.Scene.add.text(cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.PlayerName.Position, InfoPageVisual.CurrentInfoType).X, this.BaseOffset + 6 + this.Row * cfg.TabConfig.TabSize.Y, this.CurrentInfo.PlayerName, { fontFamily: cfg.TabConfig.PlayerName.Font.Name, fontSize: cfg.TabConfig.PlayerName.Font.Size, color: cfg.TabConfig.UseTeamColorsText ? this.ColorToRGBString(TextColor) : cfg.TabConfig.PlayerName.Font.Color, fontStyle: cfg.TabConfig.PlayerName.Font.Style, align: cfg.TabConfig.PlayerName.Font.Align }); this.Name.setDepth(2); this.VisualComponents.push(this.Name); } } if (!cfg.TabConfig.PlayerName.Enabled && InfoPageVisual.GetConfig()?.TabConfig.PlayerName.Enabled) { this.RemoveVisualComponent(this.Name); this.Name?.destroy(); this.Name = null; } if (cfg.TabConfig.ProgressBar.Enabled) { if (this.ProgressBarTotal !== undefined && this.ProgressBarTotal !== null) { this.ProgressBarTotal.setPosition(cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Position, InfoPageVisual.CurrentInfoType).X, this.BaseOffset + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Position, InfoPageVisual.CurrentInfoType).Y + this.Row * cfg.TabConfig.TabSize.Y); this.ProgressBarTotal.setDisplaySize(InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Size, InfoPageVisual.CurrentInfoType).X, InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Size).Y); this.ProgresssBarCompleted?.setPosition(cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Position, InfoPageVisual.CurrentInfoType).X, this.BaseOffset + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Position, InfoPageVisual.CurrentInfoType).Y + this.Row * cfg.TabConfig.TabSize.Y); } else { this.ProgressBarTotal = this.Scene.add.rectangle(cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Position, InfoPageVisual.CurrentInfoType).X, this.BaseOffset + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Position, InfoPageVisual.CurrentInfoType).Y + this.Row * cfg.TabConfig.TabSize.Y, InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Size, InfoPageVisual.CurrentInfoType).X, InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Size, InfoPageVisual.CurrentInfoType).Y, Phaser.Display.Color.RGBStringToColor(cfg.TabConfig.ProgressBar.DefaultColor).color); this.ProgressBarTotal.setOrigin(0, 0); this.ProgressBarTotal.setDepth(2); this.ProgresssBarCompleted = this.Scene.add.rectangle(cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Position, InfoPageVisual.CurrentInfoType).X, this.BaseOffset + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Position, InfoPageVisual.CurrentInfoType).Y + this.Row * cfg.TabConfig.TabSize.Y, InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Size, InfoPageVisual.CurrentInfoType).X * ((this.CurrentInfo.Values.CurrentValue - this.CurrentInfo.Values.MinValue) / (this.CurrentInfo.Values.MaxValue - this.CurrentInfo.Values.MinValue)), InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.ProgressBar.Size, InfoPageVisual.CurrentInfoType).Y, ProgressColor.color); this.ProgresssBarCompleted.setDepth(2); this.ProgresssBarCompleted.setOrigin(0, 0); this.VisualComponents.push(this.ProgressBarTotal, this.ProgresssBarCompleted); } this.ProgresssBarCompleted!.setFillStyle(ProgressColor.color); } if (!cfg.TabConfig.ProgressBar.Enabled && InfoPageVisual.GetConfig()?.TabConfig.ProgressBar.Enabled) { this.RemoveVisualComponent(this.ProgressBarTotal); this.RemoveVisualComponent(this.ProgresssBarCompleted); this.ProgressBarTotal?.destroy(); this.ProgresssBarCompleted?.destroy(); this.ProgressBarTotal = null; this.ProgresssBarCompleted = null; } if (cfg.TabConfig.MinValue.Enabled) { if (this.MinVal !== undefined && this.MinVal !== null) { this.MinVal.setPosition(cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.MinValue.Position, InfoPageVisual.CurrentInfoType).X, this.BaseOffset + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.MinValue.Position, InfoPageVisual.CurrentInfoType).Y + this.Row * cfg.TabConfig.TabSize.Y); this.UpdateTextStyle(this.MinVal, cfg.TabConfig.MinValue.Font); } else { this.MinVal = this.Scene.add.text(cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.MinValue.Position, InfoPageVisual.CurrentInfoType).X, this.BaseOffset + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.MinValue.Position, InfoPageVisual.CurrentInfoType).Y + this.Row * cfg.TabConfig.TabSize.Y, this.CurrentInfo.Values.MinValue + '', { fontFamily: cfg.TabConfig.MinValue.Font.Name, fontSize: cfg.TabConfig.MinValue.Font.Size, color: cfg.TabConfig.UseTeamColorsText ? this.ColorToRGBString(TextColor) : cfg.TabConfig.MinValue.Font.Color, fontStyle: cfg.TabConfig.MinValue.Font.Style, align: cfg.TabConfig.MinValue.Font.Align }); if (cfg.TabConfig.MinValue.Font.Align === "right" || cfg.TabConfig.MinValue.Font.Align === "Right") this.MinVal.setOrigin(1, 0); if (cfg.TabConfig.MinValue.Font.Align === "left" || cfg.TabConfig.MinValue.Font.Align === "Left") this.MinVal.setOrigin(0, 0); this.MinVal.setDepth(2); this.VisualComponents.push(this.MinVal); } } if (!cfg.TabConfig.MinValue.Enabled && InfoPageVisual.GetConfig()?.TabConfig.MinValue.Enabled) { this.RemoveVisualComponent(this.MinVal); this.MinVal?.destroy(); this.MinVal = null; } if (cfg.TabConfig.MaxValue.Enabled) { if (this.MaxVal !== undefined && this.MaxVal !== null) { this.MaxVal.setPosition(cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.MaxValue.Position, InfoPageVisual.CurrentInfoType).X, this.BaseOffset + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.MaxValue.Position, InfoPageVisual.CurrentInfoType).Y + this.Row * cfg.TabConfig.TabSize.Y); this.UpdateTextStyle(this.MaxVal, cfg.TabConfig.MaxValue.Font); } else { this.MaxVal = this.Scene.add.text(cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.MaxValue.Position, InfoPageVisual.CurrentInfoType).X, this.BaseOffset + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.MaxValue.Position, InfoPageVisual.CurrentInfoType).Y + this.Row * cfg.TabConfig.TabSize.Y, this.CurrentInfo.Values.MaxValue + '', { fontFamily: cfg.TabConfig.MaxValue.Font.Name, fontSize: cfg.TabConfig.MaxValue.Font.Size, color: cfg.TabConfig.UseTeamColorsText ? this.ColorToRGBString(TextColor) : cfg.TabConfig.MaxValue.Font.Color, fontStyle: cfg.TabConfig.MaxValue.Font.Style, align: cfg.TabConfig.MaxValue.Font.Align }); if (cfg.TabConfig.MaxValue.Font.Align === "right" || cfg.TabConfig.MaxValue.Font.Align === "Right") this.MaxVal.setOrigin(1, 0); if (cfg.TabConfig.MaxValue.Font.Align === "left" || cfg.TabConfig.MaxValue.Font.Align === "Left") this.MaxVal.setOrigin(0, 0); this.MaxVal.setDepth(2); this.VisualComponents.push(this.MaxVal); } } if (!cfg.TabConfig.MaxValue.Enabled && InfoPageVisual.GetConfig()?.TabConfig.MaxValue.Enabled) { this.RemoveVisualComponent(this.MaxVal); this.MaxVal?.destroy(); this.MaxVal = null; } if (cfg.TabConfig.CurrentValue.Enabled) { if (this.MainVal !== undefined && this.MainVal !== null) { this.MainVal.setPosition(cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.CurrentValue.Position, InfoPageVisual.CurrentInfoType).X, this.BaseOffset + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.CurrentValue.Position, InfoPageVisual.CurrentInfoType).Y + this.Row * cfg.TabConfig.TabSize.Y); this.UpdateTextStyle(this.MainVal, cfg.TabConfig.CurrentValue.Font); } else { this.MainVal = this.Scene.add.text(cfg.Position.X + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.CurrentValue.Position, InfoPageVisual.CurrentInfoType).X, this.BaseOffset + InfoPageVisual.GetCurrentElementVector2(cfg.TabConfig.CurrentValue.Position, InfoPageVisual.CurrentInfoType).Y + this.Row * cfg.TabConfig.TabSize.Y, this.CurrentInfo.ExtraInfo[0], { fontFamily: cfg.TabConfig.CurrentValue.Font.Name, fontSize: cfg.TabConfig.CurrentValue.Font.Size, color: cfg.TabConfig.UseTeamColorsText ? this.ColorToRGBString(TextColor) : cfg.TabConfig.CurrentValue.Font.Color, fontStyle: cfg.TabConfig.CurrentValue.Font.Style, align: cfg.TabConfig.CurrentValue.Font.Align }); this.MainVal.setDepth(2); this.MainVal.setOrigin(0.5, 0); this.VisualComponents.push(this.MainVal); } } if (!cfg.TabConfig.CurrentValue.Enabled && InfoPageVisual.GetConfig()?.TabConfig.CurrentValue.Enabled) { this.RemoveVisualComponent(this.MainVal); this.MainVal?.destroy(); this.MainVal = null; } if (this.Scene.info.isActive || this.Scene.info.isHiding) { this.GetActiveVisualComponents().forEach(vc => { vc.alpha = 0; }); } } SetBarWidth(width: number = 210): void { if (width === InfoPageVisual.GetCurrentElementVector2(InfoPageVisual.GetConfig()!.TabConfig.ProgressBar.Size, InfoPageVisual.CurrentInfoType).X || !InfoPageVisual.GetConfig()!.TabConfig.ProgressBar.Enabled || this.ProgresssBarCompleted === null) return; this.ProgressBarTotal!.width = width; this.ProgresssBarCompleted!.width = 0; } Start(): void { var ctx = this; ctx.Scene.tweens.add({ targets: [ctx.TopSeparator, ctx.Name, ctx.Image, ctx.ProgressBarTotal, ctx.ProgresssBarCompleted, ctx.MinVal, ctx.MainVal, ctx.MaxVal], props: { alpha: { from: 0, to: 1, duration: 500, ease: 'Cubic.easeInOut' } }, paused: false, yoyo: false, duration: 500 }); } Stop(): void { var ctx = this; ctx.Scene.tweens.add({ targets: [ctx.TopSeparator, ctx.Name, ctx.Image, ctx.ProgressBarTotal, ctx.ProgresssBarCompleted, ctx.MinVal, ctx.MainVal, ctx.MaxVal], props: { alpha: { from: 1, to: 0, duration: 500, ease: 'Cubic.easeInOut' } }, paused: false, yoyo: false, duration: 500 }); } CreateTextureListeners(): void { this.Scene.load.on(`filecomplete-image-${this.Id}`, () => { this.Image = this.Scene.make.sprite({ x: InfoPageVisual.GetConfig()!.Position.X + InfoPageVisual.GetCurrentElementVector2(InfoPageVisual.GetConfig()!.TabConfig.ChampIcon.Position).X, y: InfoPageVisual.GetConfig()!.Position.Y + InfoPageVisual.GetConfig()!.TitleHeight + this.Row * InfoPageVisual.GetConfig()!.TabConfig.TabSize.Y + InfoPageVisual.GetCurrentElementVector2(InfoPageVisual.GetConfig()!.TabConfig.ChampIcon.Position).Y, key: this.Id, add: true }); this.Image.setOrigin(0, 0); this.Image.setDepth(2); this.Image.displayWidth = InfoPageVisual.GetConfig()!.TabConfig.ChampIcon.Size.X; this.Image.displayHeight = InfoPageVisual.GetConfig()!.TabConfig.ChampIcon.Size.Y; this.Image.alpha = 0; if (this.Scene.info.isActive) { this.Image.alpha = 1; } if(this.Scene.info.isShowing) { setTimeout(() => { let ctx = this; ctx.Scene.tweens.add({ targets: ctx.Image, props: { alpha: { from: 0, to: 1, duration: 500, ease: 'Cubic.easeInOut' } }, paused: false, yoyo: false, duration: 500 }); }, this.Scene.info.currentAnimation[0].duration - this.Scene.info.currentAnimation[0].elapsed); } }); } ColorToRGBString(Color: Phaser.Display.Color): string { return `rgb(${Color.red},${Color.green},${Color.blue})` } //I hate duplicating code but making each player tab a separate VE seems overkill... I think... I'm probably wrong GetActiveVisualComponents(): any[] { return this.VisualComponents.filter(c => c !== null && c !== undefined); } RemoveVisualComponent(component: any): void { this.VisualComponents = this.VisualComponents.filter(c => c !== component); } AddVisualComponent(component: any): void { const componentInList = this.VisualComponents.find(c => c === component); if (componentInList === undefined) { this.VisualComponents.push(component); } } UpdateTextStyle(textElement: Phaser.GameObjects.Text, style: { Name: string, Size: string, Align: string, Color: string, Style: string }): void { textElement.setFontFamily(style.Name); textElement.setFontStyle(style.Style); //@ts-ignore textElement.setFontSize(style.Size) textElement.setColor(style.Color); textElement.setAlign(style.Align); } }
the_stack
import {IApp} from '../../IApp'; import {KeyboardInputManager} from './KeyboardInputManager'; import {KeyDownEventArgs} from './KeyDownEventArgs'; import {KeyUpEventArgs} from './KeyUpEventArgs'; declare var App: IApp; export class PianoKeyboardManager extends KeyboardInputManager { public PianoKeyboardMap: any; public PianoKeyboardMapFallBack: any; public KeyDown: number; public KeyUp: number; KeyDownChange = new nullstone.Event<KeyDownEventArgs>(); KeyUpChange = new nullstone.Event<KeyUpEventArgs>(); constructor() { super(); /** * Piano Keyboard Map * Musical notes follow * note_ + (musical note letter) + _octave (A is lowest) */ /*this.PianoKeyboardMap = { 'ArrowUp': 'octave-up', 'ArrowDown': 'octave-down', 'Digit0': 'note_G#_b', 'Digit2': 'note_F#_a', 'Digit3': 'note_G#_a', 'Digit4': 'note_A#_a', 'Digit6': 'note_C#_b', 'Digit7': 'note_D#_b', 'Digit9': 'note_F#_b', 'KeyB': 'note_G_c', 'KeyC': 'note_E_c', 'KeyD': 'note_D#_c', 'KeyE': 'note_A_a', 'KeyG': 'note_F#_c', 'KeyH': 'note_G#_c', 'KeyI': 'note_F_b', 'KeyJ': 'note_A#_c', 'KeyL': 'note_C#_d', 'KeyM': 'note_B_c', 'KeyN': 'note_A_c', 'KeyO': 'note_G_b', 'KeyP': 'note_A_b', 'KeyQ': 'note_F_a', 'KeyR': 'note_B_a', 'KeyS': 'note_C#_c', 'KeyT': 'note_C_b', 'KeyU': 'note_E_b', 'KeyV': 'note_F_c', 'KeyW': 'note_G_a', 'KeyX': 'note_D_c', 'KeyY': 'note_D_b', 'KeyZ': 'note_C_c', 'NumpadAdd': 'octave-up', 'NumpadSubtract': 'octave-down', 'Semicolon': 'note_D#_d', 'Comma': 'note_C_d', 'Minus': 'note_A#_b', 'Period': 'note_D_d', 'Slash': 'note_E_d', 'BracketLeft': 'note_B_b', 'BracketRight': 'note_C_c', 'OSLeft': 'blank', 'OSRight': 'blank', };*/ // MIDI NOTE CODES // // 1000 transpose down // 1001 transpose up // this.PianoKeyboardMap = { // 'ArrowUp': 1001, // 'ArrowDown': 1000, // 'Digit0': 68, // 'Digit2': 54, // 'Digit3': 56, // 'Digit4': 58, // 'Digit6': 61, // 'Digit7': 63, // 'Digit9': 66, // 'KeyB': 79, // 'KeyC': 76, // 'KeyD': 75, // 'KeyE': 57, // 'KeyG': 78, // 'KeyH': 80, // 'KeyI': 65, // 'KeyJ': 82, // 'KeyL': 85, // 'KeyM': 83, // 'KeyN': 81, // 'KeyO': 67, // 'KeyP': 69, // 'KeyQ': 53, // 'KeyR': 59, // 'KeyS': 73, // 'KeyT': 60, // 'KeyU': 64, // 'KeyV': 77, // 'KeyW': 55, // 'KeyX': 74, // 'KeyY': 62, // 'KeyZ': 72, // 'NumpadAdd': 1001, // 'NumpadSubtract': 1000, // 'Semicolon': 87, // 'Comma': 84, // 'Minus': 70, // 'Period': 86, // 'Slash': 88, // 'BracketLeft': 71, // 'BracketRight': 72, // 'OSLeft': -1, // 'OSRight': -1, // }; this.PianoKeyboardMap = { 'ArrowUp': 1001, 'ArrowDown': 1000, 'Digit0': 75, 'Digit2': 61, 'Digit3': 63, 'Digit5': 66, 'Digit6': 68, 'Digit7': 70, 'Digit9': 73, 'KeyB': 55, 'KeyC': 52, 'KeyD': 51, 'KeyE': 64, 'KeyG': 54, 'KeyH': 56, 'KeyI': 72, 'KeyJ': 58, 'KeyL': 61, 'KeyM': 59, 'KeyN': 57, 'KeyO': 74, 'KeyP': 76, 'KeyQ': 60, 'KeyR': 65, 'KeyS': 49, 'KeyT': 67, 'KeyU': 71, 'KeyV': 53, 'KeyW': 62, 'KeyX': 50, 'KeyY': 69, 'KeyZ': 48, 'NumpadAdd': 1001, 'NumpadSubtract': 1000, 'Semicolon': 63, 'Comma': 60, 'Equal': 78, 'Period': 62, 'Slash': 64, 'BracketLeft': 77, 'BracketRight': 79, 'OSLeft': -1, 'OSRight': -1, }; /** * This is used for browsers that haven't implemented KeyboardEvent.code yet. * Using KeyboardEvent.code means that the piano will work using all keyboard layouts */ this.PianoKeyboardMapFallBack = { 38: this.PianoKeyboardMap['ArrowUp'], 40: this.PianoKeyboardMap['ArrowDown'], 48: this.PianoKeyboardMap['Digit0'], 50: this.PianoKeyboardMap['Digit2'], 51: this.PianoKeyboardMap['Digit3'], 52: this.PianoKeyboardMap['Digit4'], 54: this.PianoKeyboardMap['Digit6'], 55: this.PianoKeyboardMap['Digit7'], 57: this.PianoKeyboardMap['Digit9'], 66: this.PianoKeyboardMap['KeyB'], 67: this.PianoKeyboardMap['KeyC'], 68: this.PianoKeyboardMap['KeyD'], 69: this.PianoKeyboardMap['KeyE'], 71: this.PianoKeyboardMap['KeyG'], 72: this.PianoKeyboardMap['KeyH'], 73: this.PianoKeyboardMap['KeyI'], 74: this.PianoKeyboardMap['KeyJ'], 76: this.PianoKeyboardMap['KeyL'], 77: this.PianoKeyboardMap['KeyM'], 78: this.PianoKeyboardMap['KeyN'], 79: this.PianoKeyboardMap['KeyO'], 80: this.PianoKeyboardMap['KeyP'], 81: this.PianoKeyboardMap['KeyQ'], 82: this.PianoKeyboardMap['KeyR'], 83: this.PianoKeyboardMap['KeyS'], 84: this.PianoKeyboardMap['KeyT'], 85: this.PianoKeyboardMap['KeyU'], 86: this.PianoKeyboardMap['KeyV'], 87: this.PianoKeyboardMap['KeyW'], 88: this.PianoKeyboardMap['KeyX'], 89: this.PianoKeyboardMap['KeyY'], 90: this.PianoKeyboardMap['KeyZ'], 91: this.PianoKeyboardMap['OSLeft'], 93: this.PianoKeyboardMap['OSRight'], 107: this.PianoKeyboardMap['NumpadAdd'], 109: this.PianoKeyboardMap['NumpadSubtract'], 186: this.PianoKeyboardMap['Semicolon'], 188: this.PianoKeyboardMap['Comma'], 189: this.PianoKeyboardMap['Minus'], 190: this.PianoKeyboardMap['Period'], 191: this.PianoKeyboardMap['Slash'], 219: this.PianoKeyboardMap['BracketLeft'], 221: this.PianoKeyboardMap['BracketRight'], }; } set IsEnabled(val: boolean) { if (val === false) { /*App.Sources.forEach((s) => { s.TriggerRelease('all'); })*/ } this._isEnabled = val; } get IsEnabled(): boolean { return this._isEnabled; } KeyboardDown(e) { if (!this.IsEnabled) return; var k: number; if (e.code){ k = this.PianoKeyboardMap[e.code]; } else { k = this.PianoKeyboardMapFallBack[e.keyCode]; } //Check if this key released is in our key_map if (typeof k !== undefined) { //if it's already pressed (holding note) if (k in this.KeysDown) { return; } //pressed first time, add to object this.KeysDown[k] = true; this.KeyDown = k; this.KeyDownChange.raise(this, new KeyDownEventArgs(this.KeyDown)); } } KeyboardUp(e) { if (!this.IsEnabled) return; var k: number; if (e.code){ k = this.PianoKeyboardMap[e.code]; } else { k = this.PianoKeyboardMapFallBack[e.keyCode]; } //Check if this key released is in out key_map if (typeof k !== undefined) { if (k === -1){ // if it's a blank key remove all this.KeysDown = {}; } else { // remove this key from the keysDown object delete this.KeysDown[k]; } this.KeyUp = k; this.KeyUpChange.raise(this, new KeyUpEventArgs(this.KeyUp)); } } /*KeyboardDown(e) { if (!this.IsEnabled) return; var k: string; if (e.code){ k = this.PianoKeyboardMap[e.code]; } else { k = this.PianoKeyboardMapFallBack[e.keyCode]; } //Check if this key released is in our key_map if (typeof k !== 'undefined' && k !== '') { //if it's already pressed (holding note) if (k in this.KeysDown) { return; } //pressed first time, add to object this.KeysDown[k] = true; this.KeyDown = k; this.KeyDownChange.raise(this, new KeyDownEventArgs(this.KeyDown)); } } KeyboardUp(e) { if (!this.IsEnabled) return; var k: string; if (e.code){ k = this.PianoKeyboardMap[e.code]; } else { k = this.PianoKeyboardMapFallBack[e.keyCode]; } //Check if this key released is in out key_map if (typeof k !== 'undefined' && k !== '') { if (k === 'blank'){ // if it's a blank key remove all this.KeysDown = {}; } else { // remove this key from the keysDown object delete this.KeysDown[k]; } this.KeyUp = k; this.KeyUpChange.raise(this, new KeyUpEventArgs(this.KeyUp)); } }*/ }
the_stack
export type Platform = 'browser' | 'node' | 'neutral'; export type Format = 'iife' | 'cjs' | 'esm'; export type Loader = 'js' | 'jsx' | 'ts' | 'tsx' | 'css' | 'json' | 'text' | 'base64' | 'file' | 'dataurl' | 'binary' | 'default'; export type LogLevel = 'verbose' | 'debug' | 'info' | 'warning' | 'error' | 'silent'; export type Charset = 'ascii' | 'utf8'; export type TreeShaking = true | 'ignore-annotations'; interface CommonOptions { sourcemap?: boolean | 'inline' | 'external' | 'both'; legalComments?: 'none' | 'inline' | 'eof' | 'linked' | 'external'; sourceRoot?: string; sourcesContent?: boolean; format?: Format; globalName?: string; target?: string | string[]; minify?: boolean; minifyWhitespace?: boolean; minifyIdentifiers?: boolean; minifySyntax?: boolean; charset?: Charset; treeShaking?: TreeShaking; jsx?: 'transform' | 'preserve'; jsxFactory?: string; jsxFragment?: string; define?: { [key: string]: string }; pure?: string[]; keepNames?: boolean; color?: boolean; logLevel?: LogLevel; logLimit?: number; } export interface BuildOptions extends CommonOptions { bundle?: boolean; splitting?: boolean; preserveSymlinks?: boolean; outfile?: string; metafile?: boolean; outdir?: string; outbase?: string; platform?: Platform; external?: string[]; loader?: { [ext: string]: Loader }; resolveExtensions?: string[]; mainFields?: string[]; conditions?: string[]; write?: boolean; allowOverwrite?: boolean; tsconfig?: string; outExtension?: { [ext: string]: string }; publicPath?: string; entryNames?: string; chunkNames?: string; assetNames?: string; inject?: string[]; banner?: { [type: string]: string }; footer?: { [type: string]: string }; incremental?: boolean; entryPoints?: string[] | Record<string, string>; stdin?: StdinOptions; plugins?: Plugin[]; absWorkingDir?: string; nodePaths?: string[]; // The "NODE_PATH" variable from Node.js watch?: boolean | WatchMode; } export interface WatchMode { onRebuild?: (error: BuildFailure | null, result: BuildResult | null) => void; } export interface StdinOptions { contents: string; resolveDir?: string; sourcefile?: string; loader?: Loader; } export interface Message { pluginName: string; text: string; location: Location | null; notes: Note[]; // Optional user-specified data that is passed through unmodified. You can // use this to stash the original error, for example. detail: any; } export interface Note { text: string; location: Location | null; } export interface Location { file: string; namespace: string; line: number; // 1-based column: number; // 0-based, in bytes length: number; // in bytes lineText: string; suggestion: string; } export interface OutputFile { path: string; contents: Uint8Array; // "text" as bytes text: string; // "contents" as text } export interface BuildInvalidate { (): Promise<BuildIncremental>; dispose(): void; } export interface BuildIncremental extends BuildResult { rebuild: BuildInvalidate; } export interface BuildResult { errors: Message[]; warnings: Message[]; outputFiles?: OutputFile[]; // Only when "write: false" rebuild?: BuildInvalidate; // Only when "incremental: true" stop?: () => void; // Only when "watch: true" metafile?: Metafile; // Only when "metafile: true" } export interface BuildFailure extends Error { errors: Message[]; warnings: Message[]; } export interface ServeOptions { port?: number; host?: string; servedir?: string; onRequest?: (args: ServeOnRequestArgs) => void; } export interface ServeOnRequestArgs { remoteAddress: string; method: string; path: string; status: number; timeInMS: number; // The time to generate the response, not to send it } export interface ServeResult { port: number; host: string; wait: Promise<void>; stop: () => void; } export interface TransformOptions extends CommonOptions { tsconfigRaw?: string | { compilerOptions?: { jsxFactory?: string, jsxFragmentFactory?: string, useDefineForClassFields?: boolean, importsNotUsedAsValues?: 'remove' | 'preserve' | 'error', }, }; sourcefile?: string; loader?: Loader; banner?: string; footer?: string; } export interface TransformResult { code: string; map: string; warnings: Message[]; } export interface TransformFailure extends Error { errors: Message[]; warnings: Message[]; } export interface Plugin { name: string; setup: (build: PluginBuild) => (void | Promise<void>); } export interface PluginBuild { initialOptions: BuildOptions; onStart(callback: () => (OnStartResult | null | void | Promise<OnStartResult | null | void>)): void; onEnd(callback: (result: BuildResult) => (void | Promise<void>)): void; onResolve(options: OnResolveOptions, callback: (args: OnResolveArgs) => (OnResolveResult | null | undefined | Promise<OnResolveResult | null | undefined>)): void; onLoad(options: OnLoadOptions, callback: (args: OnLoadArgs) => (OnLoadResult | null | undefined | Promise<OnLoadResult | null | undefined>)): void; } export interface OnStartResult { errors?: PartialMessage[]; warnings?: PartialMessage[]; } export interface OnResolveOptions { filter: RegExp; namespace?: string; } export interface OnResolveArgs { path: string; importer: string; namespace: string; resolveDir: string; kind: ImportKind; pluginData: any; } export type ImportKind = | 'entry-point' // JS | 'import-statement' | 'require-call' | 'dynamic-import' | 'require-resolve' // CSS | 'import-rule' | 'url-token' export interface OnResolveResult { pluginName?: string; errors?: PartialMessage[]; warnings?: PartialMessage[]; path?: string; external?: boolean; sideEffects?: boolean; namespace?: string; pluginData?: any; watchFiles?: string[]; watchDirs?: string[]; } export interface OnLoadOptions { filter: RegExp; namespace?: string; } export interface OnLoadArgs { path: string; namespace: string; pluginData: any; } export interface OnLoadResult { pluginName?: string; errors?: PartialMessage[]; warnings?: PartialMessage[]; contents?: string | Uint8Array; resolveDir?: string; loader?: Loader; pluginData?: any; watchFiles?: string[]; watchDirs?: string[]; } export interface PartialMessage { pluginName?: string; text?: string; location?: Partial<Location> | null; notes?: PartialNote[]; detail?: any; } export interface PartialNote { text?: string; location?: Partial<Location> | null; } export interface Metafile { inputs: { [path: string]: { bytes: number imports: { path: string kind: ImportKind }[] } } outputs: { [path: string]: { bytes: number inputs: { [path: string]: { bytesInOutput: number } } imports: { path: string kind: ImportKind }[] exports: string[] entryPoint?: string } } } export interface FormatMessagesOptions { kind: 'error' | 'warning'; color?: boolean; terminalWidth?: number; } // This function invokes the "esbuild" command-line tool for you. It returns a // promise that either resolves with a "BuildResult" object or rejects with a // "BuildFailure" object. // // Works in node: yes // Works in browser: yes export declare function build(options: BuildOptions & { write: false }): Promise<BuildResult & { outputFiles: OutputFile[] }>; export declare function build(options: BuildOptions & { incremental: true }): Promise<BuildIncremental>; export declare function build(options: BuildOptions): Promise<BuildResult>; // This function is similar to "build" but it serves the resulting files over // HTTP on a localhost address with the specified port. // // Works in node: yes // Works in browser: no export declare function serve(serveOptions: ServeOptions, buildOptions: BuildOptions): Promise<ServeResult>; // This function transforms a single JavaScript file. It can be used to minify // JavaScript, convert TypeScript/JSX to JavaScript, or convert newer JavaScript // to older JavaScript. It returns a promise that is either resolved with a // "TransformResult" object or rejected with a "TransformFailure" object. // // Works in node: yes // Works in browser: yes export declare function transform(input: string, options?: TransformOptions): Promise<TransformResult>; // Converts log messages to formatted message strings suitable for printing in // the terminal. This allows you to reuse the built-in behavior of esbuild's // log message formatter. This is a batch-oriented API for efficiency. // // Works in node: yes // Works in browser: yes export declare function formatMessages(messages: PartialMessage[], options: FormatMessagesOptions): Promise<string[]>; // A synchronous version of "build". // // Works in node: yes // Works in browser: no export declare function buildSync(options: BuildOptions & { write: false }): BuildResult & { outputFiles: OutputFile[] }; export declare function buildSync(options: BuildOptions): BuildResult; // A synchronous version of "transform". // // Works in node: yes // Works in browser: no export declare function transformSync(input: string, options?: TransformOptions): TransformResult; // A synchronous version of "formatMessages". // // Works in node: yes // Works in browser: no export declare function formatMessagesSync(messages: PartialMessage[], options: FormatMessagesOptions): string[]; // This configures the browser-based version of esbuild. It is necessary to // call this first and wait for the returned promise to be resolved before // making other API calls when using esbuild in the browser. // // Works in node: yes // Works in browser: yes ("options" is required) export declare function initialize(options: InitializeOptions): Promise<void>; export interface InitializeOptions { // The URL of the "esbuild.wasm" file. This must be provided when running // esbuild in the browser. wasmURL?: string // By default esbuild runs the WebAssembly-based browser API in a web worker // to avoid blocking the UI thread. This can be disabled by setting "worker" // to false. worker?: boolean } export let version: string;
the_stack
import { useContentGqlHandler } from "../utils/useContentGqlHandler"; import { createContentReviewSetup } from "../utils/helpers"; import { mocks as changeRequestMock } from "./mocks/changeRequest"; const updatedRichText = [ { tag: "h1", content: "Testing H1 tags - Updated" }, { tag: "p", content: "Some small piece of text to test P tags - Updated" }, { tag: "div", content: [ { tag: "p", text: "Text inside the div > p" }, { tag: "a", href: "https://www.webiny.com", text: "Webiny" } ] } ]; describe("ChangeRequest crud test", () => { const options = { path: "manage/en-US" }; const gqlHandler = useContentGqlHandler({ ...options }); const { getChangeRequestQuery, listChangeRequestsQuery, createChangeRequestMutation, updateChangeRequestMutation, deleteChangeRequestMutation, until } = gqlHandler; test(`should able to create, update, get, list and delete a "change request"`, async () => { const { contentReview } = await createContentReviewSetup(gqlHandler); const changeRequestStep = `${contentReview.id}#${contentReview.steps[0].id}`; /* * Create a new entry. */ const [createChangeRequestResponse] = await createChangeRequestMutation({ data: changeRequestMock.createChangeRequestInput({ step: changeRequestStep }) }); const createdChangeRequest = createChangeRequestResponse.data.apw.createChangeRequest.data; expect(createChangeRequestResponse).toEqual({ data: { apw: { createChangeRequest: { data: { id: expect.any(String), createdOn: expect.stringMatching(/^20/), savedOn: expect.stringMatching(/^20/), createdBy: { id: "12345678", displayName: "John Doe", type: "admin" }, title: expect.any(String), body: expect.any(Object), media: expect.any(Object), step: expect.any(String), resolved: null }, error: null } } } }); await until( () => getChangeRequestQuery({ id: createdChangeRequest.id }).then(([data]) => data), (response: any) => response.data.apw.getChangeRequest.data !== null, { name: "Wait for getChangeRequest query" } ); /** * Now that we have a entry, we should be able to get it. */ const [getChangeRequestByIdResponse] = await getChangeRequestQuery({ id: createdChangeRequest.id }); expect(getChangeRequestByIdResponse).toEqual({ data: { apw: { getChangeRequest: { data: { id: expect.any(String), createdOn: expect.stringMatching(/^20/), savedOn: expect.stringMatching(/^20/), createdBy: { id: "12345678", displayName: "John Doe", type: "admin" }, title: expect.any(String), body: expect.any(Object), media: expect.any(Object), step: expect.any(String), resolved: null }, error: null } } } }); /** * Let's update the entry. */ const [updateChangeRequestResponse] = await updateChangeRequestMutation({ id: createdChangeRequest.id, data: { body: updatedRichText, resolved: true } }); expect(updateChangeRequestResponse).toEqual({ data: { apw: { updateChangeRequest: { data: { id: expect.any(String), createdOn: expect.stringMatching(/^20/), savedOn: expect.stringMatching(/^20/), createdBy: { id: "12345678", displayName: "John Doe", type: "admin" }, title: expect.any(String), body: updatedRichText, media: expect.any(Object), step: expect.any(String), resolved: true }, error: null } } } }); await until( () => listChangeRequestsQuery({}).then(([data]) => data), (response: any) => { const [updatedItem] = response.data.apw.listChangeRequests.data; return updatedItem && createdChangeRequest.savedOn !== updatedItem.savedOn; }, { name: "Wait for updated entry to be available via listChangeRequests query" } ); /** * Let's list all entries should return only one. */ const [listChangeRequestsResponse] = await listChangeRequestsQuery({}); expect(listChangeRequestsResponse).toEqual({ data: { apw: { listChangeRequests: { data: [ { id: expect.any(String), createdOn: expect.stringMatching(/^20/), savedOn: expect.stringMatching(/^20/), createdBy: { id: "12345678", displayName: "John Doe", type: "admin" }, title: expect.any(String), media: expect.any(Object), step: expect.any(String), resolved: true, body: updatedRichText } ], error: null, meta: { hasMoreItems: false, totalCount: 1, cursor: null } } } } }); /** * Delete the only entry we have. */ const [deleteChangeRequestResponse] = await deleteChangeRequestMutation({ id: createdChangeRequest.id }); expect(deleteChangeRequestResponse).toEqual({ data: { apw: { deleteChangeRequest: { data: true, error: null } } } }); await until( () => listChangeRequestsQuery({}).then(([data]) => data), (response: any) => { const list = response.data.apw.listChangeRequests.data; return list.length === 0; }, { name: "Wait for empty list after deleting entry" } ); /** * Now that we've deleted the only entry we had, we should get empty list as response. */ const [listChangeRequestsAgainResponse] = await listChangeRequestsQuery({}); expect(listChangeRequestsAgainResponse).toEqual({ data: { apw: { listChangeRequests: { data: [], error: null, meta: { hasMoreItems: false, totalCount: 0, cursor: null } } } } }); }); test(`should not able to create "change request" with wrong step`, async () => { /* * Create a new entry. */ let [createChangeRequestResponse] = await createChangeRequestMutation({ data: changeRequestMock.createChangeRequestInput({ step: "61af1a60f04e49226e6cc17e#design_review" }) }); expect(createChangeRequestResponse).toEqual({ data: { apw: { createChangeRequest: { data: null, error: { message: expect.any(String), code: "MALFORMED_CHANGE_REQUEST_STEP", data: expect.any(Object) } } } } }); const nonExistingContentReview = "61af1a60f04e49226e6cc17e#0001#design_review"; [createChangeRequestResponse] = await createChangeRequestMutation({ data: changeRequestMock.createChangeRequestInput({ step: nonExistingContentReview }) }); expect(createChangeRequestResponse).toEqual({ data: { apw: { createChangeRequest: { data: null, error: { message: expect.any(String), code: "NOT_FOUND", data: expect.any(Object) } } } } }); }); });
the_stack
import { Contract, ContractTransaction, EventFilter, Signer } from 'ethers'; import { Listener, Provider } from 'ethers/providers'; import { Arrayish, BigNumber, BigNumberish, Interface } from 'ethers/utils'; import { TransactionOverrides, TypedEventDescription, TypedFunctionDescription, } from '.'; interface ERC20Interface extends Interface { functions: { name: TypedFunctionDescription<{ encode([]: []): string }>; symbol: TypedFunctionDescription<{ encode([]: []): string }>; decimals: TypedFunctionDescription<{ encode([]: []): string }>; totalSupply: TypedFunctionDescription<{ encode([]: []): string }>; balanceOf: TypedFunctionDescription<{ encode([account]: [string]): string; }>; transfer: TypedFunctionDescription<{ encode([recipient, amount]: [string, BigNumberish]): string; }>; allowance: TypedFunctionDescription<{ encode([owner, spender]: [string, string]): string; }>; approve: TypedFunctionDescription<{ encode([spender, amount]: [string, BigNumberish]): string; }>; transferFrom: TypedFunctionDescription<{ encode([sender, recipient, amount]: [ string, string, BigNumberish, ]): string; }>; increaseAllowance: TypedFunctionDescription<{ encode([spender, addedValue]: [string, BigNumberish]): string; }>; decreaseAllowance: TypedFunctionDescription<{ encode([spender, subtractedValue]: [string, BigNumberish]): string; }>; }; events: { Approval: TypedEventDescription<{ encodeTopics([owner, spender, value]: [ string | null, string | null, null, ]): string[]; }>; Transfer: TypedEventDescription<{ encodeTopics([from, to, value]: [ string | null, string | null, null, ]): string[]; }>; }; } export class ERC20 extends Contract { connect(signerOrProvider: Signer | Provider | string): ERC20; attach(addressOrName: string): ERC20; deployed(): Promise<ERC20>; on(event: EventFilter | string, listener: Listener): ERC20; once(event: EventFilter | string, listener: Listener): ERC20; addListener(eventName: EventFilter | string, listener: Listener): ERC20; removeAllListeners(eventName: EventFilter | string): ERC20; removeListener(eventName: any, listener: Listener): ERC20; interface: ERC20Interface; functions: { /** * Returns the name of the token. */ name(overrides?: TransactionOverrides): Promise<string>; /** * Returns the name of the token. */ 'name()'(overrides?: TransactionOverrides): Promise<string>; /** * Returns the symbol of the token, usually a shorter version of the name. */ symbol(overrides?: TransactionOverrides): Promise<string>; /** * Returns the symbol of the token, usually a shorter version of the name. */ 'symbol()'(overrides?: TransactionOverrides): Promise<string>; /** * Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` (`505 / 10 ** 2`). Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is called. NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}. */ decimals(overrides?: TransactionOverrides): Promise<number>; /** * Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` (`505 / 10 ** 2`). Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is called. NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}. */ 'decimals()'(overrides?: TransactionOverrides): Promise<number>; /** * See {IERC20-totalSupply}. */ totalSupply(overrides?: TransactionOverrides): Promise<BigNumber>; /** * See {IERC20-totalSupply}. */ 'totalSupply()'(overrides?: TransactionOverrides): Promise<BigNumber>; /** * See {IERC20-balanceOf}. */ balanceOf( account: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * See {IERC20-balanceOf}. */ 'balanceOf(address)'( account: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`. */ transfer( recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`. */ 'transfer(address,uint256)'( recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * See {IERC20-allowance}. */ allowance( owner: string, spender: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * See {IERC20-allowance}. */ 'allowance(address,address)'( owner: string, spender: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * See {IERC20-approve}. Requirements: - `spender` cannot be the zero address. */ approve( spender: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * See {IERC20-approve}. Requirements: - `spender` cannot be the zero address. */ 'approve(address,uint256)'( spender: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}. Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for ``sender``'s tokens of at least `amount`. */ transferFrom( sender: string, recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}. Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for ``sender``'s tokens of at least `amount`. */ 'transferFrom(address,address,uint256)'( sender: string, recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. */ increaseAllowance( spender: string, addedValue: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. */ 'increaseAllowance(address,uint256)'( spender: string, addedValue: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`. */ decreaseAllowance( spender: string, subtractedValue: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`. */ 'decreaseAllowance(address,uint256)'( spender: string, subtractedValue: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; }; /** * Returns the name of the token. */ name(overrides?: TransactionOverrides): Promise<string>; /** * Returns the name of the token. */ 'name()'(overrides?: TransactionOverrides): Promise<string>; /** * Returns the symbol of the token, usually a shorter version of the name. */ symbol(overrides?: TransactionOverrides): Promise<string>; /** * Returns the symbol of the token, usually a shorter version of the name. */ 'symbol()'(overrides?: TransactionOverrides): Promise<string>; /** * Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` (`505 / 10 ** 2`). Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is called. NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}. */ decimals(overrides?: TransactionOverrides): Promise<number>; /** * Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` (`505 / 10 ** 2`). Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is called. NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}. */ 'decimals()'(overrides?: TransactionOverrides): Promise<number>; /** * See {IERC20-totalSupply}. */ totalSupply(overrides?: TransactionOverrides): Promise<BigNumber>; /** * See {IERC20-totalSupply}. */ 'totalSupply()'(overrides?: TransactionOverrides): Promise<BigNumber>; /** * See {IERC20-balanceOf}. */ balanceOf( account: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * See {IERC20-balanceOf}. */ 'balanceOf(address)'( account: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`. */ transfer( recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`. */ 'transfer(address,uint256)'( recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * See {IERC20-allowance}. */ allowance( owner: string, spender: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * See {IERC20-allowance}. */ 'allowance(address,address)'( owner: string, spender: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * See {IERC20-approve}. Requirements: - `spender` cannot be the zero address. */ approve( spender: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * See {IERC20-approve}. Requirements: - `spender` cannot be the zero address. */ 'approve(address,uint256)'( spender: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}. Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for ``sender``'s tokens of at least `amount`. */ transferFrom( sender: string, recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}. Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for ``sender``'s tokens of at least `amount`. */ 'transferFrom(address,address,uint256)'( sender: string, recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. */ increaseAllowance( spender: string, addedValue: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. */ 'increaseAllowance(address,uint256)'( spender: string, addedValue: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`. */ decreaseAllowance( spender: string, subtractedValue: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; /** * Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`. */ 'decreaseAllowance(address,uint256)'( spender: string, subtractedValue: BigNumberish, overrides?: TransactionOverrides, ): Promise<ContractTransaction>; filters: { Approval( owner: string | null, spender: string | null, value: null, ): EventFilter; Transfer(from: string | null, to: string | null, value: null): EventFilter; }; estimate: { /** * Returns the name of the token. */ name(overrides?: TransactionOverrides): Promise<BigNumber>; /** * Returns the name of the token. */ 'name()'(overrides?: TransactionOverrides): Promise<BigNumber>; /** * Returns the symbol of the token, usually a shorter version of the name. */ symbol(overrides?: TransactionOverrides): Promise<BigNumber>; /** * Returns the symbol of the token, usually a shorter version of the name. */ 'symbol()'(overrides?: TransactionOverrides): Promise<BigNumber>; /** * Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` (`505 / 10 ** 2`). Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is called. NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}. */ decimals(overrides?: TransactionOverrides): Promise<BigNumber>; /** * Returns the number of decimals used to get its user representation. For example, if `decimals` equals `2`, a balance of `505` tokens should be displayed to a user as `5,05` (`505 / 10 ** 2`). Tokens usually opt for a value of 18, imitating the relationship between Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is called. NOTE: This information is only used for _display_ purposes: it in no way affects any of the arithmetic of the contract, including {IERC20-balanceOf} and {IERC20-transfer}. */ 'decimals()'(overrides?: TransactionOverrides): Promise<BigNumber>; /** * See {IERC20-totalSupply}. */ totalSupply(overrides?: TransactionOverrides): Promise<BigNumber>; /** * See {IERC20-totalSupply}. */ 'totalSupply()'(overrides?: TransactionOverrides): Promise<BigNumber>; /** * See {IERC20-balanceOf}. */ balanceOf( account: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * See {IERC20-balanceOf}. */ 'balanceOf(address)'( account: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`. */ transfer( recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * See {IERC20-transfer}. Requirements: - `recipient` cannot be the zero address. - the caller must have a balance of at least `amount`. */ 'transfer(address,uint256)'( recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * See {IERC20-allowance}. */ allowance( owner: string, spender: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * See {IERC20-allowance}. */ 'allowance(address,address)'( owner: string, spender: string, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * See {IERC20-approve}. Requirements: - `spender` cannot be the zero address. */ approve( spender: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * See {IERC20-approve}. Requirements: - `spender` cannot be the zero address. */ 'approve(address,uint256)'( spender: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}. Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for ``sender``'s tokens of at least `amount`. */ transferFrom( sender: string, recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * See {IERC20-transferFrom}. Emits an {Approval} event indicating the updated allowance. This is not required by the EIP. See the note at the beginning of {ERC20}. Requirements: - `sender` and `recipient` cannot be the zero address. - `sender` must have a balance of at least `amount`. - the caller must have allowance for ``sender``'s tokens of at least `amount`. */ 'transferFrom(address,address,uint256)'( sender: string, recipient: string, amount: BigNumberish, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. */ increaseAllowance( spender: string, addedValue: BigNumberish, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Atomically increases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. */ 'increaseAllowance(address,uint256)'( spender: string, addedValue: BigNumberish, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`. */ decreaseAllowance( spender: string, subtractedValue: BigNumberish, overrides?: TransactionOverrides, ): Promise<BigNumber>; /** * Atomically decreases the allowance granted to `spender` by the caller. This is an alternative to {approve} that can be used as a mitigation for problems described in {IERC20-approve}. Emits an {Approval} event indicating the updated allowance. Requirements: - `spender` cannot be the zero address. - `spender` must have allowance for the caller of at least `subtractedValue`. */ 'decreaseAllowance(address,uint256)'( spender: string, subtractedValue: BigNumberish, overrides?: TransactionOverrides, ): Promise<BigNumber>; }; }
the_stack
import {HttpClient, HttpParams} from "@angular/common/http"; import {Component, EventEmitter, Inject, Input, OnDestroy, OnInit, Output} from "@angular/core"; import {FormArray, FormControl, FormGroup,Validators} from "@angular/forms"; import {TdDialogService} from "@covalent/core/dialogs"; import {StateService} from "@uirouter/angular"; import {Subscription} from "rxjs/Subscription"; import * as _ from "underscore"; import {ProcessorRef} from "../../../../../../lib/feed/processor/processor-ref"; import {Step} from "../../../../model/feed/feed-step.model"; import {Feed} from "../../../../model/feed/feed.model"; import {FeedDetailsProcessorRenderingHelper} from "../../../../services/FeedDetailsProcessorRenderingHelper"; import {RegisterTemplatePropertyService} from "../../../../services/RegisterTemplatePropertyService"; import {RestUrlConstants} from "../../../../services/RestUrlConstants"; import {Templates} from "../../../../../../lib/feed-mgr/services/TemplateTypes"; import {DefineFeedService} from "../../services/define-feed.service"; import {FeedLoadingService} from "../../services/feed-loading-service"; import {FeedNifiPropertiesService} from "../../services/feed-nifi-properties.service"; import {FeedSideNavService} from "../../services/feed-side-nav.service"; export enum FeedDetailsMode { INPUT = "INPUT", ADDITIONAL = "ADDITIONAL", ALL = "ALL" } export class NiFiPropertiesProcessorsChangeEvent { constructor(public mode: FeedDetailsMode, public feed: Feed, public inputProcessors: ProcessorRef[], public nonInputProcessors: ProcessorRef[], public noPropertiesExist: boolean) { } } @Component({ selector: "feed-nifi-properties", styleUrls: ["./feed-nifi-properties.component.css"], templateUrl: "./feed-nifi-properties.component.html" }) export class FeedNifiPropertiesComponent implements OnInit, OnDestroy { @Input() step: Step; @Input() feed: Feed; @Input() mode?: FeedDetailsMode @Output() updatedFormControls = new EventEmitter<any>(); @Output() processorsChange = new EventEmitter<NiFiPropertiesProcessorsChangeEvent>() @Output() inputProcessorChanged = new EventEmitter<ProcessorRef>() @Input() formGroup: FormGroup; public noPropertiesExist: boolean = false; form = new FormArray([]); formSubscription: Subscription; inputProcessor: ProcessorRef; inputProcessorControl = new FormControl('',[Validators.required]); inputProcessorSubscription: Subscription; /** * processors modified for display */ inputProcessors: ProcessorRef[]; nonInputProcessors: ProcessorRef[]; constructor(private defineFeedService: DefineFeedService, stateService: StateService, private feedNifiPropertiesService: FeedNifiPropertiesService, private http: HttpClient, feedLoadingService: FeedLoadingService, dialogService: TdDialogService, feedSideNavService: FeedSideNavService, @Inject("RegisterTemplatePropertyService") private registerTemplatePropertyService: RegisterTemplatePropertyService) { this.formSubscription = this.form.statusChanges.subscribe(status => { if (status === "VALID" && this.form.dirty) { this.step.markDirty(); } }); this.inputProcessorSubscription = this.inputProcessorControl.valueChanges.subscribe((value: ProcessorRef) => { this.inputProcessor = value; this.form.setControl(0, (value != null) ? value.form : new FormControl()); this.updateProcessors(); this.inputProcessorChanged.emit(value) }); } ngOnDestroy() { if (this.formSubscription) { this.formSubscription.unsubscribe(); } if (this.inputProcessorSubscription) { this.inputProcessorSubscription.unsubscribe(); } } ngOnInit() { if(this.formGroup) { this.formGroup.addControl("processors", this.form); } //touch the input control to show validation error this.inputProcessorControl.markAsTouched() if (this.mode == undefined) { this.mode = FeedDetailsMode.ALL; } this.inputProcessors = []; if (this.feed.isNew()) { this.initializeTemplateProperties(); } else { this.mergeTemplateDataWithFeed(this.feed); } } hasProcessor(downstreamProcessors: any[], processorId: string, processorName: string): boolean { if (downstreamProcessors) { return downstreamProcessors.find(p => p.name == processorName) != undefined; } return false; } applyUpdatesToFeed(): void { let properties = []; let inputProperties: any = []; //Templates.Property[] let otherProperties: any = []; //Templates.Property[] if (this.mode == FeedDetailsMode.ALL || this.mode == FeedDetailsMode.INPUT) { inputProperties = this.inputProcessor.processor.properties; this.feed.inputProcessor = this.inputProcessor.processor as any; this.feed.inputProcessorName = this.inputProcessor.name; this.feed.inputProcessorType = this.inputProcessor.type; } else { this.ensureFeedInputProcessor(); inputProperties = this.feed.inputProcessor.properties } if (this.mode == FeedDetailsMode.ALL || this.mode == FeedDetailsMode.ADDITIONAL) { otherProperties = _.chain(this.nonInputProcessors) .map(ref => ref.processor.properties as any[]) .flatten(true) .value(); } else { otherProperties = _.chain(this.feed.nonInputProcessors) .map(processor => processor.properties as any[]) .flatten(true) .value(); } this.feed.properties = <Templates.Property[]>inputProperties.concat(otherProperties) } private buildInputProcessorRelationships(registeredTemplate: any) { if (registeredTemplate.inputProcessorRelationships) { } } private initializeTemplateProperties() { if (!this.feed.propertiesInitialized && this.feed.templateId != null && this.feed.templateId != '') { let params = new HttpParams().append("feedEdit", "true").append("allProperties", "true"); this.http.get(this.registerTemplatePropertyService.GET_REGISTERED_TEMPLATES_URL + "/" + this.feed.templateId, {params: params}) .subscribe((template: any) => { if (typeof this.feed.cloned !== "undefined" && this.feed.cloned == true) { this.registerTemplatePropertyService.setProcessorRenderTemplateUrl(this.feed, 'create'); this.feedNifiPropertiesService.sortAndSetupFeedProperties(this.feed); } else { this.feedNifiPropertiesService.setupFeedProperties(this.feed, template, 'create'); this.buildInputProcessorRelationships(template); this.setProcessors(this.feed.inputProcessors, this.feed.nonInputProcessors, this.feed.inputProcessor, this.feed); this.feed.propertiesInitialized = true; } }, () => { }); } else if (this.feed.propertiesInitialized) { this.buildInputProcessorRelationships(this.feed.registeredTemplate) this.setProcessors(this.feed.inputProcessors, this.feed.nonInputProcessors, this.feed.inputProcessor, this.feed); } } public mergeTemplateDataWithFeed(feed: Feed) { if (!feed.propertiesInitialized) { let feedCopy = feed.copy(false); delete feedCopy.steps; this.http.post<Feed>(RestUrlConstants.MERGE_FEED_WITH_TEMPLATE(feed.id), feedCopy, {headers: {'Content-Type': 'application/json; charset=UTF-8'}}) .subscribe(updatedFeedResponse => { if (updatedFeedResponse == undefined) { //ERROR out //@TODO present error or return observable.error() console.log("Failed to merge template with undefined"); feed.propertiesInitialized = true; } else { //merge the properties back into this feed feed.properties = updatedFeedResponse.properties; feed.registeredTemplate = updatedFeedResponse.registeredTemplate; this.feedNifiPropertiesService.setupFeedProperties(feed, feed.registeredTemplate, 'edit',); feed.propertiesInitialized = true; this.buildInputProcessorRelationships(feed.registeredTemplate) this.setProcessors(feed.inputProcessors, feed.nonInputProcessors, feed.inputProcessor, feed); //@TODO add in access control /* var entityAccessControlled = accessControlService.isEntityAccessControlled(); //Apply the entity access permissions var requests = { entityEditAccess: !entityAccessControlled || FeedService.hasEntityAccess(EntityAccessControlService.ENTITY_ACCESS.FEED.EDIT_FEED_DETAILS, self.model), entityExportAccess: !entityAccessControlled || FeedService.hasEntityAccess(EntityAccessControlService.ENTITY_ACCESS.FEED.EXPORT, self.model), entityStartAccess: !entityAccessControlled || FeedService.hasEntityAccess(EntityAccessControlService.ENTITY_ACCESS.FEED.START, self.model), entityPermissionAccess: !entityAccessControlled || FeedService.hasEntityAccess(EntityAccessControlService.ENTITY_ACCESS.FEED.CHANGE_FEED_PERMISSIONS, self.model), functionalAccess: accessControlService.getUserAllowedActions() }; $q.all(requests).then(function (response:any) { var allowEditAccess = accessControlService.hasAction(AccessControlService.FEEDS_EDIT, response.functionalAccess.actions); var allowAdminAccess = accessControlService.hasAction(AccessControlService.FEEDS_ADMIN, response.functionalAccess.actions); var slaAccess = accessControlService.hasAction(AccessControlService.SLA_ACCESS, response.functionalAccess.actions); var allowExport = accessControlService.hasAction(AccessControlService.FEEDS_EXPORT, response.functionalAccess.actions); var allowStart = accessControlService.hasAction(AccessControlService.FEEDS_EDIT, response.functionalAccess.actions); self.allowEdit = response.entityEditAccess && allowEditAccess; self.allowChangePermissions = entityAccessControlled && response.entityPermissionAccess && allowEditAccess; self.allowAdmin = allowAdminAccess; self.allowSlaAccess = slaAccess; self.allowExport = response.entityExportAccess && allowExport; self.allowStart = response.entityStartAccess && allowStart; }); */ } }, err => { console.log("Failed to merge template", err); feed.propertiesInitialized = true; }) } else { // this.defineFeedService.setupFeedProperties(this.feed,this.feed.registeredTemplate, 'edit') this.buildInputProcessorRelationships(this.feed.registeredTemplate) this.setProcessors(feed.inputProcessors, feed.nonInputProcessors, feed.inputProcessor, feed); } } private getInputRenderProcessors(inputProcessor: Templates.Processor): Templates.Processor[] { const renderingHelper = new FeedDetailsProcessorRenderingHelper(); if (renderingHelper.isRenderProcessorGetTableDataProcessor(inputProcessor) || renderingHelper.isRenderSqoopProcessor(inputProcessor)) { const inputProcessorRelationships = (typeof this.feed.registeredTemplate.inputProcessorRelationships[inputProcessor.name] !== "undefined") ? this.feed.registeredTemplate.inputProcessorRelationships[inputProcessor.name] : null; return this.feed.nonInputProcessors .filter(processor => processor.id.substring(0, 18) === inputProcessorRelationships[0].id.substring(0, 18)) .filter(processor => renderingHelper.isGetTableDataProcessor(processor) || renderingHelper.isSqoopProcessor(processor)); } else { return []; } } private updateProcessors() { if(this.inputProcessor) { this.nonInputProcessors = this.getInputRenderProcessors(this.inputProcessor.processor as any) .map(processor => { const ref = new ProcessorRef(processor as any, this.feed); this.form.push(ref.form); return ref; }); let hasVisibleProcessors = _.chain([...this.inputProcessors, ...this.nonInputProcessors]) .map(ref => ref.processor.properties) .flatten(true) .find((property: Templates.Property) => property.userEditable) .value() != null; if (!hasVisibleProcessors) { this.noPropertiesExist = true; } this.updatedFormControls.emit(); this.processorsChange.emit(new NiFiPropertiesProcessorsChangeEvent(this.mode, this.feed, this.inputProcessors, this.nonInputProcessors, this.noPropertiesExist)); } } private ensureFeedInputProcessor(){ if(this.feed.inputProcessor == undefined && this.feed.registeredTemplate) { //attempt to get the first one //get the first input processor and select it let inputProcessors = this.feed.inputProcessors && this.feed.inputProcessors.length >0 ? this.feed.inputProcessors : this.feed.registeredTemplate && this.feed.registeredTemplate.inputProcessors && this.feed.registeredTemplate.inputProcessors.length >0 ? this.feed.registeredTemplate.inputProcessors : [] if(inputProcessors.length >0) { let input: Templates.Processor = inputProcessors[0]; this.feed.inputProcessor = input; this.feed.inputProcessorName = input.name; this.feed.inputProcessorType = input.type; } } } private setProcessors(inputProcessors: Templates.Processor[], nonInputProcessors: Templates.Processor[], selected?: Templates.Processor, feed?: Feed) { let hasVisibleProcessors = false; let selectedProcessorRef: ProcessorRef = null; if (this.isShowInputProperties()) { //set the value after inputProcessors is defined so the valuechanges callback is called after this.inputProcessors is initialized this.inputProcessors = inputProcessors.map(processor => { const ref = new ProcessorRef(processor as any, feed); if (selected && ref.id === selected.id) { selectedProcessorRef = ref; } return ref; }); hasVisibleProcessors = this.inputProcessors .find((ref: ProcessorRef) => ref.processor.properties && ref.processor.properties.find((property: Templates.Property) => property.userEditable) != undefined) != undefined; } if (this.isShowAdditionalProperties()) { this.ensureFeedInputProcessor() let inputName = this.feed.inputProcessor != undefined ? this.feed.inputProcessor.name : undefined; let inputProcessorRelationships = this.feed.registeredTemplate.inputProcessorRelationships; let downstreamProcessors = inputProcessorRelationships != undefined ? inputProcessorRelationships[inputName] : undefined; const inputRenderProcessors = selected ? this.getInputRenderProcessors(selected) : null; //limit the downstream additional processors to only those that are available in the flow coming from the input processor this.nonInputProcessors = nonInputProcessors .filter(processor => inputRenderProcessors.find(x => x.id === processor.id) == null) .filter(processor => downstreamProcessors != undefined ? this.hasProcessor(downstreamProcessors, processor.id, processor.name) : true) .map(processor => { const ref = new ProcessorRef(processor as any, feed); this.form.push(ref.form); return ref; }); if (!hasVisibleProcessors) { hasVisibleProcessors = this.nonInputProcessors.find((ref: ProcessorRef) => ref.processor.properties && ref.processor.properties.find((property: Templates.Property) => property.userEditable) != undefined) != undefined; } } if (selectedProcessorRef != null) { this.inputProcessorControl.setValue(selectedProcessorRef); this.form.setControl(0, selectedProcessorRef.form); } if (!hasVisibleProcessors) { this.noPropertiesExist = true; } this.updatedFormControls.emit(); this.processorsChange.emit(new NiFiPropertiesProcessorsChangeEvent(this.mode, this.feed, this.inputProcessors, this.nonInputProcessors, this.noPropertiesExist)); } private isShowInputProperties() { return (this.mode == FeedDetailsMode.ALL || this.mode == FeedDetailsMode.INPUT); } private isShowAdditionalProperties() { return (this.mode == FeedDetailsMode.ALL || this.mode == FeedDetailsMode.ADDITIONAL); } }
the_stack
import assertValidProps from "../shared/assertValidProps"; import { Type, Instance, Container, HostContext } from "../shared/HostConfigTypes"; import { TextBase } from "@nativescript/core"; import { setValueForStyles, StyleUpdates } from "../shared/CSSPropertyOperations"; import { setValueForProperty } from "./NativeScriptPropertyOperations"; import * as console from "../shared/Logger"; import { rnsDeletedPropValue } from "./magicValues"; import type { NativeScriptAttributes } from "../shared/NativeScriptJSXTypings"; const DANGEROUSLY_SET_INNER_HTML = "dangerouslySetInnerHTML"; const SUPPRESS_CONTENT_EDITABLE_WARNING = "suppressContentEditableWarning"; const SUPPRESS_HYDRATION_WARNING = "suppressHydrationWarning"; const AUTOFOCUS = "autoFocus"; const CHILDREN = "children"; const TEXT = "text"; const STYLE = "style"; const HTML = "__html"; // const TEXT_NODE: string = ''; function setTextContent(node: Instance, text: string): void { /* No concept of text nodes in NativeScript as far as I know... */ // if (text) { // let firstChild; // let i: number = 0; // node.eachChild((child: ViewBase) => { // if(i === 0){ // firstChild = child; // } else if(i > 0){ // return false; // } // i++; // return true; // }); // const isLastChild: boolean = firstChild && i === 1; // if ( // firstChild && // isLastChild && // // firstChild.nodeType === TEXT_NODE // typeof firstChild === "string" || typeof firstChild === "number" // ) { // const oldText: string = firstChild.text; // firstChild.text = text; // firstChild.notifyPropertyChange("text", text, oldText); // return; // } // } node.text = text; } export function setInitialProperties( domElement: Instance, tag: Type, rawProps: Object, rootContainerElement: Container, hostContext: HostContext ): void { // const isCustomComponentTag = isCustomComponent(tag, rawProps); // if ((global as any).__DEV__) { // validatePropertiesInDevelopment(tag, rawProps); // if ( // isCustomComponentTag && // !didWarnShadyDOM && // (domElement: any).shadyRoot // ) { // warning( // false, // '%s is using shady DOM. Using shady DOM with React can ' + // 'cause things to break subtly.', // getCurrentFiberOwnerNameInDevOrNull() || 'A component', // ); // didWarnShadyDOM = true; // } // } // TODO: Make sure that we check isMounted before firing any of these events. // let props: Object; // switch (tag) { // case 'iframe': // case 'object': // trapBubbledEvent(TOP_LOAD, domElement); // props = rawProps; // break; // case 'video': // case 'audio': // // Create listener for each media event // for (let i = 0; i < mediaEventTypes.length; i++) { // trapBubbledEvent(mediaEventTypes[i], domElement); // } // props = rawProps; // break; // case 'source': // trapBubbledEvent(TOP_ERROR, domElement); // props = rawProps; // break; // case 'img': // case 'image': // case 'link': // trapBubbledEvent(TOP_ERROR, domElement); // trapBubbledEvent(TOP_LOAD, domElement); // props = rawProps; // break; // case 'form': // trapBubbledEvent(TOP_RESET, domElement); // trapBubbledEvent(TOP_SUBMIT, domElement); // props = rawProps; // break; // case 'details': // trapBubbledEvent(TOP_TOGGLE, domElement); // props = rawProps; // break; // case 'input': // ReactDOMInputInitWrapperState(domElement, rawProps); // props = ReactDOMInputGetHostProps(domElement, rawProps); // trapBubbledEvent(TOP_INVALID, domElement); // // For controlled components we always need to ensure we're listening // // to onChange. Even if there is no listener. // ensureListeningTo(rootContainerElement, 'onChange'); // break; // case 'option': // ReactDOMOptionValidateProps(domElement, rawProps); // props = ReactDOMOptionGetHostProps(domElement, rawProps); // break; // case 'select': // ReactDOMSelectInitWrapperState(domElement, rawProps); // props = ReactDOMSelectGetHostProps(domElement, rawProps); // trapBubbledEvent(TOP_INVALID, domElement); // // For controlled components we always need to ensure we're listening // // to onChange. Even if there is no listener. // ensureListeningTo(rootContainerElement, 'onChange'); // break; // case 'textarea': // ReactDOMTextareaInitWrapperState(domElement, rawProps); // props = ReactDOMTextareaGetHostProps(domElement, rawProps); // trapBubbledEvent(TOP_INVALID, domElement); // // For controlled components we always need to ensure we're listening // // to onChange. Even if there is no listener. // ensureListeningTo(rootContainerElement, 'onChange'); // break; // default: // props = rawProps; // } const props = rawProps; assertValidProps(tag, props); setInitialDOMProperties(tag, domElement, rootContainerElement, props, false, hostContext); // switch (tag) { // case 'input': // // TODO: Make sure we check if this is still unmounted or do any clean // // up necessary since we never stop tracking anymore. // track((domElement: any)); // ReactDOMInputPostMountWrapper(domElement, rawProps, false); // break; // case 'textarea': // // TODO: Make sure we check if this is still unmounted or do any clean // // up necessary since we never stop tracking anymore. // track((domElement: any)); // ReactDOMTextareaPostMountWrapper(domElement, rawProps); // break; // case 'option': // ReactDOMOptionPostMountWrapper(domElement, rawProps); // break; // case 'select': // ReactDOMSelectPostMountWrapper(domElement, rawProps); // break; // default: // if (typeof props.onClick === 'function') { // // TODO: This cast may not be sound for SVG, MathML or custom elements. // trapClickOnNonInteractiveElement(((domElement: any): HTMLElement)); // } // break; // } } export function setInitialDOMProperties( tag: Type, domElement: Instance, rootContainerElement: Container, nextProps: Object, isCustomComponentTag: boolean, hostContext: HostContext ): void { // console.log(`[setInitialDOMProperties] for: ${domElement}`); for (const propKey in nextProps) { if (!nextProps.hasOwnProperty(propKey)) { continue; } const nextProp = nextProps[propKey]; if (propKey === STYLE) { if ((global as any).__DEV__) { if (nextProp) { // Freeze the next style object so that we can assume it won't be // mutated. We have already warned for this in the past. Object.freeze(nextProp); } } // Relies on `updateStylesByID` not mutating `styleUpdates`. setValueForStyles(domElement, nextProp as StyleUpdates); // } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { // const nextHtml = nextProp ? nextProp[HTML] : undefined; // if (nextHtml != null) { // setInnerHTML(domElement, nextHtml); // } } else if (propKey === CHILDREN) { if (typeof nextProp === "string") { // Avoid setting initial textContent when the text is empty. In IE11 setting // textContent on a <textarea> will cause the placeholder to not // show within the <textarea> until it has been focused and blurred again. // https://github.com/facebook/react/issues/6731#issuecomment-254874553 const canSetTextContent = tag !== "textarea" || nextProp !== ""; if (canSetTextContent) { setTextContent(domElement, nextProp); } } else if (typeof nextProp === "number") { setTextContent(domElement, "" + nextProp); } } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) { // Noop } else if (propKey === AUTOFOCUS) { // We polyfill it separately on the client during commit. // We could have excluded it in the property list instead of // adding a special case here, but then it wouldn't be emitted // on server rendering (but we *do* want to emit it in SSR). // } else if (registrationNameModules.hasOwnProperty(propKey)) { // if (nextProp != null) { // if (__DEV__ && typeof nextProp !== 'function') { // warnForInvalidEventListener(propKey, nextProp); // } // ensureListeningTo(rootContainerElement, propKey); // } // TODO: check whether this condition, which makes sense for DOM, makes sense for NativeScript. } else if (nextProp != null) { setValueForProperty(domElement, propKey, nextProp, isCustomComponentTag, hostContext); } } } export function updateDOMProperties( instance: Instance, updatePayload: Array<any>, wasCustomComponentTag: boolean, isCustomComponentTag: boolean, hostContext: HostContext ): void { // console.log(`[updateDOMProperties] for: ${instance}`); // TODO: Handle wasCustomComponentTag for (let i = 0; i < updatePayload.length; i += 2) { const propKey = updatePayload[i]; const propValue = updatePayload[i + 1]; if (propKey === STYLE) { if(propValue !== null){ /* * When a React element updates from having no style prop at all to having one, the Host Config's commitUpdate() * the diffProperties() update payload will consist of e.g. ["style", null, "style", { color: "red" }]. * As far as I can tell, we can just no-op for the ["style", null] update. Alternatively, we could pass in an * empty object, but it'd be a little less efficient. So instead, I just skip the null case via the above * conditional check. */ console.log(`[updateDOMProperties] ${instance}.style`, propValue); setValueForStyles(instance, propValue as StyleUpdates); } // } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { // setInnerHTML(instance, propValue); } else if (propKey === CHILDREN) { /* The fact that React DOM don't handle child nesting here suggests that * it has already been filtered out beforehand, and children can only be * text content by this point. */ setTextContent(instance, propValue); } else if (propKey === TEXT && instance instanceof TextBase) { setTextContent(instance, propValue); } else { // console.log(`[updateDOMProperties] calling setValueForProperty on ${instance} for propKey: ${propKey}; value:`, propValue); setValueForProperty(instance, propKey, propValue, isCustomComponentTag, hostContext); } } } export function diffProperties( domElement: Instance, tag: Type, lastRawProps: object, nextRawProps: object, rootContainerElement: Container ): null | Array<any> { // if(__DEV__){ // validatePropertiesInDevelopment(tag, nextRawProps); // } let updatePayload: null | Array<any> = null; let lastProps: object = lastRawProps; let nextProps: object = nextRawProps; // switch(tag){ // case 'input': // lastProps = ReactDOMInputGetHostProps(domElement, lastRawProps); // nextProps = ReactDOMInputGetHostProps(domElement, nextRawProps); // updatePayload = []; // break; // case 'option': // lastProps = ReactDOMOptionGetHostProps(domElement, lastRawProps); // nextProps = ReactDOMOptionGetHostProps(domElement, nextRawProps); // updatePayload = []; // break; // case 'select': // lastProps = ReactDOMSelectGetHostProps(domElement, lastRawProps); // nextProps = ReactDOMSelectGetHostProps(domElement, nextRawProps); // updatePayload = []; // break; // case 'textarea': // lastProps = ReactDOMTextareaGetHostProps(domElement, lastRawProps); // nextProps = ReactDOMTextareaGetHostProps(domElement, nextRawProps); // updatePayload = []; // break; // default: // lastProps = lastRawProps; // nextProps = nextRawProps; // if ( // typeof lastProps.onClick !== 'function' && // typeof nextProps.onClick === 'function' // ) { // // TODO: This cast may not be sound for SVG, MathML or custom elements. // trapClickOnNonInteractiveElement(((domElement: any): HTMLElement)); // } // break; // } if (typeof tag === "string") { assertValidProps(tag, nextProps); } else { console.warn( `TODO: determine whether a custom component may pass through client/ReactNativeScriptComponent.diffProperties()` ); } let propKey: string; let styleName: string; let styleUpdates: StyleUpdates|null = null; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) { // console.log(`[diffProperties] skipping on lastProps key:`, propKey); continue; } if (propKey === STYLE) { const lastStyle: NativeScriptAttributes["style"] = lastProps[propKey]; if(lastStyle){ for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { if (!styleUpdates) { styleUpdates = {}; } console.log(`[diffProperties.lastProps] style.${styleName} found in last update's style object.`); styleUpdates[styleName] = rnsDeletedPropValue; // Will be deleted by default, unless updated. } } } } else if (propKey === DANGEROUSLY_SET_INNER_HTML || propKey === CHILDREN) { // Noop. This is handled by the clear text mechanism. console.warn(`[diffProperties] propKey === CHILDREN; Noop. This is handled by the clear text mechanism.`); } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) { // Noop } else if (propKey === AUTOFOCUS) { // Noop. It doesn't work on updates anyway. // } else if (registrationNameModules.hasOwnProperty(propKey)) { // // This is a special case. If any listener updates we need to ensure // // that the "current" fiber pointer gets updated so we need a commit // // to update this element. // if (!updatePayload) { // updatePayload = []; // } } else { console.log(`[diffProperties] INSPECTING OLDPROPS key:`, propKey); // For all other deleted properties we add it to the queue. We use // the whitelist in the commit phase instead. // (updatePayload = updatePayload || []).push(propKey, rnsDeletedPropValue); } } // console.log(`[diffProperties] updatePayload as of lastProp`, updatePayload); for (propKey in nextProps) { const nextProp = nextProps[propKey]; const lastProp = lastProps != null ? lastProps[propKey] : undefined; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || (nextProp == null && lastProp == null)) { // console.log(`[diffProperties] skipping on nextProps key:`, propKey); continue; } if (propKey === STYLE) { if ((global as any).__DEV__) { if (nextProp) { // Freeze the next style object so that we can assume it won't be // mutated. We have already warned for this in the past. Object.freeze(nextProp); } } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { if (!styleUpdates) { styleUpdates = {}; } console.log(`[diffProperties.nextProps] style.${styleName} deleted!`); styleUpdates[styleName] = rnsDeletedPropValue; } } // Update styles that changed since `lastProp`. for (styleName in nextProp) { if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { if (!styleUpdates) { styleUpdates = {}; } styleUpdates[styleName] = nextProp[styleName]; } } } else { // Relies on `updateStylesByID` not mutating `styleUpdates`. if (!styleUpdates) { if (!updatePayload) { updatePayload = []; } // This is where we get the update ["style", null] from. updatePayload.push(STYLE, styleUpdates); } styleUpdates = nextProp; } // } else if (propKey === DANGEROUSLY_SET_INNER_HTML) { // const nextHtml = nextProp ? nextProp[HTML] : undefined; // const lastHtml = lastProp ? lastProp[HTML] : undefined; // if (nextHtml != null) { // if (lastHtml !== nextHtml) { // (updatePayload = updatePayload || []).push(propKey, '' + nextHtml); // } // } else { // // TODO: It might be too late to clear this if we have children // // inserted already. // } } else if (propKey === CHILDREN) { // console.log(`[diffProperties] got propKey === CHILDREN.`); // console.log(`[diffProperties] lastProp`, lastProp); // console.log(`[diffProperties] nextProp`, nextProp); if (lastProp !== nextProp && (typeof nextProp === "string" || typeof nextProp === "number")) { (updatePayload = updatePayload || []).push(propKey, "" + nextProp); } else { // console.log(`[diffProperties] not pushing for propKey === CHILDREN.`); } } else if (propKey === SUPPRESS_CONTENT_EDITABLE_WARNING || propKey === SUPPRESS_HYDRATION_WARNING) { // Noop // } else if (registrationNameModules.hasOwnProperty(propKey)) { // if (nextProp != null) { // // We eagerly listen to this even though we haven't committed yet. // if (__DEV__ && typeof nextProp !== 'function') { // warnForInvalidEventListener(propKey, nextProp); // } // ensureListeningTo(rootContainerElement, propKey); // } // if (!updatePayload && lastProp !== nextProp) { // // This is a special case. If any listener updates we need to ensure // // that the "current" props pointer gets updated so we need a commit // // to update this element. // updatePayload = []; // } } else { // console.log(`[diffProperties] INSPECTING NEWPROPS key and nextProp`, propKey, nextProp); // For any other property we always add it to the queue and then we // filter it out using the whitelist during the commit. (updatePayload = updatePayload || []).push(propKey, nextProp); } } if (styleUpdates) { // if (__DEV__) { // validateShorthandPropertyCollisionInDev(styleUpdates, nextProps[STYLE]); // } (updatePayload = updatePayload || []).push(STYLE, styleUpdates); } // console.log(`[diffProperties] updatePayload as of nextProp:`, updatePayload); return updatePayload; } export function updateProperties( instance: Instance, updatePayload: Array<any>, type: Type, lastRawProps: any, nextRawProps: any, hostContext: HostContext ): void { // Update checked *before* name. // In the middle of an update, it is possible to have multiple checked. // When a checked radio tries to change name, browser makes another radio's checked false. // if ( // tag === 'input' && // nextRawProps.type === 'radio' && // nextRawProps.name != null // ) { // ReactDOMInputUpdateChecked(instance, nextRawProps); // } /* More relevant to HTML. */ // const wasCustomComponentTag = isCustomComponent(tag, lastRawProps); // const isCustomComponentTag = isCustomComponent(tag, nextRawProps); // Apply the diff. updateDOMProperties(instance, updatePayload, false, false, hostContext); /* TODO: I Won't be implementing these for now. */ // switch (tag) { // case 'input': // // Update the wrapper around inputs *after* updating props. This has to // // happen after `updateDOMProperties`. Otherwise HTML5 input validations // // raise warnings and prevent the new value from being assigned. // ReactDOMInputUpdateWrapper(instance, nextRawProps); // break; // case 'textarea': // ReactDOMTextareaUpdateWrapper(instance, nextRawProps); // break; // case 'select': // // <select> value update needs to occur after <option> children // // reconciliation // ReactDOMSelectPostUpdateWrapper(instance, nextRawProps); // break; // } }
the_stack
import * as sinon from 'sinon'; import { legacyPlugin as pluginApi } from '@snyk/cli-interface'; import { AcceptanceTests } from './cli-test.acceptance.test'; import { CommandResult } from '../../../src/cli/commands/types'; import { createCallGraph } from '../../utils'; import * as fs from 'fs'; import * as path from 'path'; const readJSON = (jsonPath: string) => { return JSON.parse( fs.readFileSync(path.resolve(__dirname, jsonPath), 'utf-8'), ); }; export const GradleTests: AcceptanceTests = { language: 'Gradle', tests: { '`test gradle-kotlin-dsl-app` returns correct meta': ( params, utils, ) => async (t) => { utils.chdirWorkspaces(); const plugin = { async inspect() { return { package: {}, plugin: { name: 'testplugin', runtime: 'testruntime' }, }; }, }; sinon.spy(plugin, 'inspect'); const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); t.teardown(loadPlugin.restore); loadPlugin.withArgs('gradle').returns(plugin); const commandResult: CommandResult = await params.cli.test( 'gradle-kotlin-dsl-app', ); const res: string = commandResult.getDisplayResults(); const meta = res.slice(res.indexOf('Organization:')).split('\n'); t.match(meta[0], /Organization:\s+test-org/, 'organization displayed'); t.match( meta[1], /Package manager:\s+gradle/, 'package manager displayed', ); t.match( meta[2], /Target file:\s+build.gradle.kts/, 'target file displayed', ); t.match(meta[3], /Open source:\s+no/, 'open source displayed'); t.match( meta[4], /Project path:\s+gradle-kotlin-dsl-app/, 'path displayed', ); t.notMatch( meta[5], /Local Snyk policy:\s+found/, 'local policy not displayed', ); }, '`test gradle-app` returns correct meta': (params, utils) => async (t) => { utils.chdirWorkspaces(); const plugin = { async inspect() { return { package: {}, plugin: { name: 'testplugin', runtime: 'testruntime' }, }; }, }; const spyPlugin = sinon.spy(plugin, 'inspect'); const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); t.teardown(loadPlugin.restore); loadPlugin.withArgs('gradle').returns(plugin); const commandResult: CommandResult = await params.cli.test('gradle-app'); const res = commandResult.getDisplayResults(); const meta = res.slice(res.indexOf('Organization:')).split('\n'); t.false( ((spyPlugin.args[0] as any)[2] as any).allSubProjects, '`allSubProjects` option is not sent', ); t.match(meta[0], /Organization:\s+test-org/, 'organization displayed'); t.match( meta[1], /Package manager:\s+gradle/, 'package manager displayed', ); t.match(meta[2], /Target file:\s+build.gradle/, 'target file displayed'); t.match(meta[3], /Open source:\s+no/, 'open source displayed'); t.match(meta[4], /Project path:\s+gradle-app/, 'path displayed'); t.notMatch( meta[5], /Local Snyk policy:\s+found/, 'local policy not displayed', ); }, '`test gradle-app --reachable-vulns` sends call graph': ( params, utils, ) => async (t) => { utils.chdirWorkspaces(); const callGraphPayload = readJSON('../fixtures/call-graphs/maven.json'); const callGraph = createCallGraph(callGraphPayload); const plugin = { async inspect() { return { package: {}, plugin: { name: 'testplugin', runtime: 'testruntime' }, callGraph, }; }, }; const spyPlugin = sinon.spy(plugin, 'inspect'); const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); t.teardown(loadPlugin.restore); loadPlugin.withArgs('gradle').returns(plugin); await params.cli.test('gradle-app', { reachableVulns: true, }); const req = params.server.popRequest(); t.equal(req.method, 'POST', 'makes POST request'); t.equal( req.headers['x-snyk-cli-version'], params.versionNumber, 'sends version number', ); t.match(req.url, '/test-dep-graph', 'posts to correct url'); t.match(req.body.targetFile, undefined, 'target is undefined'); t.equal(req.body.depGraph.pkgManager.name, 'gradle'); t.deepEqual( req.body.callGraph, callGraphPayload, 'correct call graph sent', ); t.same( spyPlugin.getCall(0).args, [ 'gradle-app', 'build.gradle', { args: null, file: 'build.gradle', org: null, projectName: null, packageManager: 'gradle', path: 'gradle-app', showVulnPaths: 'some', reachableVulns: true, }, ], 'calls gradle plugin', ); }, '`test gradle-app --reachable-vulns and --init-script` sends call graph': ( params, utils, ) => async (t) => { utils.chdirWorkspaces(); const callGraphPayload = readJSON('../fixtures/call-graphs/maven.json'); const callGraph = createCallGraph(callGraphPayload); const plugin = { async inspect() { return { package: {}, plugin: { name: 'testplugin', runtime: 'testruntime' }, callGraph, }; }, }; const spyPlugin = sinon.spy(plugin, 'inspect'); const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); t.teardown(loadPlugin.restore); loadPlugin.withArgs('gradle').returns(plugin); await params.cli.test('gradle-app', { reachableVulns: true, initScript: 'somescript.gradle', }); const req = params.server.popRequest(); t.equal(req.method, 'POST', 'makes POST request'); t.equal( req.headers['x-snyk-cli-version'], params.versionNumber, 'sends version number', ); t.match(req.url, '/test-dep-graph', 'posts to correct url'); t.match(req.body.targetFile, undefined, 'target is undefined'); t.equal(req.body.depGraph.pkgManager.name, 'gradle'); t.deepEqual( req.body.callGraph, callGraphPayload, 'correct call graph sent', ); t.same( spyPlugin.getCall(0).args, [ 'gradle-app', 'build.gradle', { args: null, file: 'build.gradle', org: null, projectName: null, packageManager: 'gradle', path: 'gradle-app', showVulnPaths: 'some', reachableVulns: true, initScript: 'somescript.gradle', }, ], 'calls gradle plugin', ); }, '`test gradle-app --all-sub-projects` sends `allSubProjects` argument to plugin': ( params, utils, ) => async (t) => { utils.chdirWorkspaces(); const plugin = { async inspect() { return { plugin: { name: 'gradle' }, package: {} }; }, }; const spyPlugin = sinon.spy(plugin, 'inspect'); const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); t.teardown(loadPlugin.restore); loadPlugin.withArgs('gradle').returns(plugin); await params.cli.test('gradle-app', { allSubProjects: true, }); t.true(((spyPlugin.args[0] as any)[2] as any).allSubProjects); }, '`test gradle-app --all-sub-projects` with policy': ( params, utils, ) => async (t) => { utils.chdirWorkspaces(); const plugin = { async inspect() { return { plugin: { name: 'gradle' }, package: {} }; }, }; const spyPlugin = sinon.spy(plugin, 'inspect'); const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); t.teardown(loadPlugin.restore); loadPlugin.withArgs('gradle').returns(plugin); await params.cli.test('gradle-app', { allSubProjects: true, }); t.true(((spyPlugin.args[0] as any)[2] as any).allSubProjects); let policyCount = 0; params.server .getRequests() .filter((r) => r.url === '/api/v1/test-dep-graph?org=') .forEach((req) => { if ( req.body.displayTargetFile.endsWith('gradle-multi-project/subproj') ) { // TODO: this should return 1 policy when fixed // uncomment then // t.match( // req.body.policy, // 'SNYK-JAVA-ORGBOUNCYCASTLE-32364', // 'policy is found & sent', // ); t.ok( req.body.policy, undefined, 'policy is not found even though it should be', ); policyCount += 1; } t.match(req.url, '/test-dep-graph', 'posts to correct url'); }); // TODO: this should return 1 policy when fixed t.equal(policyCount, 0, 'one sub-project policy found & sent'); }, '`test gradle-app` plugin fails to return package or scannedProjects': ( params, utils, ) => async (t) => { utils.chdirWorkspaces(); const plugin = { async inspect() { return { plugin: { name: 'gradle' } }; }, }; sinon.spy(plugin, 'inspect'); const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); t.teardown(loadPlugin.restore); loadPlugin.withArgs('gradle').returns(plugin); try { await params.cli.test('gradle-app', {}); t.fail('expected error'); } catch (error) { t.match( error, /error getting dependencies from gradle plugin: neither 'package' nor 'scannedProjects' were found/, 'error found', ); } }, '`test gradle-app --all-sub-projects` returns correct multi tree meta': ( params, utils, ) => async (t) => { utils.chdirWorkspaces(); const plugin = { async inspect(): Promise<pluginApi.MultiProjectResult> { return { plugin: { meta: { allSubProjectNames: ['a', 'b'], }, name: 'gradle', }, scannedProjects: [ { depTree: { name: 'tree0', version: '1.0.0', dependencies: { dep1: { name: 'dep1', version: '1' } }, }, }, { depTree: { name: 'tree1', version: '2.0.0', dependencies: { dep1: { name: 'dep2', version: '2' } }, }, }, ], }; }, }; const spyPlugin = sinon.spy(plugin, 'inspect'); const loadPlugin = sinon.stub(params.plugins, 'loadPlugin'); t.teardown(loadPlugin.restore); loadPlugin.withArgs('gradle').returns(plugin); const commandResult: CommandResult = await params.cli.test('gradle-app', { allSubProjects: true, }); const res = commandResult.getDisplayResults(); t.true( ((spyPlugin.args[0] as any)[2] as any).allSubProjects, '`allSubProjects` option is sent', ); const tests = res .split('Testing gradle-app...') .filter((s) => !!s.trim()); t.equals(tests.length, 2, 'two projects tested independently'); t.match( res, /Tested 2 projects/, 'number projects tested displayed properly', ); t.notMatch( res, /use --all-sub-projects flag to scan all sub-projects/, 'all-sub-projects flag is NOT suggested as we already scanned with it', ); for (let i = 0; i < tests.length; i++) { const meta = tests[i] .slice(tests[i].indexOf('Organization:')) .split('\n'); t.match(meta[0], /Organization:\s+test-org/, 'organization displayed'); t.match( meta[1], /Package manager:\s+gradle/, 'package manager displayed', ); t.match( meta[2], /Target file:\s+build.gradle/, 'target file displayed', ); t.match(meta[3], /Project name:\s+tree/, 'sub-project displayed'); t.includes(meta[3], `tree${i}`, 'sub-project displayed'); t.match(meta[4], /Open source:\s+no/, 'open source displayed'); t.match(meta[5], /Project path:\s+gradle-app/, 'path displayed'); t.notMatch( meta[6], /Local Snyk policy:\s+found/, 'local policy not displayed', ); } }, }, };
the_stack
import { FbForm, FormBuilderStorageOperationsCreateFormFromParams, FormBuilderStorageOperationsCreateFormParams, FormBuilderStorageOperationsDeleteFormParams, FormBuilderStorageOperationsDeleteFormRevisionParams, FormBuilderStorageOperationsGetFormParams, FormBuilderStorageOperationsListFormRevisionsParams, FormBuilderStorageOperationsListFormRevisionsParamsWhere, FormBuilderStorageOperationsListFormsParams, FormBuilderStorageOperationsListFormsResponse, FormBuilderStorageOperationsPublishFormParams, FormBuilderStorageOperationsUnpublishFormParams, FormBuilderStorageOperationsUpdateFormParams } from "@webiny/api-form-builder/types"; import { Entity, Table } from "dynamodb-toolbox"; import { Client } from "@elastic/elasticsearch"; import { queryAll, QueryAllParams } from "@webiny/db-dynamodb/utils/query"; import WebinyError from "@webiny/error"; import { cleanupItem } from "@webiny/db-dynamodb/utils/cleanup"; import { batchWriteAll } from "@webiny/db-dynamodb/utils/batchWrite"; import { configurations } from "~/configurations"; import { filterItems } from "@webiny/db-dynamodb/utils/filter"; import fields from "./fields"; import { sortItems } from "@webiny/db-dynamodb/utils/sort"; import { parseIdentifier, zeroPad } from "@webiny/utils"; import { createElasticsearchBody, createFormElasticType } from "./elasticsearchBody"; import { decodeCursor, encodeCursor } from "@webiny/api-elasticsearch/cursors"; import { PluginsContainer } from "@webiny/plugins"; import { FormBuilderFormCreateKeyParams, FormBuilderFormStorageOperations } from "~/types"; import { ElasticsearchSearchResponse } from "@webiny/api-elasticsearch/types"; export type DbRecord<T = any> = T & { PK: string; SK: string; TYPE: string; }; export interface CreateFormStorageOperationsParams { entity: Entity<any>; esEntity: Entity<any>; table: Table; elasticsearch: Client; plugins: PluginsContainer; } type FbFormElastic = Omit<FbForm, "triggers" | "fields" | "settings" | "layout" | "stats"> & { __type: string; }; const getESDataForLatestRevision = (form: FbForm): FbFormElastic => ({ __type: createFormElasticType(), id: form.id, createdOn: form.createdOn, savedOn: form.savedOn, name: form.name, slug: form.slug, published: form.published, publishedOn: form.publishedOn, version: form.version, locked: form.locked, status: form.status, createdBy: form.createdBy, ownedBy: form.ownedBy, tenant: form.tenant, locale: form.locale, webinyVersion: form.webinyVersion, formId: form.formId }); export const createFormStorageOperations = ( params: CreateFormStorageOperationsParams ): FormBuilderFormStorageOperations => { const { entity, esEntity, table, plugins, elasticsearch } = params; const formDynamoDbFields = fields(); const createFormPartitionKey = (params: FormBuilderFormCreateKeyParams): string => { const { tenant, locale, id: targetId } = params; const { id } = parseIdentifier(targetId); return `T#${tenant}#L#${locale}#FB#F#${id}`; }; const createRevisionSortKey = (value: string | number | undefined): string => { const version = typeof value === "number" ? Number(value) : (parseIdentifier(value).version as number); return `REV#${zeroPad(version)}`; }; const createLatestSortKey = (): string => { return "L"; }; const createLatestPublishedSortKey = (): string => { return "LP"; }; const createFormType = (): string => { return "fb.form"; }; const createFormLatestType = (): string => { return "fb.form.latest"; }; const createFormLatestPublishedType = (): string => { return "fb.form.latestPublished"; }; const createForm = async ( params: FormBuilderStorageOperationsCreateFormParams ): Promise<FbForm> => { const { form } = params; const revisionKeys = { PK: createFormPartitionKey(form), SK: createRevisionSortKey(form.id) }; const latestKeys = { PK: createFormPartitionKey(form), SK: createLatestSortKey() }; const items = [ entity.putBatch({ ...form, TYPE: createFormType(), ...revisionKeys }), entity.putBatch({ ...form, TYPE: createFormLatestType(), ...latestKeys }) ]; try { await batchWriteAll({ table, items }); } catch (ex) { throw new WebinyError( ex.message || "Could not insert form data into regular table.", ex.code || "CREATE_FORM_ERROR", { revisionKeys, latestKeys, form } ); } try { const { index } = configurations.es({ tenant: form.tenant, locale: form.locale }); await esEntity.put({ index, data: getESDataForLatestRevision(form), TYPE: createFormType(), ...latestKeys }); } catch (ex) { throw new WebinyError( ex.message || "Could not insert form data into Elasticsearch table.", ex.code || "CREATE_FORM_ERROR", { latestKeys, form } ); } return form; }; const createFormFrom = async ( params: FormBuilderStorageOperationsCreateFormFromParams ): Promise<FbForm> => { const { form, original, latest } = params; const revisionKeys = { PK: createFormPartitionKey(form), SK: createRevisionSortKey(form.version) }; const latestKeys = { PK: createFormPartitionKey(form), SK: createLatestSortKey() }; const items = [ entity.putBatch({ ...form, ...revisionKeys, TYPE: createFormType() }), entity.putBatch({ ...form, ...latestKeys, TYPE: createFormLatestType() }) ]; try { await batchWriteAll({ table, items }); } catch (ex) { throw new WebinyError( ex.message || "Could not create form data in the regular table, from existing form.", ex.code || "CREATE_FORM_FROM_ERROR", { revisionKeys, latestKeys, original, form, latest } ); } try { const { index } = configurations.es({ tenant: form.tenant, locale: form.locale }); await esEntity.put({ index, data: getESDataForLatestRevision(form), TYPE: createFormLatestType(), ...latestKeys }); } catch (ex) { throw new WebinyError( ex.message || "Could not create form in the Elasticsearch table, from existing form.", ex.code || "CREATE_FORM_FROM_ERROR", { latestKeys, form, latest, original } ); } return form; }; const updateForm = async ( params: FormBuilderStorageOperationsUpdateFormParams ): Promise<FbForm> => { const { form, original } = params; const revisionKeys = { PK: createFormPartitionKey(form), SK: createRevisionSortKey(form.id) }; const latestKeys = { PK: createFormPartitionKey(form), SK: createLatestSortKey() }; const { formId, tenant, locale } = form; const latestForm = await getForm({ where: { formId, tenant, locale, latest: true } }); const isLatestForm = latestForm ? latestForm.id === form.id : false; const items = [ entity.putBatch({ ...form, TYPE: createFormType(), ...revisionKeys }) ]; if (isLatestForm) { items.push( entity.putBatch({ ...form, TYPE: createFormLatestType(), ...latestKeys }) ); } try { await batchWriteAll({ table, items }); } catch (ex) { throw new WebinyError( ex.message || "Could not update form data in the regular table.", ex.code || "UPDATE_FORM_ERROR", { revisionKeys, latestKeys, original, form, latestForm } ); } /** * No need to go further if its not latest form. */ if (!isLatestForm) { return form; } try { const { index } = configurations.es({ tenant: form.tenant, locale: form.locale }); await esEntity.put({ index, data: getESDataForLatestRevision(form), TYPE: createFormLatestType(), ...latestKeys }); } catch (ex) { throw new WebinyError( ex.message || "Could not update form data in the Elasticsearch table.", ex.code || "UPDATE_FORM_ERROR", { latestKeys, form, latestForm, original } ); } return form; }; const getForm = async ( params: FormBuilderStorageOperationsGetFormParams ): Promise<FbForm | null> => { const { where } = params; const { id, formId, latest, published, version, tenant, locale } = where; if (latest && published) { throw new WebinyError("Cannot have both latest and published params."); } let sortKey: string; if (latest) { sortKey = createLatestSortKey(); } else if (published && !version) { /** * Because of the specifics how DynamoDB works, we must not load the published record if version is sent. */ sortKey = createLatestPublishedSortKey(); } else if (id || version) { sortKey = createRevisionSortKey(version || id); } else { throw new WebinyError( "Missing parameter to create a sort key.", "MISSING_WHERE_PARAMETER", { where } ); } const keys = { PK: createFormPartitionKey({ tenant, locale, id: (formId || id) as string }), SK: sortKey }; try { const result = await entity.get(keys); if (!result || !result.Item) { return null; } return cleanupItem(entity, result.Item); } catch (ex) { throw new WebinyError( ex.message || "Could not get form by keys.", ex.code || "GET_FORM_ERROR", { keys } ); } }; const listForms = async ( params: FormBuilderStorageOperationsListFormsParams ): Promise<FormBuilderStorageOperationsListFormsResponse> => { const { sort, limit, where, after } = params; const body = createElasticsearchBody({ plugins, sort, limit: limit + 1, where, after: decodeCursor(after) as any }); const esConfig = configurations.es({ tenant: where.tenant, locale: where.locale }); const query = { ...esConfig, body }; let response: ElasticsearchSearchResponse<FbForm>; try { response = await elasticsearch.search(query); } catch (ex) { throw new WebinyError( ex.message || "Could list forms.", ex.code || "LIST_FORMS_ERROR", { where, query } ); } const { hits, total } = response.body.hits; const items = hits.map(item => item._source); const hasMoreItems = items.length > limit; if (hasMoreItems) { /** * Remove the last item from results, we don't want to include it. */ items.pop(); } /** * Cursor is the `sort` value of the last item in the array. * https://www.elastic.co/guide/en/elasticsearch/reference/current/paginate-search-results.html#search-after */ const meta = { hasMoreItems, totalCount: total.value, cursor: items.length > 0 ? encodeCursor(hits[items.length - 1].sort) || null : null }; return { items, meta }; }; const listFormRevisions = async ( params: FormBuilderStorageOperationsListFormRevisionsParams ): Promise<FbForm[]> => { const { where: initialWhere, sort } = params; const { id, formId, tenant, locale } = initialWhere; const queryAllParams: QueryAllParams = { entity, partitionKey: createFormPartitionKey({ tenant, locale, id: (id || formId) as string }), options: { beginsWith: "REV#" } }; let items: FbForm[] = []; try { items = await queryAll<FbForm>(queryAllParams); } catch (ex) { throw new WebinyError( ex.message || "Could not query forms by given params.", ex.code || "QUERY_FORMS_ERROR", { partitionKey: queryAllParams.partitionKey, options: queryAllParams.options } ); } const where: Partial<FormBuilderStorageOperationsListFormRevisionsParamsWhere> = { ...initialWhere, id: undefined, formId: undefined }; const filteredItems = filterItems({ plugins, items, where, fields: formDynamoDbFields }); if (!sort || sort.length === 0) { return filteredItems; } return sortItems({ items: filteredItems, sort, fields: formDynamoDbFields }); }; const deleteForm = async ( params: FormBuilderStorageOperationsDeleteFormParams ): Promise<FbForm> => { const { form } = params; let items: any[]; /** * This will find all form and submission records. */ const queryAllParams = { entity, partitionKey: createFormPartitionKey(form), options: { gte: " " } }; try { items = await queryAll<DbRecord>(queryAllParams); } catch (ex) { throw new WebinyError( ex.message || "Could not query forms and submissions by given params.", ex.code || "QUERY_FORM_AND_SUBMISSIONS_ERROR", { partitionKey: queryAllParams.partitionKey, options: queryAllParams.options } ); } const deleteItems = items.map(item => { return entity.deleteBatch({ PK: item.PK, SK: item.SK }); }); try { await batchWriteAll({ table, items: deleteItems }); } catch (ex) { throw new WebinyError( ex.message || "Could not delete form and it's submissions.", ex.code || "DELETE_FORM_AND_SUBMISSIONS_ERROR" ); } const latestKeys = { PK: createFormPartitionKey(form), SK: createLatestSortKey() }; try { await esEntity.delete(latestKeys); } catch (ex) { throw new WebinyError( ex.message || "Could not delete latest form record from Elasticsearch.", ex.code || "DELETE_FORM_ERROR", { latestKeys } ); } return form; }; /** * We need to: * - delete current revision * - get previously published revision and update the record if it exists or delete if it does not * - update latest record if current one is the latest */ const deleteFormRevision = async ( params: FormBuilderStorageOperationsDeleteFormRevisionParams ): Promise<FbForm> => { const { form, revisions, previous } = params; const revisionKeys = { PK: createFormPartitionKey(form), SK: createRevisionSortKey(form.id) }; const latestKeys = { PK: createFormPartitionKey(form), SK: createLatestSortKey() }; const latestForm = revisions[0]; const latestPublishedForm = revisions.find(rev => rev.published === true); const isLatest = latestForm ? latestForm.id === form.id : false; const isLatestPublished = latestPublishedForm ? latestPublishedForm.id === form.id : false; const items = [entity.deleteBatch(revisionKeys)]; let esDataItem = undefined; if (isLatest || isLatestPublished) { /** * Sort out the latest published record. */ if (isLatestPublished) { const previouslyPublishedForm = revisions .filter(f => !!f.publishedOn && f.version !== form.version) .sort((a, b) => { return ( new Date(b.publishedOn as string).getTime() - new Date(a.publishedOn as string).getTime() ); }) .shift(); if (previouslyPublishedForm) { items.push( entity.putBatch({ ...previouslyPublishedForm, PK: createFormPartitionKey(previouslyPublishedForm), SK: createLatestPublishedSortKey(), TYPE: createFormLatestPublishedType() }) ); } else { items.push( entity.deleteBatch({ PK: createFormPartitionKey(form), SK: createLatestPublishedSortKey() }) ); } } /** * Sort out the latest record. */ if (isLatest && previous) { items.push( entity.putBatch({ ...previous, ...latestKeys, TYPE: createFormLatestType() }) ); const { index } = configurations.es({ tenant: previous.tenant, locale: previous.locale }); esDataItem = { index, ...latestKeys, data: getESDataForLatestRevision(previous) }; } } /** * Now save the batch data. */ try { await batchWriteAll({ table, items }); } catch (ex) { throw new WebinyError( ex.message || "Could not delete form revision from regular table.", ex.code || "DELETE_FORM_REVISION_ERROR", { form, latestForm, revisionKeys, latestKeys } ); } /** * And then the Elasticsearch data, if any. */ if (!esDataItem) { return form; } try { await esEntity.put(esDataItem); return form; } catch (ex) { throw new WebinyError( ex.message || "Could not delete form from to the Elasticsearch table.", ex.code || "DELETE_FORM_REVISION_ERROR", { form, latestForm, revisionKeys, latestKeys } ); } }; /** * We need to save form in: * - regular form record * - latest published form record * - latest form record - if form is latest one * - elasticsearch latest form record */ const publishForm = async ( params: FormBuilderStorageOperationsPublishFormParams ): Promise<FbForm> => { const { form, original } = params; const revisionKeys = { PK: createFormPartitionKey(form), SK: createRevisionSortKey(form.version) }; const latestKeys = { PK: createFormPartitionKey(form), SK: createLatestSortKey() }; const latestPublishedKeys = { PK: createFormPartitionKey(form), SK: createLatestPublishedSortKey() }; const { locale, tenant, formId } = form; const latestForm = await getForm({ where: { formId, tenant, locale, latest: true } }); const isLatestForm = latestForm ? latestForm.id === form.id : false; /** * Update revision and latest published records */ const items = [ entity.putBatch({ ...form, ...revisionKeys, TYPE: createFormType() }), entity.putBatch({ ...form, ...latestPublishedKeys, TYPE: createFormLatestPublishedType() }) ]; /** * Update the latest form as well */ if (isLatestForm) { items.push( entity.putBatch({ ...form, ...latestKeys, TYPE: createFormLatestType() }) ); } try { await batchWriteAll({ table, items }); } catch (ex) { throw new WebinyError( ex.message || "Could not publish form.", ex.code || "PUBLISH_FORM_ERROR", { form, original, latestForm, revisionKeys, latestKeys, latestPublishedKeys } ); } if (!isLatestForm) { return form; } const { index } = configurations.es({ tenant: form.tenant, locale: form.locale }); const esData = getESDataForLatestRevision(form); try { await esEntity.put({ ...latestKeys, index, TYPE: createFormLatestType(), data: esData }); return form; } catch (ex) { throw new WebinyError( ex.message || "Could not publish form to the Elasticsearch.", ex.code || "PUBLISH_FORM_ERROR", { form, original, latestForm, revisionKeys, latestKeys, latestPublishedKeys } ); } }; /** * We need to: * - update form revision record * - if latest published (LP) is current form, find the previously published record and update LP if there is some previously published, delete otherwise * - if is latest update the Elasticsearch record */ const unpublishForm = async ( params: FormBuilderStorageOperationsUnpublishFormParams ): Promise<FbForm> => { const { form, original } = params; const revisionKeys = { PK: createFormPartitionKey(form), SK: createRevisionSortKey(form.version) }; const latestKeys = { PK: createFormPartitionKey(form), SK: createLatestSortKey() }; const latestPublishedKeys = { PK: createFormPartitionKey(form), SK: createLatestPublishedSortKey() }; const { formId, tenant, locale } = form; const latestForm = await getForm({ where: { formId, tenant, locale, latest: true } }); const latestPublishedForm = await getForm({ where: { formId, tenant, locale, published: true } }); const isLatest = latestForm ? latestForm.id === form.id : false; const isLatestPublished = latestPublishedForm ? latestPublishedForm.id === form.id : false; const items = [ entity.putBatch({ ...form, ...revisionKeys, TYPE: createFormType() }) ]; let esData: any = undefined; if (isLatest) { esData = getESDataForLatestRevision(form); } /** * In case previously published revision exists, replace current one with that one. * And if it does not, delete the record. */ if (isLatestPublished) { const revisions = await listFormRevisions({ where: { formId, tenant, locale, version_not: form.version, publishedOn_not: null }, sort: ["savedOn_DESC"] }); const previouslyPublishedRevision = revisions.shift(); if (previouslyPublishedRevision) { items.push( entity.putBatch({ ...previouslyPublishedRevision, ...latestPublishedKeys, TYPE: createFormLatestPublishedType() }) ); } else { items.push(entity.deleteBatch(latestPublishedKeys)); } } try { await batchWriteAll({ table, items }); } catch (ex) { throw new WebinyError( ex.message || "Could not unpublish form.", ex.code || "UNPUBLISH_FORM_ERROR", { form, original, latestForm, revisionKeys, latestKeys, latestPublishedKeys } ); } /** * No need to go further in case of non-existing Elasticsearch data. */ if (!esData) { return form; } const { index } = configurations.es({ tenant: form.tenant, locale: form.locale }); try { await esEntity.put({ ...latestKeys, index, TYPE: createFormLatestType(), data: esData }); return form; } catch (ex) { throw new WebinyError( ex.message || "Could not unpublish form from the Elasticsearch.", ex.code || "UNPUBLISH_FORM_ERROR", { form, original, latestForm, revisionKeys, latestKeys, latestPublishedKeys } ); } }; return { createForm, createFormFrom, updateForm, listForms, listFormRevisions, getForm, deleteForm, deleteFormRevision, publishForm, unpublishForm, createFormPartitionKey }; };
the_stack
import Token = require('markdown-it/lib/token'); import * as vscode from 'vscode'; import { MarkdownEngine } from '../markdownEngine'; import { TableOfContents, TocEntry } from '../tableOfContents'; import { SkinnyTextDocument } from '../workspaceContents'; interface MarkdownItTokenWithMap extends Token { map: [number, number]; } export class MdSmartSelect implements vscode.SelectionRangeProvider { constructor( private readonly engine: MarkdownEngine ) { } public async provideSelectionRanges(document: SkinnyTextDocument, positions: vscode.Position[], _token: vscode.CancellationToken): Promise<vscode.SelectionRange[] | undefined> { const promises = await Promise.all(positions.map((position) => { return this.provideSelectionRange(document, position, _token); })); return promises.filter(item => item !== undefined) as vscode.SelectionRange[]; } private async provideSelectionRange(document: SkinnyTextDocument, position: vscode.Position, _token: vscode.CancellationToken): Promise<vscode.SelectionRange | undefined> { const headerRange = await this.getHeaderSelectionRange(document, position); const blockRange = await this.getBlockSelectionRange(document, position, headerRange); const inlineRange = await this.getInlineSelectionRange(document, position, blockRange); return inlineRange || blockRange || headerRange; } private async getInlineSelectionRange(document: SkinnyTextDocument, position: vscode.Position, blockRange?: vscode.SelectionRange): Promise<vscode.SelectionRange | undefined> { return createInlineRange(document, position, blockRange); } private async getBlockSelectionRange(document: SkinnyTextDocument, position: vscode.Position, headerRange?: vscode.SelectionRange): Promise<vscode.SelectionRange | undefined> { const tokens = await this.engine.parse(document); const blockTokens = getBlockTokensForPosition(tokens, position, headerRange); if (blockTokens.length === 0) { return undefined; } let currentRange: vscode.SelectionRange | undefined = headerRange ? headerRange : createBlockRange(blockTokens.shift()!, document, position.line); for (let i = 0; i < blockTokens.length; i++) { currentRange = createBlockRange(blockTokens[i], document, position.line, currentRange); } return currentRange; } private async getHeaderSelectionRange(document: SkinnyTextDocument, position: vscode.Position): Promise<vscode.SelectionRange | undefined> { const toc = await TableOfContents.create(this.engine, document); const headerInfo = getHeadersForPosition(toc.entries, position); const headers = headerInfo.headers; let currentRange: vscode.SelectionRange | undefined; for (let i = 0; i < headers.length; i++) { currentRange = createHeaderRange(headers[i], i === headers.length - 1, headerInfo.headerOnThisLine, currentRange, getFirstChildHeader(document, headers[i], toc.entries)); } return currentRange; } } function getHeadersForPosition(toc: readonly TocEntry[], position: vscode.Position): { headers: TocEntry[]; headerOnThisLine: boolean } { const enclosingHeaders = toc.filter(header => header.sectionLocation.range.start.line <= position.line && header.sectionLocation.range.end.line >= position.line); const sortedHeaders = enclosingHeaders.sort((header1, header2) => (header1.line - position.line) - (header2.line - position.line)); const onThisLine = toc.find(header => header.line === position.line) !== undefined; return { headers: sortedHeaders, headerOnThisLine: onThisLine }; } function createHeaderRange(header: TocEntry, isClosestHeaderToPosition: boolean, onHeaderLine: boolean, parent?: vscode.SelectionRange, startOfChildRange?: vscode.Position): vscode.SelectionRange | undefined { const range = header.sectionLocation.range; const contentRange = new vscode.Range(range.start.translate(1), range.end); if (onHeaderLine && isClosestHeaderToPosition && startOfChildRange) { // selection was made on this header line, so select header and its content until the start of its first child // then all of its content return new vscode.SelectionRange(range.with(undefined, startOfChildRange), new vscode.SelectionRange(range, parent)); } else if (onHeaderLine && isClosestHeaderToPosition) { // selection was made on this header line and no children so expand to all of its content return new vscode.SelectionRange(range, parent); } else if (isClosestHeaderToPosition && startOfChildRange) { // selection was made within content and has child so select content // of this header then all content then header return new vscode.SelectionRange(contentRange.with(undefined, startOfChildRange), new vscode.SelectionRange(contentRange, (new vscode.SelectionRange(range, parent)))); } else { // not on this header line so select content then header return new vscode.SelectionRange(contentRange, new vscode.SelectionRange(range, parent)); } } function getBlockTokensForPosition(tokens: Token[], position: vscode.Position, parent?: vscode.SelectionRange): MarkdownItTokenWithMap[] { const enclosingTokens = tokens.filter((token): token is MarkdownItTokenWithMap => !!token.map && (token.map[0] <= position.line && token.map[1] > position.line) && (!parent || (token.map[0] >= parent.range.start.line && token.map[1] <= parent.range.end.line + 1)) && isBlockElement(token)); if (enclosingTokens.length === 0) { return []; } const sortedTokens = enclosingTokens.sort((token1, token2) => (token2.map[1] - token2.map[0]) - (token1.map[1] - token1.map[0])); return sortedTokens; } function createBlockRange(block: MarkdownItTokenWithMap, document: SkinnyTextDocument, cursorLine: number, parent?: vscode.SelectionRange): vscode.SelectionRange | undefined { if (block.type === 'fence') { return createFencedRange(block, cursorLine, document, parent); } else { let startLine = document.lineAt(block.map[0]).isEmptyOrWhitespace ? block.map[0] + 1 : block.map[0]; let endLine = startLine === block.map[1] ? block.map[1] : block.map[1] - 1; if (block.type === 'paragraph_open' && block.map[1] - block.map[0] === 2) { startLine = endLine = cursorLine; } else if (isList(block) && document.lineAt(endLine).isEmptyOrWhitespace) { endLine = endLine - 1; } const range = new vscode.Range(startLine, 0, endLine, document.lineAt(endLine).text?.length ?? 0); if (parent?.range.contains(range) && !parent.range.isEqual(range)) { return new vscode.SelectionRange(range, parent); } else if (parent?.range.isEqual(range)) { return parent; } else { return new vscode.SelectionRange(range); } } } function createInlineRange(document: SkinnyTextDocument, cursorPosition: vscode.Position, parent?: vscode.SelectionRange): vscode.SelectionRange | undefined { const lineText = document.lineAt(cursorPosition.line).text; const boldSelection = createBoldRange(lineText, cursorPosition.character, cursorPosition.line, parent); const italicSelection = createOtherInlineRange(lineText, cursorPosition.character, cursorPosition.line, true, parent); let comboSelection: vscode.SelectionRange | undefined; if (boldSelection && italicSelection && !boldSelection.range.isEqual(italicSelection.range)) { if (boldSelection.range.contains(italicSelection.range)) { comboSelection = createOtherInlineRange(lineText, cursorPosition.character, cursorPosition.line, true, boldSelection); } else if (italicSelection.range.contains(boldSelection.range)) { comboSelection = createBoldRange(lineText, cursorPosition.character, cursorPosition.line, italicSelection); } } const linkSelection = createLinkRange(lineText, cursorPosition.character, cursorPosition.line, comboSelection || boldSelection || italicSelection || parent); const inlineCodeBlockSelection = createOtherInlineRange(lineText, cursorPosition.character, cursorPosition.line, false, linkSelection || parent); return inlineCodeBlockSelection || linkSelection || comboSelection || boldSelection || italicSelection; } function createFencedRange(token: MarkdownItTokenWithMap, cursorLine: number, document: SkinnyTextDocument, parent?: vscode.SelectionRange): vscode.SelectionRange { const startLine = token.map[0]; const endLine = token.map[1] - 1; const onFenceLine = cursorLine === startLine || cursorLine === endLine; const fenceRange = new vscode.Range(startLine, 0, endLine, document.lineAt(endLine).text.length); const contentRange = endLine - startLine > 2 && !onFenceLine ? new vscode.Range(startLine + 1, 0, endLine - 1, document.lineAt(endLine - 1).text.length) : undefined; if (contentRange) { return new vscode.SelectionRange(contentRange, new vscode.SelectionRange(fenceRange, parent)); } else { if (parent?.range.isEqual(fenceRange)) { return parent; } else { return new vscode.SelectionRange(fenceRange, parent); } } } function createBoldRange(lineText: string, cursorChar: number, cursorLine: number, parent?: vscode.SelectionRange): vscode.SelectionRange | undefined { const regex = /\*\*([^*]+\*?[^*]+\*?[^*]+)\*\*/gim; const matches = [...lineText.matchAll(regex)].filter(match => lineText.indexOf(match[0]) <= cursorChar && lineText.indexOf(match[0]) + match[0].length >= cursorChar); if (matches.length) { // should only be one match, so select first and index 0 contains the entire match const bold = matches[0][0]; const startIndex = lineText.indexOf(bold); const cursorOnStars = cursorChar === startIndex || cursorChar === startIndex + 1 || cursorChar === startIndex + bold.length || cursorChar === startIndex + bold.length - 1; const contentAndStars = new vscode.SelectionRange(new vscode.Range(cursorLine, startIndex, cursorLine, startIndex + bold.length), parent); const content = new vscode.SelectionRange(new vscode.Range(cursorLine, startIndex + 2, cursorLine, startIndex + bold.length - 2), contentAndStars); return cursorOnStars ? contentAndStars : content; } return undefined; } function createOtherInlineRange(lineText: string, cursorChar: number, cursorLine: number, isItalic: boolean, parent?: vscode.SelectionRange): vscode.SelectionRange | undefined { const italicRegexes = [/(?:[^*]+)(\*([^*]+)(?:\*\*[^*]*\*\*)*([^*]+)\*)(?:[^*]+)/g, /^(?:[^*]*)(\*([^*]+)(?:\*\*[^*]*\*\*)*([^*]+)\*)(?:[^*]*)$/g]; let matches = []; if (isItalic) { matches = [...lineText.matchAll(italicRegexes[0])].filter(match => lineText.indexOf(match[0]) <= cursorChar && lineText.indexOf(match[0]) + match[0].length >= cursorChar); if (!matches.length) { matches = [...lineText.matchAll(italicRegexes[1])].filter(match => lineText.indexOf(match[0]) <= cursorChar && lineText.indexOf(match[0]) + match[0].length >= cursorChar); } } else { matches = [...lineText.matchAll(/\`[^\`]*\`/g)].filter(match => lineText.indexOf(match[0]) <= cursorChar && lineText.indexOf(match[0]) + match[0].length >= cursorChar); } if (matches.length) { // should only be one match, so select first and select group 1 for italics because that contains just the italic section // doesn't include the leading and trailing characters which are guaranteed to not be * so as not to be confused with bold const match = isItalic ? matches[0][1] : matches[0][0]; const startIndex = lineText.indexOf(match); const cursorOnType = cursorChar === startIndex || cursorChar === startIndex + match.length; const contentAndType = new vscode.SelectionRange(new vscode.Range(cursorLine, startIndex, cursorLine, startIndex + match.length), parent); const content = new vscode.SelectionRange(new vscode.Range(cursorLine, startIndex + 1, cursorLine, startIndex + match.length - 1), contentAndType); return cursorOnType ? contentAndType : content; } return undefined; } function createLinkRange(lineText: string, cursorChar: number, cursorLine: number, parent?: vscode.SelectionRange): vscode.SelectionRange | undefined { const regex = /(\[[^\(\)]*\])(\([^\[\]]*\))/g; const matches = [...lineText.matchAll(regex)].filter(match => lineText.indexOf(match[0]) <= cursorChar && lineText.indexOf(match[0]) + match[0].length > cursorChar); if (matches.length) { // should only be one match, so select first and index 0 contains the entire match, so match = [text](url) const link = matches[0][0]; const linkRange = new vscode.SelectionRange(new vscode.Range(cursorLine, lineText.indexOf(link), cursorLine, lineText.indexOf(link) + link.length), parent); const linkText = matches[0][1]; const url = matches[0][2]; // determine if cursor is within [text] or (url) in order to know which should be selected const nearestType = cursorChar >= lineText.indexOf(linkText) && cursorChar < lineText.indexOf(linkText) + linkText.length ? linkText : url; const indexOfType = lineText.indexOf(nearestType); // determine if cursor is on a bracket or paren and if so, return the [content] or (content), skipping over the content range const cursorOnType = cursorChar === indexOfType || cursorChar === indexOfType + nearestType.length; const contentAndNearestType = new vscode.SelectionRange(new vscode.Range(cursorLine, indexOfType, cursorLine, indexOfType + nearestType.length), linkRange); const content = new vscode.SelectionRange(new vscode.Range(cursorLine, indexOfType + 1, cursorLine, indexOfType + nearestType.length - 1), contentAndNearestType); return cursorOnType ? contentAndNearestType : content; } return undefined; } function isList(token: Token): boolean { return token.type ? ['ordered_list_open', 'list_item_open', 'bullet_list_open'].includes(token.type) : false; } function isBlockElement(token: Token): boolean { return !['list_item_close', 'paragraph_close', 'bullet_list_close', 'inline', 'heading_close', 'heading_open'].includes(token.type); } function getFirstChildHeader(document: SkinnyTextDocument, header?: TocEntry, toc?: readonly TocEntry[]): vscode.Position | undefined { let childRange: vscode.Position | undefined; if (header && toc) { let children = toc.filter(t => header.sectionLocation.range.contains(t.sectionLocation.range) && t.sectionLocation.range.start.line > header.sectionLocation.range.start.line).sort((t1, t2) => t1.line - t2.line); if (children.length > 0) { childRange = children[0].sectionLocation.range.start; const lineText = document.lineAt(childRange.line - 1).text; return childRange ? childRange.translate(-1, lineText.length) : undefined; } } return undefined; }
the_stack
import { objects, Uri } from '@opensumi/ide-core-browser'; import * as monaco from '@opensumi/monaco-editor-core/esm/vs/editor/editor.api'; import { IConfigurationService } from '@opensumi/monaco-editor-core/esm/vs/platform/configuration/common/configuration'; import { IConvertedMonacoOptions } from '../types'; const { removeUndefined } = objects; /** * 计算由ConfigurationService设置值带来的monaco编辑器的属性 * @param configurationService IConfigurationService * @param updatingKey 需要处理的Preference key。如果没有这个值,默认处理全部。 */ export function getConvertedMonacoOptions( configurationService: IConfigurationService, resourceUri?: string, language?: string, updatingKey?: string[], ): IConvertedMonacoOptions { const editorOptions: Partial<monaco.editor.IEditorOptions> = {}; const diffOptions: Partial<monaco.editor.IDiffEditorOptions> = {}; const modelOptions: Partial<monaco.editor.ITextModelUpdateOptions> = {}; const editorOptionsKeys = updatingKey ? updatingKey.filter((key) => editorOptionsConverters.has(key)) : Array.from(editorOptionsConverters.keys()); const textModelUpdateOptionsKeys = updatingKey ? updatingKey.filter((key) => textModelUpdateOptionsConverters.has(key)) : Array.from(textModelUpdateOptionsConverters.keys()); const diffEditorOptionsKeys = updatingKey ? updatingKey.filter((key) => diffEditorOptionsConverters.has(key)) : Array.from(diffEditorOptionsConverters.keys()); editorOptionsKeys.forEach((key) => { const value = configurationService.getValue(key, { resource: resourceUri ? Uri.parse(resourceUri) : undefined, overrideIdentifier: language, }); if (value === undefined) { return; } if (!editorOptionsConverters.get(key)) { editorOptions[key] = value; } else { const converter: IMonacoOptionsConverter = editorOptionsConverters.get(key)! as IMonacoOptionsConverter; editorOptions[converter.monaco] = converter.convert ? converter.convert(value) : value; } }); textModelUpdateOptionsKeys.forEach((key) => { const value = configurationService.getValue(key, { resource: resourceUri ? Uri.parse(resourceUri) : undefined, overrideIdentifier: language, }); if (value === undefined) { return; } if (!textModelUpdateOptionsConverters.get(key)) { modelOptions[key] = value; } else { const converter: IMonacoOptionsConverter = textModelUpdateOptionsConverters.get(key)! as IMonacoOptionsConverter; modelOptions[converter.monaco] = converter.convert ? converter.convert(value) : value; } }); diffEditorOptionsKeys.forEach((key) => { const value = configurationService.getValue(key, { resource: resourceUri ? Uri.parse(resourceUri) : undefined, overrideIdentifier: language, }); if (value === undefined) { return; } if (!diffEditorOptionsConverters.get(key)) { editorOptions[key] = value; } else { const converter: IMonacoOptionsConverter = diffEditorOptionsConverters.get(key)! as IMonacoOptionsConverter; diffOptions[converter.monaco] = converter.convert ? converter.convert(value) : value; } }); return { editorOptions: removeUndefined(editorOptions), modelOptions: removeUndefined(modelOptions), diffOptions: removeUndefined(diffOptions), }; } type NoConverter = false; type KaitianPreferenceKey = string; type MonacoPreferenceKey = string; /** * monacoOption和Preference的转换 */ interface IMonacoOptionsConverter { /** * monaco编辑器的设置值 */ monaco: MonacoPreferenceKey; /** * 转换器:输入为Preference值,输出monaco Options值 */ convert?: (value: any) => any; } /** * Configuration options for the editor. */ export const editorOptionsConverters: Map<KaitianPreferenceKey, NoConverter | IMonacoOptionsConverter> = new Map< string, NoConverter | IMonacoOptionsConverter >([ /** * The aria label for the editor's textarea (when it is focused). */ ['editor.ariaLabel', { monaco: 'ariaLabel' }], /** * Render vertical lines at the specified columns. * Defaults to empty array. */ ['editor.rulers', { monaco: 'rulers' }], /** * A string containing the word separators used when doing word navigation. * Defaults to `~!@#$%^&*()-=+[{]}\\|;'', */ ['editor.wordSeparators', { monaco: 'wordSeparators' }], /** * Enable Linux primary clipboard. * Defaults to true. */ ['editor.selectionClipboard', { monaco: 'selectionClipboard' }], /** * Control the rendering of line numbers. * If it is a function, it will be invoked when rendering a line number and the return value will be rendered. * Otherwise, if it is a truey, line numbers will be rendered normally (equivalent of using an identity function). * Otherwise, line numbers will not be rendered. * Defaults to true. */ ['editor.lineNumbers', { monaco: 'lineNumbers' }], /** * Render last line number when the file ends with a newline. * Defaults to true. */ ['editor.renderFinalNewline', { monaco: 'renderFinalNewline' }], /** * Should the corresponding line be selected when clicking on the line number? * Defaults to true. */ ['editor.selectOnLineNumbers', { monaco: 'selectOnLineNumbers' }], /** * Control the width of line numbers, by reserving horizontal space for rendering at least an amount of digits. * Defaults to 5. */ ['editor.lineNumbersMinChars', { monaco: 'lineNumbersMinChars' }], /** * Enable the rendering of the glyph margin. * Defaults to true in vscode and to false in monaco-editor. */ ['editor.glyphMargin', { monaco: 'glyphMargin' }], /** * The width reserved for line decorations (in px). * Line decorations are placed between line numbers and the editor content. * You can pass in a string in the format floating point followed by "ch". e.g. 1.3ch. * Defaults to 10. */ ['editor.lineDecorationsWidth', { monaco: 'lineDecorationsWidth' }], /** * When revealing the cursor, a virtual padding (px) is added to the cursor, turning it into a rectangle. * This virtual padding ensures that the cursor gets revealed before hitting the edge of the viewport. * Defaults to 30 (px). */ ['editor.revealHorizontalRightPadding', { monaco: 'revealHorizontalRightPadding' }], /** * Render the editor selection with rounded borders. * Defaults to true. */ ['editor.roundedSelection', { monaco: 'roundedSelection' }], /** * Class name to be added to the editor. */ ['editor.extraEditorClassName', { monaco: 'extraEditorClassName' }], /** * Should the editor be read only. * Defaults to false. */ ['editor.readOnly', { monaco: 'readOnly' }], /** * Control the behavior and rendering of the scrollbars. */ ['editor.scrollbar', { monaco: 'scrollbar' }], /** * Control the behavior and rendering of the minimap. */ [ 'editor.minimap', { monaco: 'minimap', convert: (value: any) => ({ enabled: value, }), }, ], /** * Control the behavior of the find widget. */ ['editor.find', { monaco: 'find' }], /** * Display overflow widgets as `fixed`. * Defaults to `false`. */ ['editor.fixedOverflowWidgets', { monaco: 'fixedOverflowWidgets' }], /** * The number of vertical lanes the overview ruler should render. * Defaults to 2. */ ['editor.overviewRulerLanes', { monaco: 'overviewRulerLanes' }], /** * Controls if a border should be drawn around the overview ruler. * Defaults to `true`. */ ['editor.overviewRulerBorder', { monaco: 'overviewRulerBorder' }], /** * Control the cursor animation style, possible values are 'blink', 'smooth', 'phase', 'expand' and 'solid'. * Defaults to 'blink'. */ ['editor.cursorBlinking', { monaco: 'cursorBlinking' }], /** * Zoom the font in the editor when using the mouse wheel in combination with holding Ctrl. * Defaults to false. */ ['editor.mouseWheelZoom', { monaco: 'mouseWheelZoom' }], /** * Enable smooth caret animation. * Defaults to false. */ ['editor.cursorSmoothCaretAnimation', { monaco: 'cursorSmoothCaretAnimation' }], /** * Control the cursor style, either 'block' or 'line'. * Defaults to 'line'. */ ['editor.cursorStyle', { monaco: 'cursorStyle' }], /** * Control the width of the cursor when cursorStyle is set to 'line' */ ['editor.cursorWidth', { monaco: 'cursorWidth' }], /** * Enable font ligatures. * Defaults to false. */ ['editor.fontLigatures', { monaco: 'fontLigatures' }], /** * Disable the use of `will-change` for the editor margin and lines layers. * The usage of `will-change` acts as a hint for browsers to create an extra layer. * Defaults to false. */ ['editor.disableLayerHinting', { monaco: 'disableLayerHinting' }], /** * Disable the optimizations for monospace fonts. * Defaults to false. */ ['editor.disableMonospaceOptimizations', { monaco: 'disableMonospaceOptimizations' }], /** * Should the cursor be hidden in the overview ruler. * Defaults to false. */ ['editor.hideCursorInOverviewRuler', { monaco: 'hideCursorInOverviewRuler' }], /** * Enable that scrolling can go one screen size after the last line. * Defaults to true. */ ['editor.scrollBeyondLastLine', { monaco: 'scrollBeyondLastLine' }], /** * Enable that scrolling can go beyond the last column by a number of columns. * Defaults to 5. */ ['editor.scrollBeyondLastColumn', { monaco: 'scrollBeyondLastColumn' }], /** * Enable that the editor animates scrolling to a position. * Defaults to false. */ ['editor.smoothScrolling', { monaco: 'smoothScrolling' }], /** * Enable that the editor will install an interval to check if its container dom node size has changed. * Enabling this might have a severe performance impact. * Defaults to false. */ ['editor.automaticLayout', { monaco: 'automaticLayout' }], /** * Control the wrapping of the editor. * When `wordWrap` = "off", the lines will never wrap. * When `wordWrap` = "on", the lines will wrap at the viewport width. * When `wordWrap` = "wordWrapColumn", the lines will wrap at `wordWrapColumn`. * When `wordWrap` = "bounded", the lines will wrap at min(viewport width, wordWrapColumn). * Defaults to "off". */ ['editor.wordWrap', { monaco: 'wordWrap' }], /** * Control the wrapping of the editor. * When `wordWrap` = "off", the lines will never wrap. * When `wordWrap` = "on", the lines will wrap at the viewport width. * When `wordWrap` = "wordWrapColumn", the lines will wrap at `wordWrapColumn`. * When `wordWrap` = "bounded", the lines will wrap at min(viewport width, wordWrapColumn). * Defaults to 80. */ ['editor.wordWrapColumn', { monaco: 'wordWrapColumn' }], /** * Force word wrapping when the text appears to be of a minified/generated file. * Defaults to true. */ ['editor.wordWrapMinified', { monaco: 'wordWrapMinified' }], /** * Control indentation of wrapped lines. Can 'be', * Defaults to 'same' in vscode and to 'none' in monaco-editor. */ ['editor.wrappingIndent', { monaco: 'wrappingIndent' }], /** * Configure word wrapping characters. A break will be introduced before these characters. * Defaults to '{([+'. */ ['editor.wordWrapBreakBeforeCharacters', { monaco: 'wordWrapBreakBeforeCharacters' }], /** * Configure word wrapping characters. A break will be introduced after these characters. * Defaults to ' \t})]?|&,;'. */ ['editor.wordWrapBreakAfterCharacters', { monaco: 'wordWrapBreakAfterCharacters' }], /** * Configure word wrapping characters. A break will be introduced after these characters only if no `wordWrapBreakBeforeCharacters` or `wordWrapBreakAfterCharacters` were found. * Defaults to '.'. */ ['editor.wordWrapBreakObtrusiveCharacters', { monaco: 'wordWrapBreakObtrusiveCharacters' }], /** * Performance 'guard', * Defaults to 10000. * Use -1 to never stop rendering */ ['editor.stopRenderingLineAfter', { monaco: 'stopRenderingLineAfter' }], /** * Configure the editor's hover. */ ['editor.hover', { monaco: 'hover' }], /** * Enable detecting links and making them clickable. * Defaults to true. */ ['editor.links', { monaco: 'links' }], /** * Enable inline color decorators and color picker rendering. */ ['editor.colorDecorators', { monaco: 'colorDecorators' }], /** * Enable custom contextmenu. * Defaults to true. */ ['editor.contextmenu', { monaco: 'contextmenu' }], /** * A multiplier to be used on the `deltaX` and `deltaY` of mouse wheel scroll events. * Defaults to 1. */ ['editor.mouseWheelScrollSensitivity', { monaco: 'mouseWheelScrollSensitivity' }], /** * FastScrolling mulitplier speed when pressing `Alt` * Defaults to 5. */ ['editor.fastScrollSensitivity', { monaco: 'fastScrollSensitivity' }], /** * The modifier to be used to add multiple cursors with the mouse. * Defaults to 'alt' */ ['editor.multiCursorModifier', { monaco: 'multiCursorModifier' }], /** * Merge overlapping selections. * Defaults to true */ ['editor.multiCursorMergeOverlapping', { monaco: 'multiCursorMergeOverlapping' }], /** * Configure the editor's accessibility support. * Defaults to 'auto'. It is best to leave this to 'auto'. */ ['editor.accessibilitySupport', { monaco: 'accessibilitySupport' }], /** * Suggest options. */ ['editor.suggest', { monaco: 'suggest' }], /** * */ ['editor.gotoLocation', { monaco: 'gotoLocation' }], /** * Enable quick suggestions (shadow suggestions) * Defaults to true. */ ['editor.quickSuggestions', { monaco: 'quickSuggestions' }], /** * Quick suggestions show delay (in ms) * Defaults to 500 (ms) */ ['editor.quickSuggestionsDelay', { monaco: 'quickSuggestionsDelay' }], /** * Parameter hint options. */ ['editor.parameterHints', { monaco: 'parameterHints' }], /** * Options for auto closing brackets. * Defaults to language defined behavior. */ ['editor.autoClosingBrackets', { monaco: 'autoClosingBrackets' }], /** * Options for auto closing quotes. * Defaults to language defined behavior. */ ['editor.autoClosingQuotes', { monaco: 'autoClosingQuotes' }], /** * Options for auto surrounding. * Defaults to always allowing auto surrounding. */ ['editor.autoSurround', { monaco: 'autoSurround' }], /** * Enable auto indentation adjustment. * Defaults to false. */ ['editor.autoIndent', { monaco: 'autoIndent' }], /** * Enable format on type. * Defaults to false. */ ['editor.formatOnType', { monaco: 'formatOnType' }], /** * Enable format on paste. * Defaults to false. */ ['editor.formatOnPaste', { monaco: 'formatOnPaste' }], /** * Controls if the editor should allow to move selections via drag and drop. * Defaults to false. */ ['editor.dragAndDrop', { monaco: 'dragAndDrop' }], /** * Enable the suggestion box to pop-up on trigger characters. * Defaults to true. */ ['editor.suggestOnTriggerCharacters', { monaco: 'suggestOnTriggerCharacters' }], /** * Accept suggestions on ENTER. * Defaults to 'on'. */ ['editor.acceptSuggestionOnEnter', { monaco: 'acceptSuggestionOnEnter' }], /** * Accept suggestions on provider defined characters. * Defaults to true. */ ['editor.acceptSuggestionOnCommitCharacter', { monaco: 'acceptSuggestionOnCommitCharacter' }], /** * Enable snippet suggestions. Default to 'true'. */ ['editor.snippetSuggestions', { monaco: 'snippetSuggestions' }], /** * Copying without a selection copies the current line. */ ['editor.emptySelectionClipboard', { monaco: 'emptySelectionClipboard' }], /** * Syntax highlighting is copied. */ ['editor.copyWithSyntaxHighlighting', { monaco: 'copyWithSyntaxHighlighting' }], /** * Enable word based suggestions. Defaults to 'true' */ ['editor.wordBasedSuggestions', { monaco: 'wordBasedSuggestions' }], /** * The history mode for suggestions. */ ['editor.suggestSelection', { monaco: 'suggestSelection' }], /** * The font size for the suggest widget. * Defaults to the editor font size. */ ['editor.suggestFontSize', { monaco: 'suggestFontSize' }], /** * The line height for the suggest widget. * Defaults to the editor line height. */ ['editor.suggestLineHeight', { monaco: 'suggestLineHeight' }], /** * Enable tab completion. */ ['editor.tabCompletion', { monaco: 'tabCompletion' }], /** * Enable selection highlight. * Defaults to true. */ ['editor.selectionHighlight', { monaco: 'selectionHighlight' }], /** * Enable semantic occurrences highlight. * Defaults to true. */ ['editor.occurrencesHighlight', { monaco: 'occurrencesHighlight' }], /** * Show code lens * Defaults to true. */ ['editor.codeLens', { monaco: 'codeLens' }], /** * Control the behavior and rendering of the code action lightbulb. */ ['editor.lightbulb', { monaco: 'lightbulb' }], /** * Code action kinds to be run on save. */ ['editor.codeActionsOnSave', { monaco: 'codeActionsOnSave' }], /** * Timeout for running code actions on save. */ ['editor.codeActionsOnSaveTimeout', { monaco: 'codeActionsOnSaveTimeout' }], /** * Enable code folding * Defaults to true. */ ['editor.folding', { monaco: 'folding' }], /** * Selects the folding strategy. 'auto' uses the strategies contributed for the current document, 'indentation' uses the indentation based folding strategy. * Defaults to 'auto'. */ ['editor.foldingStrategy', { monaco: 'foldingStrategy' }], /** * Controls whether the fold actions in the gutter stay always visible or hide unless the mouse is over the gutter. * Defaults to 'mouseover'. */ ['editor.showFoldingControls', { monaco: 'showFoldingControls' }], /** * Enable highlighting of matching brackets. * Defaults to true. */ ['editor.matchBrackets', { monaco: 'matchBrackets' }], /** * Enable rendering of whitespace. * Defaults to none. */ ['editor.renderWhitespace', { monaco: 'renderWhitespace' }], /** * Enable rendering of control characters. * Defaults to false. */ ['editor.renderControlCharacters', { monaco: 'renderControlCharacters' }], /** * Enable rendering of indent guides. * Defaults to true. */ ['editor.renderIndentGuides', { monaco: 'guides.indentation' }], /** * Enable highlighting of the active indent guide. * Defaults to true. */ ['editor.highlightActiveIndentGuide', { monaco: 'guides.highlightActiveIndentation' }], /** * editor.guides -> guides */ ['editor.guides', { monaco: 'guides' }], /** * Enable rendering of current line highlight. * Defaults to all. */ ['editor.renderLineHighlight', { monaco: 'renderLineHighlight' }], /** * Inserting and deleting whitespace follows tab stops. */ ['editor.useTabStops', { monaco: 'useTabStops' }], /** * The font family */ ['editor.fontFamily', { monaco: 'fontFamily' }], /** * The font weight */ ['editor.fontWeight', { monaco: 'fontWeight' }], /** * The font size */ ['editor.fontSize', { monaco: 'fontSize' }], /** * The line height */ ['editor.lineHeight', { monaco: 'lineHeight' }], /** * The letter spacing */ ['editor.letterSpacing', { monaco: 'letterSpacing' }], /** * Controls fading out of unused variables. */ ['editor.showUnused', { monaco: 'showUnused' }], ['editor.rename.enablePreview', { monaco: 'editor.rename.enablePreview' }], ['editor.semanticHighlighting', { monaco: 'semanticHighlighting' }], ['editor.bracketPairColorization', { monaco: 'bracketPairColorization' }], /** * Controls the algorithm that computes wrapping points. * Default is "advanced" (Monaco Editor default is "simple") */ ['editor.wrappingStrategy', { monaco: 'wrappingStrategy' }], /** * 是否强行readonly */ [ 'editor.forceReadOnly', { monaco: 'readOnly', convert: (value: boolean) => { if (value) { return true; } else { return undefined; } }, }, ], ]); export const textModelUpdateOptionsConverters: Map<KaitianPreferenceKey, NoConverter | IMonacoOptionsConverter> = new Map<string, NoConverter | IMonacoOptionsConverter>([ ['editor.tabSize', { monaco: 'tabSize' }], ['editor.indentSize', { monaco: 'indentSize' }], ['editor.insertSpaces', { monaco: 'insertSpaces' }], ['editor.trimAutoWhitespace', { monaco: 'trimAutoWhitespace' }], ]); export const diffEditorOptionsConverters: Map<KaitianPreferenceKey, NoConverter | IMonacoOptionsConverter> = new Map< string, NoConverter | IMonacoOptionsConverter >([ /** * Allow the user to resize the diff editor split view. * Defaults to true. */ ['diffEditor.enableSplitViewResizing', { monaco: 'enableSplitViewResizing' }], /** * Render the differences in two side-by-side editors. * Defaults to true. */ ['diffEditor.renderSideBySide', { monaco: 'renderSideBySide' }], /** * Compute the diff by ignoring leading/trailing whitespace * Defaults to true. */ ['diffEditor.ignoreTrimWhitespace', { monaco: 'ignoreTrimWhitespace' }], /** * Render +/- indicators for added/deleted changes. * Defaults to true. */ ['diffEditor.renderIndicators', { monaco: 'renderIndicators' }], /** * Original model should be editable? * Defaults to false. */ ['diffEditor.originalEditable', { monaco: 'originalEditable' }], ]); function isContainOptionKey(key: string, optionMap: Map<KaitianPreferenceKey, NoConverter | IMonacoOptionsConverter>) { if (optionMap.has(key)) { return true; } else { // 处理 "包含" 情况下的配置判断,如 // editor.suggest.xxx const keys = optionMap.keys(); for (const k of keys) { if (key.startsWith(k)) { return true; } } } return false; } export function isEditorOption(key: string) { return ( isContainOptionKey(key, editorOptionsConverters) || isContainOptionKey(key, textModelUpdateOptionsConverters) || isContainOptionKey(key, diffEditorOptionsConverters) ); } export function isDiffEditorOption(key: string): boolean { return isContainOptionKey(key, diffEditorOptionsConverters); }
the_stack
import * as path from "path"; import * as vscode from "vscode"; import { applyWorkspaceEdit } from "../utils/editUtils"; import { registerCommand } from "../utils/uiUtils"; import { executeJavaLanguageServerCommand, getJavaExtension, isJavaExtActivated } from "./commands"; // Please refer to https://help.eclipse.org/2019-06/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Freference%2Fapi%2Fconstant-values.html const UNDEFINED_TYPE: string = "16777218"; // e.g. Unknown var; const UNDEFINED_NAME: string = "570425394"; // e.g. Unknown.foo(); const COMMAND_SEARCH_ARTIFACT: string = "maven.artifactSearch"; const TITLE_RESOLVE_UNKNOWN_TYPE: string = "Resolve unknown type"; export function registerArtifactSearcher(context: vscode.ExtensionContext): void { const javaExt: vscode.Extension<any> | undefined = getJavaExtension(); if (!!javaExt) { const resolver: TypeResolver = new TypeResolver(path.join(context.extensionPath, "resources", "IndexData")); registerCommand(context, COMMAND_SEARCH_ARTIFACT, async (param: any) => await resolver.pickAndAddDependency(param)); context.subscriptions.push(vscode.languages.registerHoverProvider("java", { provideHover(document: vscode.TextDocument, position: vscode.Position, _token: vscode.CancellationToken): vscode.ProviderResult<vscode.Hover> { return resolver.getArtifactsHover(document, position); } })); context.subscriptions.push(vscode.languages.registerCodeActionsProvider("java", { provideCodeActions(document: vscode.TextDocument, range: vscode.Range | vscode.Selection, codeActionContext: vscode.CodeActionContext, _token: vscode.CancellationToken): vscode.ProviderResult<(vscode.Command | vscode.CodeAction)[]> { return resolver.getArtifactsCodeActions(document, codeActionContext, range); } })); } } class TypeResolver { private dataPath: string; private initialized: boolean = false; constructor(dataPath: string) { this.dataPath = dataPath; } public async initialize(): Promise<void> { if (!this.initialized) { try { await executeJavaLanguageServerCommand("java.maven.initializeSearcher", this.dataPath); this.initialized = true; } catch (error) { // ignore } } } public getArtifactsHover(document: vscode.TextDocument, position: vscode.Position): vscode.Hover | undefined { if (!isJavaExtActivated()) { return undefined; } if (!this.initialized) { this.initialize().catch(); return undefined; } const diagnostics: vscode.Diagnostic[] = vscode.languages.getDiagnostics(document.uri).filter(diagnostic => { return diagnosticIndicatesUnresolvedType(diagnostic, document) && position.isAfterOrEqual(diagnostic.range.start) && position.isBeforeOrEqual(diagnostic.range.end); }); if (diagnostics.length > 0) { const diagnostic: vscode.Diagnostic = diagnostics[0]; const line: number = diagnostic.range.start.line; const character: number = diagnostic.range.start.character; const className: string = document.getText(diagnostic.range); const length: number = document.offsetAt(diagnostic.range.end) - document.offsetAt(diagnostic.range.start); const param: any = { className, uri: encodeBase64(document.uri.toString()), line, character, length }; const commandName: string = TITLE_RESOLVE_UNKNOWN_TYPE; const message: string = `\uD83D\uDC49 [${commandName}](command:${COMMAND_SEARCH_ARTIFACT}?${encodeURIComponent(JSON.stringify(param))} "${commandName}")`; const hoverMessage: vscode.MarkdownString = new vscode.MarkdownString(message); hoverMessage.isTrusted = true; return new vscode.Hover(hoverMessage); } else { return undefined; } } public getArtifactsCodeActions(document: vscode.TextDocument, context: vscode.CodeActionContext, _selectRange: vscode.Range): vscode.CodeAction[] | undefined { if (!isJavaExtActivated()) { return undefined; } if (!this.initialized) { this.initialize().catch(); return undefined; } const diagnostics: vscode.Diagnostic[] = context.diagnostics.filter(diagnostic => { return diagnosticIndicatesUnresolvedType(diagnostic, document); }); if (diagnostics.length > 0) { const range: vscode.Range = diagnostics[0].range; const className: string = document.getText(range); const uri: string = document.uri.toString(); const line: number = range.start.line; const character: number = range.start.character; const length: number = document.offsetAt(range.end) - document.offsetAt(range.start); const command: vscode.Command = { title: TITLE_RESOLVE_UNKNOWN_TYPE, command: COMMAND_SEARCH_ARTIFACT, arguments: [{ className, uri: encodeBase64(uri), line, character, length }] }; const codeAction: vscode.CodeAction = { title: `${TITLE_RESOLVE_UNKNOWN_TYPE} '${className}'`, command, kind: vscode.CodeActionKind.QuickFix }; return [codeAction]; } else { return []; } } public async pickAndAddDependency(param: any): Promise<void> { if (!isJavaExtActivated()) { return; } if (!this.initialized) { this.initialize().catch(); return; } const pickItem: vscode.QuickPickItem | undefined = await vscode.window.showQuickPick(getArtifactsPickItems(param.className), { placeHolder: "Select the artifact you want to add" }); if (pickItem === undefined) { return; } param.uri = decodeBase64(param.uri); const edits: vscode.WorkspaceEdit[] = await getWorkSpaceEdits(pickItem, param); await applyEdits(vscode.Uri.parse(param.uri), edits); } } async function getArtifactsPickItems(className: string): Promise<vscode.QuickPickItem[]> { const searchParam: ISearchArtifactParam = { searchType: SearchType.className, className }; const response: IArtifactSearchResult[] = await executeJavaLanguageServerCommand("java.maven.searchArtifact", searchParam); const picks: vscode.QuickPickItem[] = []; for (let i: number = 0; i < Math.min(Math.round(response.length / 5), 5); i += 1) { const arr: string[] = [response[i].groupId, " : ", response[i].artifactId, " : ", response[i].version]; picks.push( { label: `$(thumbsup) ${response[i].className}`, description: response[i].fullClassName, detail: arr.join("") } ); } for (let i: number = Math.min(Math.round(response.length / 5), 5); i < response.length; i += 1) { const arr: string[] = [response[i].groupId, " : ", response[i].artifactId, " : ", response[i].version]; picks.push( { label: response[i].className, description: response[i].fullClassName, detail: arr.join("") } ); } return picks; } async function applyEdits(uri: vscode.Uri, edits: any): Promise<void> { // if the pom is invalid, no change occurs in edits[2] if (Object.keys(edits[2].changes).length > 0) { // 0: import 1: replace await applyWorkspaceEdit(edits[0]); await applyWorkspaceEdit(edits[1]); let document: vscode.TextDocument = await vscode.workspace.openTextDocument(uri); document.save(); // 2: pom if (edits[2].changes[Object.keys(edits[2].changes)[0]].length === 0) { // already has this dependency return; } await applyWorkspaceEdit(edits[2]); document = await vscode.workspace.openTextDocument(vscode.Uri.parse(Object.keys(edits[2].changes)[0])); document.save(); const LINE_OFFSET: number = 1; // tslint:disable-next-line: restrict-plus-operands const startLine: number = edits[2].changes[Object.keys(edits[2].changes)[0]][0].range.start.line + LINE_OFFSET; // skip blank line const lineNumber: number = edits[2].changes[Object.keys(edits[2].changes)[0]][0].newText.indexOf("<dependencies>") === -1 ? 5 : 7; const editor: vscode.TextEditor = await vscode.window.showTextDocument(document, { selection: new vscode.Range(startLine, 0, startLine + lineNumber, 0), preview: false }); editor.revealRange(new vscode.Range(startLine, 0, startLine + lineNumber, 0), vscode.TextEditorRevealType.InCenter); } else { vscode.window.showInformationMessage("Sorry, the pom.xml file is inexistent or invalid."); } } async function getWorkSpaceEdits(pickItem: vscode.QuickPickItem, param: any): Promise<vscode.WorkspaceEdit[]> { return await executeJavaLanguageServerCommand("java.maven.addDependency", pickItem.description, pickItem.detail, param.uri, param.line, param.character, param.length); } function startsWithCapitalLetter(word: string): boolean { return word.charCodeAt(0) >= 65 && word.charCodeAt(0) <= 90; } function diagnosticIndicatesUnresolvedType(diagnostic: vscode.Diagnostic, document: vscode.TextDocument): boolean { return ( UNDEFINED_TYPE === diagnostic.code || UNDEFINED_NAME === diagnostic.code && startsWithCapitalLetter(document.getText(diagnostic.range)) ); } function encodeBase64(content: string): string { return Buffer.from(content, "utf8").toString("base64"); } function decodeBase64(content: string): string { return Buffer.from(content, "base64").toString("utf8"); } export interface IArtifactSearchResult { groupId: string; artifactId: string; version: string; className: string; fullClassName: string; usage: number; kind: number; } export enum SearchType { className = "CLASSNAME", identifier = "IDENTIFIER" } export interface ISearchArtifactParam { searchType: SearchType; className?: string; groupId?: string; artifactId?: string; }
the_stack
/* tslint:disable:no-redundant-jsdoc */ export { }; export enum FileStatus { INIT = 1, IDLE = 2, PROCESSING_QUEUED = 9, PROCESSING = 3, PROCESSING_COMPLETE = 5, PROCESSING_ERROR = 6, PROCESSING_REVERT_ERROR = 10, LOADING = 7, LOAD_ERROR = 8 } export enum Status { EMPTY = 0, IDLE = 1, ERROR = 2, BUSY = 3, READY = 4 } export enum FileOrigin { INPUT = 1, LIMBO = 2, LOCAL = 3 } // TODO replace all references to `ActualFileObject` with native `File` /** * @deprecated Don't use this type explicitly within your code. It'll be replaced with the native `File` type in a future release. */ export type ActualFileObject = Blob & { readonly lastModified: number; readonly name: string; }; /** * A custom FilePond File. */ export class FilePondFile { /** Returns the ID of the file. */ id: string; /** Returns the server id of the file. */ serverId: string; /** Returns the source of the file. */ source: ActualFileObject | string; /** Returns the origin of the file. */ origin: FileOrigin; /** Returns the current status of the file. */ status: FileStatus; /** Returns the File object. */ file: ActualFileObject; /** Returns the file extensions. */ fileExtension: string; /** Returns the size of the file. */ fileSize: number; /** Returns the type of the file. */ fileType: string; /** Returns the full name of the file. */ filename: string; /** Returns the name of the file without extension. */ filenameWithoutExtension: string; /** Aborts loading of this file */ abortLoad: () => void; /** Aborts processing of this file */ abortProcessing: () => void; /** * Retrieve metadata saved to the file, pass a key to retrieve * a specific part of the metadata (e.g. 'crop' or 'resize'). * If no key is passed, the entire metadata object is returned. */ getMetadata: (key?: string) => any; /** Add additional metadata to the file */ setMetadata: (key: string, value: any, silent?: boolean) => void; } // TODO delete /** * A custom FilePond File. Don't confuse this with the native `File` type. * * @deprecated use `FilePondFile` instead. This type will be removed in a future release. */ export class File extends FilePondFile {} export interface ServerUrl { url: string; method?: 'GET' | 'POST' | 'PUT' | 'DELETE'; withCredentials?: boolean; headers?: { [key: string]: string | boolean | number }; timeout?: number; /** * Called when server response is received, useful for getting * the unique file id from the server response. */ onload?: (response: any) => number | string; /** * Called when server error is received, receives the response * body, useful to select the relevant error data. */ onerror?: (responseBody: any) => any; /** * Called with the formdata object right before it is sent, * return extended formdata object to make changes. */ ondata?: (data: FormData) => FormData; } export type ProgressServerConfigFunction = ( /** * Flag indicating if the resource has a length that can be calculated. * If not, the totalDataAmount has no significant value. Setting this to * false switches the FilePond loading indicator to infinite mode. */ isLengthComputable: boolean, /** The amount of data currently transferred. */ loadedDataAmount: number, /** The total amount of data to be transferred. */ totalDataAmount: number, ) => void; export type ProcessServerConfigFunction = ( /** The name of the input field. */ fieldName: string, /** The actual file object to send. */ file: ActualFileObject, metadata: { [key: string]: any }, /** * Should call the load method when done and pass the returned server file id. * This server file id is then used later on when reverting or restoring a file * so that your server knows which file to return without exposing that info * to the client. */ load: (p: string | { [key: string]: any }) => void, /** Call if something goes wrong, will exit after. */ error: (errorText: string) => void, /** * Should call the progress method to update the progress to 100% before calling load(). * Setting computable to false switches the loading indicator to infinite mode. */ progress: ProgressServerConfigFunction, /** Let FilePond know the request has been cancelled. */ abort: () => void ) => void; export type RevertServerConfigFunction = ( /** Server file id of the file to restore. */ uniqueFieldId: any, /** Should call the load method when done. */ load: () => void, /** Call if something goes wrong, will exit after. */ error: (errorText: string) => void ) => void; export type RestoreServerConfigFunction = ( /** Server file id of the file to restore. */ uniqueFileId: any, /** Should call the load method with a file object or blob when done. */ load: (file: ActualFileObject) => void, /** Call if something goes wrong, will exit after. */ error: (errorText: string) => void, /** * Should call the progress method to update the progress to 100% before calling load(). * Setting computable to false switches the loading indicator to infinite mode. */ progress: ProgressServerConfigFunction, /** Let FilePond know the request has been cancelled. */ abort: () => void, /** * Can call the headers method to supply FilePond with early response header string. * https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders */ headers: (headersString: string) => void ) => void; export type LoadServerConfigFunction = ( source: any, /** Should call the load method with a file object or blob when done. */ load: (file: ActualFileObject | Blob) => void, /** Call if something goes wrong, will exit after. */ error: (errorText: string) => void, /** * Should call the progress method to update the progress to 100% before calling load(). * Setting computable to false switches the loading indicator to infinite mode. */ progress: ProgressServerConfigFunction, /** Let FilePond know the request has been cancelled. */ abort: () => void, /** * Can call the headers method to supply FilePond with early response header string. * https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders> */ headers: (headersString: string) => void ) => void; export type FetchServerConfigFunction = ( url: string, /** Should call the load method with a file object or blob when done. */ load: (file: ActualFileObject | Blob) => void, /** Call if something goes wrong, will exit after. */ error: (errorText: string) => void, /** * Should call the progress method to update the progress to 100% before calling load(). * Setting computable to false switches the loading indicator to infinite mode. */ progress: ProgressServerConfigFunction, /** Let FilePond know the request has been cancelled. */ abort: () => void, /** * Can call the headers method to supply FilePond with early response header string. * https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/getAllResponseHeaders */ headers: (headersString: string) => void ) => void; export type RemoveServerConfigFunction = ( /** Local file source */ source: any, /** Call when done */ load: () => void, /** Call if something goes wrong, will exit after. */ error: (errorText: string) => void ) => void; export interface FilePondInitialFile { /** The server file reference. */ source: string; options: { /** Origin of file being added. */ type: 'input' | 'limbo' | 'local'; /** Mock file information. */ file?: { name?: string; size?: number; type?: string; }; /** File initial metadata. */ metadata?: { [key: string]: any }; }; } export interface FilePondServerConfigProps { /** * Immediately upload new files to the server. * @default true */ instantUpload?: boolean; /** * The maximum number of files that can be uploaded in parallel. * @default 2 */ maxParallelUploads?: number; /** * Server API Configuration. * See: https://pqina.nl/filepond/docs/patterns/api/server * @default null */ server?: string | { url?: string timeout?: number headers?: { [key: string]: string | boolean | number }; process?: string | ServerUrl | ProcessServerConfigFunction | null; revert?: string | ServerUrl | RevertServerConfigFunction | null; restore?: string | ServerUrl | RestoreServerConfigFunction | null; load?: string | ServerUrl | LoadServerConfigFunction | null; fetch?: string | ServerUrl | FetchServerConfigFunction | null; remove?: RemoveServerConfigFunction | null; } | null; /** * Enable chunk uploads * @default false */ chunkUploads?: boolean; /** * Force use of chunk uploads even for files smaller than chunk size * @default false */ chunkForce?: boolean; /** * Size of chunks (5MB default) * @default 5000000 */ chunkSize?: number; /** * Amount of times to retry upload of a chunk when it fails * @default [500, 1000, 3000] */ chunkRetryDelays?: number[]; /** * A list of file locations that should be loaded immediately. * See: https://pqina.nl/filepond/docs/patterns/api/filepond-object/#setting-initial-files * @default [] */ files?: Array<FilePondInitialFile | ActualFileObject | Blob | string>; } export interface FilePondDragDropProps { /** * FilePond will catch all files dropped on the webpage. * @default false */ dropOnPage?: boolean; /** * Require drop on the FilePond element itself to catch the file. * @default true */ dropOnElement?: boolean; /** * When enabled, files are validated before they are dropped. * A file is not added when it’s invalid. * @default false */ dropValidation?: boolean; /** * Ignored file names when handling dropped directories. * Dropping directories is not supported on all browsers. * @default ['.ds_store', 'thumbs.db', 'desktop.ini'] */ ignoredFiles?: string[]; } export interface FilePondLabelProps { /** * The decimal separator used to render numbers. * By default this is determined automatically. * @default 'auto' */ labelDecimalSeparator?: string; /** * The thousands separator used to render numbers. * By default this is determined automatically. * @default 'auto' */ labelThousandsSeparator?: string; /** * Default label shown to indicate this is a drop area. * FilePond will automatically bind browse file events to * the element with CSS class .filepond--label-action. * @default 'Drag & Drop your files or <span class="filepond--label-action"> Browse </span>' */ labelIdle?: string; /** * Label shown when the field contains invalid files and is validated by the parent form. * @default 'Field contains invalid files' */ labelInvalidField?: string; /** * Label used while waiting for file size information. * @default 'Waiting for size' */ labelFileWaitingForSize?: string; /** * Label used when no file size information was received. * @default 'Size not available' */ labelFileSizeNotAvailable?: string; /** * Label used when showing the number of files and there is only one. * @default 'file in list' */ labelFileCountSingular?: string; /** * Label used when showing the number of files and there is more than one. * @default 'files in list' */ labelFileCountPlural?: string; /** * Label used while loading a file. * @default 'Loading' */ labelFileLoading?: string; /** * Label used when file is added (assistive only). * @default 'Added' */ labelFileAdded?: string; /** * Label used when file load failed. * @default 'Error during load' */ labelFileLoadError?: ((error: any) => string) | string; /** * Label used when file is removed (assistive only). * @default 'Removed' */ labelFileRemoved?: string; /** * Label used when something went during during removing the file upload. * @default 'Error during remove' */ labelFileRemoveError?: ((error: any) => string) | string; /** * Label used when uploading a file. * @default 'Uploading' */ labelFileProcessing?: string; /** * Label used when file upload has completed. * @default 'Upload complete' */ labelFileProcessingComplete?: string; /** * Label used when upload was cancelled. * @default 'Upload cancelled' */ labelFileProcessingAborted?: string; /** * Label used when something went wrong during file upload. * @default 'Error during upload' */ labelFileProcessingError?: ((error: any) => string) | string; /** * Label used when something went wrong during reverting the file upload. * @default 'Error during revert' */ labelFileProcessingRevertError?: ((error: any) => string) | string; /** * Label used to indicate to the user that an action can be cancelled. * @default 'tap to cancel' */ labelTapToCancel?: string; /** * Label used to indicate to the user that an action can be retried. * @default 'tap to retry' */ labelTapToRetry?: string; /** * Label used to indicate to the user that an action can be undone. * @default 'tap to undo' */ labelTapToUndo?: string; /** * Label used for remove button. * @default 'Remove' */ labelButtonRemoveItem?: string; /** * Label used for abort load button. * @default 'Abort' */ labelButtonAbortItemLoad?: string; /** * Label used for retry load. * @default 'Retry' */ labelButtonRetryItemLoad?: string; /** * Label used for abort upload button. * @default 'Cancel' */ labelButtonAbortItemProcessing?: string; /** * Label used for undo upload button. * @default 'Undo' */ labelButtonUndoItemProcessing?: string; /** * Label used for retry upload button. * @default 'Retry' */ labelButtonRetryItemProcessing?: string; /** * Label used for upload button. * @default 'Upload' */ labelButtonProcessItem?: string; } export interface FilePondSvgIconProps { /** * The icon used for remove actions. * @default '<svg></svg>' */ iconRemove?: string; /** * The icon used for process actions. * @default '<svg></svg>' */ iconProcess?: string; /** * The icon used for retry actions. * @default '<svg></svg>' */ iconRetry?: string; /** * The icon used for undo actions. * @default '<svg></svg>' */ iconUndo?: string; /** * The icon used for done. * @default '<svg></svg>' */ iconDone?: string; } export interface FilePondErrorDescription { type: string; code: number; body: string; } export interface FilePondCallbackProps { /** FilePond instance has been created and is ready. */ oninit?: () => void; /** * FilePond instance throws a warning. For instance * when the maximum amount of files has been reached. * Optionally receives file if error is related to a * file object. */ onwarning?: (error: any, file?: FilePondFile, status?: any) => void; /** * FilePond instance throws an error. Optionally receives * file if error is related to a file object. */ onerror?: (error: FilePondErrorDescription, file?: FilePondFile, status?: any) => void; /** Started file load. */ onaddfilestart?: (file: FilePondFile) => void; /** Made progress loading a file. */ onaddfileprogress?: (file: FilePondFile, progress: number) => void; /** If no error, file has been successfully loaded. */ onaddfile?: (error: FilePondErrorDescription | null, file: FilePondFile) => void; /** Started processing a file. */ onprocessfilestart?: (file: FilePondFile) => void; /** Made progress processing a file. */ onprocessfileprogress?: (file: FilePondFile, progress: number) => void; /** Aborted processing of a file. */ onprocessfileabort?: (file: FilePondFile) => void; /** Processing of a file has been reverted. */ onprocessfilerevert?: (file: FilePondFile) => void; /** If no error, Processing of a file has been completed. */ onprocessfile?: (error: FilePondErrorDescription | null, file: FilePondFile) => void; /** Called when all files in the list have been processed. */ onprocessfiles?: () => void; /** File has been removed. */ onremovefile?: (error: FilePondErrorDescription | null, file: FilePondFile) => void; /** * File has been transformed by the transform plugin or * another plugin subscribing to the prepare_output filter. * It receives the file item and the output data. */ onpreparefile?: (file: FilePondFile, output: any) => void; /** A file has been added or removed, receives a list of file items. */ onupdatefiles?: (files: FilePondFile[]) => void; /* Called when a file is clicked or tapped. **/ onactivatefile?: (file: FilePondFile) => void; /** Called when the files have been reordered */ onreorderfiles?: (files: FilePondFile[]) => void; } export interface FilePondHookProps { /** * FilePond is about to allow this item to be dropped, it can be a URL or a File object. * * Return `true` or `false` depending on if you want to allow the item to be dropped. */ beforeDropFile?: (file: FilePondFile | string) => boolean; /** * FilePond is about to add this file. * * Return `false` to prevent adding it, or return a `Promise` and resolve with `true` or `false`. */ beforeAddFile?: (item: FilePondFile) => boolean | Promise<boolean>; /** * FilePond is about to remove this file. * * Return `false` to prevent adding it, or return a `Promise` and resolve with `true` or `false`. */ beforeRemoveFile?: (item: FilePondFile) => boolean | Promise<boolean>; } export interface FilePondStyleProps { /** * Set a different layout render mode. * @default null */ stylePanelLayout?: 'integrated' | 'compact' | 'circle' | 'integrated circle' | 'compact circle' | null; /** * Set a forced aspect ratio for the FilePond drop area. * * Accepts human readable aspect ratios like `1:1` or numeric aspect ratios like `0.75`. * @default null */ stylePanelAspectRatio?: string | null; /** * Set a forced aspect ratio for the file items. * * Useful when rendering cropped or fixed aspect ratio images in grid view. * @default null */ styleItemPanelAspectRatio?: string | null; /** * The position of the remove item button. * @default 'left' */ styleButtonRemoveItemPosition?: string; /** * The position of the remove item button. * @default 'right' */ styleButtonProcessItemPosition?: string; /** * The position of the load indicator. * @default 'right' */ styleLoadIndicatorPosition?: string; /** * The position of the progress indicator. * @default 'right' */ styleProgressIndicatorPosition?: string; /** * Enable to align the remove button to the left side of the file item. * @default false */ styleButtonRemoveItemAlign?: boolean; } export type CaptureAttribute = "camera" | "microphone" | "camcorder"; export interface FilePondBaseProps { /** * The ID to add to the root element. * @default null */ id?: string | null; /** * The input field name to use. * @default 'filepond' */ name?: string; /** * Class Name to put on wrapper. * @default null */ className?: string | null; /** * Sets the required attribute to the output field. * @default false */ required?: boolean; /** * Sets the disabled attribute to the output field. * @default false */ disabled?: boolean; /** * Sets the given value to the capture attribute. * @default null */ captureMethod?: CaptureAttribute | null; /** * Set to false to prevent FilePond from setting the file input field `accept` attribute to the value of the `acceptedFileTypes`. */ allowSyncAcceptAttribute?: boolean; /** * Enable or disable drag n’ drop. * @default true */ allowDrop?: boolean; /** * Enable or disable file browser. * @default true */ allowBrowse?: boolean; /** * Enable or disable pasting of files. Pasting files is not * supported on all browsers. * @default true */ allowPaste?: boolean; /** * Enable or disable adding multiple files. * @default false */ allowMultiple?: boolean; /** * Allow drop to replace a file, only works when allowMultiple is false. * @default true */ allowReplace?: boolean; /** * Allows the user to revert file upload. * @default true */ allowRevert?: boolean; /** * Allows user to process a file. When set to false, this removes the file upload button. * @default true */ allowProcess?: boolean; /** * Allows the user to reorder the file items * @default false */ allowReorder?: boolean; /** * Allow only selecting directories with browse (no support for filtering dnd at this point) * @default false */ allowDirectoriesOnly?: boolean; /** * Require the file to be successfully reverted before continuing. * @default false */ forceRevert?: boolean; /** * The maximum number of files that filepond pond can handle. * @default null */ maxFiles?: number | null; /** * Enables custom validity messages. * @default false */ checkValidity?: boolean; /** * Set to false to always add items to beginning or end of list. * @default true */ itemInsertLocationFreedom?: boolean; /** * Default index in list to add items that have been dropped at the top of the list. * @default 'before' */ itemInsertLocation?: 'before' | 'after' | ((a: FilePondFile, b: FilePondFile) => number); /** * The interval to use before showing each item being added to the list. * @default 75 */ itemInsertInterval?: number; /** * The base value used to calculate file size * @default 1000 */ fileSizeBase?: number; } // TODO delete /** * @deprecated use `FilePondOptions`. This will be removed in a future release. */ export interface FilePondOptionProps extends FilePondDragDropProps, FilePondServerConfigProps, FilePondLabelProps, FilePondSvgIconProps, FilePondCallbackProps, FilePondHookProps, FilePondStyleProps, FilePondBaseProps { } export interface FilePondOptions extends FilePondDragDropProps, FilePondServerConfigProps, FilePondLabelProps, FilePondSvgIconProps, FilePondCallbackProps, FilePondHookProps, FilePondStyleProps, FilePondBaseProps { } export type FilePondEventPrefixed = 'FilePond:init' | 'FilePond:warning' | 'FilePond:error' | 'FilePond:addfilestart' | 'FilePond:addfileprogress' | 'FilePond:addfile' | 'FilePond:processfilestart' | 'FilePond:processfileprogress' | 'FilePond:processfileabort' | 'FilePond:processfilerevert' | 'FilePond:processfile' | 'FilePond:removefile' | 'FilePond:updatefiles' | 'FilePond:reorderfiles'; export type FilePondEvent = 'init' | 'warning' | 'error' | 'addfilestart' | 'addfileprogress' | 'addfile' | 'processfilestart' | 'processfileprogress' | 'processfileabort' | 'processfilerevert' | 'processfile' | 'removefile' | 'updatefiles' | 'reorderfiles'; export interface RemoveFileOptions { remove?: boolean; revert?: boolean; } export interface FilePond extends Required<FilePondOptions> {} export class FilePond { /** * The root element of the Filepond instance. */ readonly element: Element | null; /** * Returns the current status of the FilePond instance. * @default Status.EMPTY */ readonly status: Status; /** Override multiple options at once. */ setOptions(options: FilePondOptions): void; /** * Adds a file. * @param options.index The index that the file should be added at. */ addFile(source: ActualFileObject | Blob | string, options?: { index?: number } & Partial<FilePondInitialFile["options"]>): Promise<FilePondFile>; /** * Adds multiple files. * @param options.index The index that the files should be added at. */ addFiles(source: ActualFileObject[] | Blob[] | string[], options?: { index: number }): Promise<FilePondFile[]>; /** * Moves a file. Select file with query and supply target index. * @param query The file reference, id, or index. * @param index The index to move the file to. */ moveFile(query: FilePondFile | string | number, index: number): void; /** * Removes a file. * @param query The file reference, id, or index. If no query is provided, removes the first file in the list. * @param options Options for removal */ removeFile(query?: FilePondFile | string | number, options?: RemoveFileOptions): void; /** * Removes the first file in the list. * @param options Options for removal */ removeFile(options: RemoveFileOptions): void; /** * Removes files matching the query. * @param query Array containing file references, ids, and/or indexes. If no array is provided, all files are removed * @param options Options for removal */ removeFiles(query?: Array<FilePondFile | string | number>, options?: RemoveFileOptions): void; /** * Removes all files. * @param options Options for removal */ removeFiles(options: RemoveFileOptions): void; /** * Processes a file. If no parameter is provided, processes the first file in the list. * @param query The file reference, id, or index */ processFile(query?: FilePondFile | string | number): Promise<FilePondFile>; /** * Processes multiple files. If no parameter is provided, processes all files. * @param query The file reference(s), id(s), or index(es) */ processFiles(query?: FilePondFile[] | string[] | number[]): Promise<FilePondFile[]>; /** * Starts preparing the file matching the given query, returns a Promise, the Promise is resolved with the file item and the output file { file, output } * @param query The file reference, id, or index */ prepareFile(query?: FilePondFile | string | number): Promise<{file: FilePondFile, output: any}>; /** * Processes multiple files. If no parameter is provided, processes all files. * @param query Array containing file reference(s), id(s), or index(es) */ prepareFiles(query?: FilePondFile[] | string[] | number[]): Promise<Array<{file: FilePondFile, output: any}>>; /** * Returns a file. If no parameter is provided, returns the first file in the list. * @param query The file id, or index */ getFile(query?: string | number): FilePondFile; /** Returns all files. */ getFiles(): FilePondFile[]; /** * Manually trigger the browse files panel. * * Only works if the call originates from the user. */ browse(): void; /** * Sort the items in the files list. * @param compare The comparison function */ sort(compare: (a: FilePondFile, b: FilePondFile) => number): void; /** Destroys this FilePond instance. */ destroy(): void; /** Inserts the FilePond instance after the supplied element. */ insertAfter(element: Element): void; /** Inserts the FilePond instance before the supplied element. */ insertBefore(element: Element): void; /** Appends FilePond to the given element. */ appendTo(element: Element): void; /** Returns true if the current instance is attached to the supplied element. */ isAttachedTo(element: Element): void; /** Replaces the supplied element with FilePond. */ replaceElement(element: Element): void; /** If FilePond replaced the original element, this restores the original element to its original glory. */ restoreElement(element: Element): void; /** * Adds an event listener to the given event. * @param event Name of the event, prefixed with `Filepond:` * @param fn Event handler */ addEventListener(event: FilePondEventPrefixed, fn: (e: any) => void): void; /** * Listen to an event. * @param event Name of the event * @param fn Event handler, signature is identical to the callback method */ on(event: FilePondEvent, fn: (...args: any[]) => void): void; /** * Listen to an event once and remove the handler. * @param event Name of the event * @param fn Event handler, signature is identical to the callback method */ onOnce(event: FilePondEvent, fn: (...args: any[]) => void): void; /** * Stop listening to an event. * @param event Name of the event * @param fn Event handler, signature is identical to the callback method */ off(event: FilePondEvent, fn: (...args: any[]) => void): void; } /** Creates a new FilePond instance. */ export function create(element?: Element, options?: FilePondOptions): FilePond; /** Destroys the FilePond instance attached to the supplied element. */ export function destroy(element: Element): void; /** Returns the FilePond instance attached to the supplied element. */ export function find(element: Element): FilePond; /** * Parses a given section of the DOM tree for elements with class * .filepond and turns them into FilePond elements. */ export function parse(context: Element): void; /** Registers a FilePond plugin for later use. */ export function registerPlugin(...plugins: any[]): void; /** Sets page level default options for all FilePond instances. */ export function setOptions(options: FilePondOptions): void; /** Returns the current default options. */ export function getOptions(): FilePondOptions; /** Determines whether or not the browser supports FilePond. */ export function supported(): boolean; /** Returns an object describing all the available options and their types, useful for writing FilePond adapters. */ export const OptionTypes: object;
the_stack
import { getVoidLogger } from '@backstage/backend-common'; import { Entity, LOCATION_ANNOTATION } from '@backstage/catalog-model'; import { Database, DatabaseManager, Transaction } from '../database'; import { basicEntityFilter } from '../../service/request'; import { DatabaseEntitiesCatalog } from './DatabaseEntitiesCatalog'; import { EntityUpsertRequest } from '../../catalog/types'; describe('DatabaseEntitiesCatalog', () => { let db: jest.Mocked<Database>; let transaction: jest.Mocked<Transaction>; beforeAll(() => { db = { transaction: jest.fn(), addEntities: jest.fn(), updateEntity: jest.fn(), entities: jest.fn(), entityByName: jest.fn(), entityByUid: jest.fn(), removeEntityByUid: jest.fn(), setRelations: jest.fn(), addLocation: jest.fn(), removeLocation: jest.fn(), location: jest.fn(), locations: jest.fn(), locationHistory: jest.fn(), addLocationUpdateLogEvent: jest.fn(), }; transaction = { rollback: jest.fn(), }; }); beforeEach(() => { jest.resetAllMocks(); db.transaction.mockImplementation(async f => f(transaction)); }); describe('batchAddOrUpdateEntities', () => { it('adds when no given uid and no matching by name', async () => { const entity: Entity = { apiVersion: 'a', kind: 'b', metadata: { name: 'c', namespace: 'd', }, }; db.entities.mockResolvedValue({ entities: [], pageInfo: { hasNextPage: false }, }); db.addEntities.mockResolvedValue([ { entity: { ...entity, metadata: { ...entity.metadata, uid: 'u' } } }, ]); const catalog = new DatabaseEntitiesCatalog(db, getVoidLogger()); const result = await catalog.batchAddOrUpdateEntities([ { entity, relations: [] }, ]); expect(db.entities).toHaveBeenCalledTimes(1); expect(db.entities).toHaveBeenCalledWith(expect.anything(), { filter: basicEntityFilter({ kind: 'b', 'metadata.namespace': 'd', 'metadata.name': 'c', }), }); expect(db.addEntities).toHaveBeenCalledTimes(1); expect(db.addEntities).toHaveBeenCalledWith(expect.anything(), [ { entity: expect.anything(), relations: [] }, ]); expect(result).toEqual([{ entityId: 'u' }]); }); it('dry run of add operation', async () => { const entity: Entity = { apiVersion: 'a', kind: 'b', metadata: { name: 'c', namespace: 'd', }, }; db.entities.mockResolvedValue({ entities: [], pageInfo: { hasNextPage: false }, }); db.addEntities.mockResolvedValue([ { entity: { ...entity, metadata: { ...entity.metadata, uid: 'u' } } }, ]); const catalog = new DatabaseEntitiesCatalog(db, getVoidLogger()); const result = await catalog.batchAddOrUpdateEntities( [{ entity, relations: [] }], { dryRun: true }, ); expect(db.entities).toHaveBeenCalledTimes(1); expect(db.entities).toHaveBeenCalledWith(expect.anything(), { filter: basicEntityFilter({ kind: 'b', 'metadata.namespace': 'd', 'metadata.name': 'c', }), }); expect(db.addEntities).toHaveBeenCalledTimes(1); expect(db.addEntities).toHaveBeenCalledWith(expect.anything(), [ { entity: expect.anything(), relations: [] }, ]); expect(transaction.rollback).toBeCalledTimes(1); expect(result).toEqual([{ entityId: 'u' }]); }); it('output modified entities', async () => { const entity: Entity = { apiVersion: 'a', kind: 'b', metadata: { name: 'c', namespace: 'd', annotations: { [LOCATION_ANNOTATION]: 'mock', }, }, }; const dbEntity: Entity = { apiVersion: 'a', kind: 'b', metadata: { name: 'c', namespace: 'd', description: 'changes', uid: 'u', annotations: { [LOCATION_ANNOTATION]: 'mock', }, }, }; db.entities.mockResolvedValue({ entities: [{ entity: dbEntity }], pageInfo: { hasNextPage: false }, }); db.addEntities.mockResolvedValue([ { entity: { ...entity, metadata: { ...entity.metadata, uid: 'u' } } }, ]); const catalog = new DatabaseEntitiesCatalog(db, getVoidLogger()); const result = await catalog.batchAddOrUpdateEntities( [{ entity, relations: [] }], { outputEntities: true }, ); expect(db.entities).toHaveBeenCalledTimes(2); expect(db.addEntities).toHaveBeenCalledTimes(1); expect(result).toEqual([ { entityId: 'u', entity: dbEntity, }, ]); }); it('updates when given uid', async () => { const entity: Entity = { apiVersion: 'a', kind: 'b', metadata: { uid: 'u', name: 'c', namespace: 'd', }, spec: { x: 'b', }, }; const existing = { entity: { apiVersion: 'a', kind: 'b', metadata: { uid: 'u', etag: 'e', generation: 1, name: 'c', namespace: 'd', }, spec: { x: 'a', }, }, }; db.entities.mockResolvedValue({ entities: [existing], pageInfo: { hasNextPage: false }, }); db.entityByUid.mockResolvedValue(existing); db.updateEntity.mockResolvedValue({ entity }); const catalog = new DatabaseEntitiesCatalog(db, getVoidLogger()); const result = await catalog.batchAddOrUpdateEntities([ { entity, relations: [] }, ]); expect(db.entities).toHaveBeenCalledTimes(1); expect(db.entities).toHaveBeenCalledWith(expect.anything(), { filter: basicEntityFilter({ kind: 'b', 'metadata.namespace': 'd', 'metadata.name': 'c', }), }); expect(db.entityByName).not.toHaveBeenCalled(); expect(db.entityByUid).toHaveBeenCalledTimes(1); expect(db.entityByUid).toHaveBeenCalledWith(transaction, 'u'); expect(db.updateEntity).toHaveBeenCalledTimes(1); expect(db.updateEntity).toHaveBeenCalledWith( transaction, { entity: { apiVersion: 'a', kind: 'b', metadata: { uid: 'u', etag: expect.any(String), generation: 2, name: 'c', namespace: 'd', }, spec: { x: 'b', }, }, relations: [], }, 'e', 1, ); expect(result).toEqual([{ entityId: 'u' }]); }); it('update when no given uid and matching by name', async () => { const added: Entity = { apiVersion: 'a', kind: 'b', metadata: { name: 'c', namespace: 'd', }, spec: { x: 'b', }, }; const existing = { entity: { apiVersion: 'a', kind: 'b', metadata: { uid: 'u', etag: 'e', generation: 1, name: 'c', namespace: 'd', }, spec: { x: 'a', }, }, }; db.entities.mockResolvedValue({ entities: [existing], pageInfo: { hasNextPage: false }, }); db.entityByName.mockResolvedValue(existing); db.updateEntity.mockResolvedValue(existing); const catalog = new DatabaseEntitiesCatalog(db, getVoidLogger()); const result = await catalog.batchAddOrUpdateEntities([ { entity: added, relations: [] }, ]); expect(db.entities).toHaveBeenCalledTimes(1); expect(db.entities).toHaveBeenCalledWith(expect.anything(), { filter: basicEntityFilter({ kind: 'b', 'metadata.namespace': 'd', 'metadata.name': 'c', }), }); expect(db.entityByName).toHaveBeenCalledTimes(1); expect(db.entityByName).toHaveBeenCalledWith(transaction, { kind: 'b', namespace: 'd', name: 'c', }); expect(db.updateEntity).toHaveBeenCalledTimes(1); expect(db.updateEntity).toHaveBeenCalledWith( transaction, { entity: { apiVersion: 'a', kind: 'b', metadata: { uid: 'u', etag: expect.any(String), generation: 2, name: 'c', namespace: 'd', }, spec: { x: 'b', }, }, relations: [], }, 'e', 1, ); expect(result).toEqual([{ entityId: 'u' }]); }); it('should not update if entity is unchanged', async () => { const entity: Entity = { apiVersion: 'a', kind: 'b', metadata: { uid: 'u', name: 'c', namespace: 'd', }, spec: { x: 'a', }, }; db.entities.mockResolvedValue({ entities: [{ entity }], pageInfo: { hasNextPage: false }, }); db.entityByUid.mockResolvedValue({ entity }); db.updateEntity.mockResolvedValue({ entity }); const catalog = new DatabaseEntitiesCatalog(db, getVoidLogger()); const result = await catalog.batchAddOrUpdateEntities([ { entity, relations: [] }, ]); expect(db.entities).toHaveBeenCalledTimes(1); expect(db.entities).toHaveBeenCalledWith(expect.anything(), { filter: basicEntityFilter({ kind: 'b', 'metadata.namespace': 'd', 'metadata.name': 'c', }), }); expect(db.entityByName).not.toHaveBeenCalled(); expect(db.entityByUid).not.toHaveBeenCalled(); expect(db.updateEntity).not.toHaveBeenCalled(); expect(db.setRelations).toHaveBeenCalledTimes(1); expect(db.setRelations).toHaveBeenCalledWith(expect.anything(), 'u', []); expect(result).toEqual([{ entityId: 'u' }]); }); it('both adds and updates', async () => { const catalog = new DatabaseEntitiesCatalog( await DatabaseManager.createTestDatabase(), getVoidLogger(), ); const entities: EntityUpsertRequest[] = []; for (let i = 0; i < 300; ++i) { entities.push({ entity: { apiVersion: 'a', kind: 'k', metadata: { name: `n${i}` }, }, relations: [], }); } await catalog.batchAddOrUpdateEntities(entities); const afterFirst = await catalog.entities(); expect(afterFirst.entities.length).toBe(300); entities[40].entity.metadata.op = 'changed'; entities.push({ entity: { apiVersion: 'a', kind: 'k', metadata: { name: `n300`, op: 'added' }, }, relations: [], }); await catalog.batchAddOrUpdateEntities(entities); const afterSecond = await catalog.entities(); expect(afterSecond.entities.length).toBe(301); expect( afterSecond.entities.find(e => e.metadata.op === 'changed'), ).toBeDefined(); expect( afterSecond.entities.find(e => e.metadata.op === 'added'), ).toBeDefined(); }, 10000); }); });
the_stack
/// <reference types="@stdlib/types"/> import { ndarray } from '@stdlib/types/ndarray'; import { ArrayLike } from '@stdlib/types/array'; import dispatch = require( './index' ); // FUNCTIONS // /** * Nullary callback. * * @return input value */ function nullary(): any { return 5.0; } /** * Unary callback. * * @param x - input value * @return input value */ function unary( x: any ): any { return x; } /** * Binary callback. * * @param x - input value * @param y - input value * @return output value */ function binary( x: number, y: number ): number { return x + y; } /** * Ternary callback. * * @param x - input value * @param y - input value * @param z - input value * @return output value */ function ternary( x: number, y: number, z: number ): number { return x + y + z; } /** * Quaternary callback. * * @param x - input value * @param y - input value * @param z - input value * @param w - input value * @return output value */ function quaternary( x: number, y: number, z: number, w: number ): number { return x + y + z + w; } /** * Mock `ind2sub` function. * * @param shape - dimensions * @param idx - linear index * @param opts - options * @return subscripts */ function ind2sub( shape: ArrayLike<number>, idx: number, opts?: any ): Array<number> { // tslint:disable-line:max-line-length let out; let i; out = []; if ( typeof opts === 'object' && opts !== null && opts.order === 'row-major' ) { // tslint:disable-line:max-line-length no-unsafe-any for ( i = 0; i < shape.length; i += 1 ) { out.push( idx % shape[ i ] ); } } else { for ( i = 0; i < shape.length; i += 1 ) { out.push( idx % shape[ i ] ); } } return out; } /** * Mock ndarray function. * * @param arrays - ndarrays * @param fcn - callback */ function ndarrayFcn( arrays: Array<ndarray>, fcn: ( x: any ) => any ): void { let xord; let yord; let opts; let sub; let sh; let N; let x; let y; let v; let i; x = arrays[ 0 ]; y = arrays[ 1 ]; sh = x.shape; if ( sh.length === 0 ) { return; } N = 1; for ( i = 0; i < sh.length; i += 1 ) { N *= sh[ i ]; } xord = x.order; yord = y.order; opts = { 'order': '' }; opts.order = xord; for ( i = 0; i < N; i += 1 ) { // Convert a linear index to subscripts: opts.order = xord; sub = ind2sub( sh, i, opts ); // Retrieve an element from `x`: v = x.get.apply( x, sub ); // Convert a linear index to subscripts: opts.order = yord; sub = ind2sub( sh, i, opts ); // Append the result of applying the callback: sub[ sub.length ] = fcn( v ) as number; // Assign the result to an element in `y`: y.set.apply( y, sub ); } } /** * Mock function to create an ndarray-like object. * * @return ndarray-like object */ function array(): ndarray { const obj: ndarray = { 'byteLength': 80, 'BYTES_PER_ELEMENT': 8, 'data': new Float64Array( 10 ), 'dtype': 'float64', 'flags': { 'ROW_MAJOR_CONTIGUOUS': true, 'COLUMN_MAJOR_CONTIGUOUS': false }, 'length': 10, 'ndims': 1, 'offset': 0, 'order': 'row-major', 'shape': [ 10 ], 'strides': [ 1 ], 'get': (): number => 0, 'set': (): ndarray => obj }; return obj; } // TESTS // // The function returns a dispatch function... { const types = [ 'float64', 'float64' ]; const data = [ unary ]; dispatch( ndarrayFcn, types, data, 2, 1, 1 ); // $ExpectType Dispatcher dispatch( [ ndarrayFcn ], types, data, 2, 1, 1 ); // $ExpectType Dispatcher } // The compiler throws an error if the function is provided a first argument which is not either an ndarray function or an array-like object containing ndarray functions... { const types = [ 'float64', 'float64' ]; const data = [ unary ]; dispatch( '10', types, data, 2, 1, 1 ); // $ExpectError dispatch( 10, types, data, 2, 1, 1 ); // $ExpectError dispatch( true, types, data, 2, 1, 1 ); // $ExpectError dispatch( false, types, data, 2, 1, 1 ); // $ExpectError dispatch( null, types, data, 2, 1, 1 ); // $ExpectError dispatch( undefined, types, data, 2, 1, 1 ); // $ExpectError dispatch( [ '1' ], types, data, 2, 1, 1 ); // $ExpectError dispatch( {}, types, data, 2, 1, 1 ); // $ExpectError dispatch( ( x: number ): number => x, types, data, 2, 1, 1 ); // $ExpectError } // The compiler throws an error if the function is provided a second argument which is not an array-like object... { const data = [ unary ]; dispatch( ndarrayFcn, 10, data, 2, 1, 1 ); // $ExpectError dispatch( ndarrayFcn, true, data, 2, 1, 1 ); // $ExpectError dispatch( ndarrayFcn, false, data, 2, 1, 1 ); // $ExpectError dispatch( ndarrayFcn, null, data, 2, 1, 1 ); // $ExpectError dispatch( ndarrayFcn, undefined, data, 2, 1, 1 ); // $ExpectError dispatch( ndarrayFcn, {}, data, 2, 1, 1 ); // $ExpectError } // The compiler throws an error if the function is provided a third argument which is not an array-like object or null... { const types = [ 'float64', 'float64' ]; dispatch( ndarrayFcn, types, 10, 2, 1, 1 ); // $ExpectError dispatch( ndarrayFcn, types, true, 2, 1, 1 ); // $ExpectError dispatch( ndarrayFcn, types, false, 2, 1, 1 ); // $ExpectError dispatch( ndarrayFcn, types, undefined, 2, 1, 1 ); // $ExpectError dispatch( ndarrayFcn, types, {}, 2, 1, 1 ); // $ExpectError } // The compiler throws an error if the function is provided a fourth argument which is not a number... { const types = [ 'float64', 'float64' ]; const data = [ unary ]; dispatch( ndarrayFcn, types, data, '10', 1, 1 ); // $ExpectError dispatch( ndarrayFcn, types, data, true, 1, 1 ); // $ExpectError dispatch( ndarrayFcn, types, data, false, 1, 1 ); // $ExpectError dispatch( ndarrayFcn, types, data, null, 1, 1 ); // $ExpectError dispatch( ndarrayFcn, types, data, undefined, 1, 1 ); // $ExpectError dispatch( ndarrayFcn, types, data, [ '1' ], 1, 1 ); // $ExpectError dispatch( ndarrayFcn, types, data, {}, 1, 1 ); // $ExpectError dispatch( ndarrayFcn, types, data, ( x: number ): number => x, 1, 1 ); // $ExpectError } // The compiler throws an error if the function is provided a fifth argument which is not a number... { const types = [ 'float64', 'float64' ]; const data = [ unary ]; dispatch( ndarrayFcn, types, data, 2, '10', 1 ); // $ExpectError dispatch( ndarrayFcn, types, data, 2, true, 1 ); // $ExpectError dispatch( ndarrayFcn, types, data, 2, false, 1 ); // $ExpectError dispatch( ndarrayFcn, types, data, 2, null, 1 ); // $ExpectError dispatch( ndarrayFcn, types, data, 2, undefined, 1 ); // $ExpectError dispatch( ndarrayFcn, types, data, 2, [ '1' ], 1 ); // $ExpectError dispatch( ndarrayFcn, types, data, 2, {}, 1 ); // $ExpectError dispatch( ndarrayFcn, types, data, 2, ( x: number ): number => x, 1 ); // $ExpectError } // The compiler throws an error if the function is provided a sixth argument which is not a number... { const types = [ 'float64', 'float64' ]; const data = [ unary ]; dispatch( ndarrayFcn, types, data, 2, 1, '10' ); // $ExpectError dispatch( ndarrayFcn, types, data, 2, 1, true ); // $ExpectError dispatch( ndarrayFcn, types, data, 2, 1, false ); // $ExpectError dispatch( ndarrayFcn, types, data, 2, 1, null ); // $ExpectError dispatch( ndarrayFcn, types, data, 2, 1, undefined ); // $ExpectError dispatch( ndarrayFcn, types, data, 2, 1, [ '1' ] ); // $ExpectError dispatch( ndarrayFcn, types, data, 2, 1, {} ); // $ExpectError dispatch( ndarrayFcn, types, data, 2, 1, ( x: number ): number => x ); // $ExpectError } // The compiler throws an error if the function is provided an unsupported number of arguments... { const types = [ 'float64', 'float64' ]; const data = [ unary ]; dispatch(); // $ExpectError dispatch( ndarrayFcn ); // $ExpectError dispatch( ndarrayFcn, types ); // $ExpectError dispatch( ndarrayFcn, types, data ); // $ExpectError dispatch( ndarrayFcn, types, data, 2 ); // $ExpectError dispatch( ndarrayFcn, types, data, 2, 1 ); // $ExpectError dispatch( ndarrayFcn, types, data, 2, 1, 1, 0 ); // $ExpectError } // The function returns a dispatch function... { const x = array(); const y = array(); const z = array(); const w = array(); const u = array(); const t1 = [ 'float64' ]; const d1 = [ nullary ]; const f1 = dispatch( ndarrayFcn, t1, d1, 1, 1, 0 ); f1( x ); // $ExpectType void | ndarray const t2 = [ 'float64', 'float64' ]; const d2 = [ unary ]; const f2 = dispatch( ndarrayFcn, t2, d2, 2, 1, 1 ); f2( x, y ); // $ExpectType void | ndarray const t3 = [ 'float64', 'float64', 'float64' ]; const d3 = [ binary ]; const f3 = dispatch( ndarrayFcn, t3, d3, 3, 2, 1 ); f3( x, y, z ); // $ExpectType void | ndarray const t4 = [ 'float64', 'float64', 'float64', 'float64' ]; const d4 = [ ternary ]; const f4 = dispatch( ndarrayFcn, t4, d4, 4, 3, 1 ); f4( x, y, z, w ); // $ExpectType void | ndarray const t5 = [ 'float64', 'float64', 'float64', 'float64', 'float64' ]; const d5 = [ quaternary ]; const f5 = dispatch( ndarrayFcn, t5, d5, 5, 4, 1 ); f5( x, y, z, w, u ); // $ExpectType void | ndarray } // The compiler throws an error if the returned function is provided a first argument which is not an ndarray (1 ndarray)... { const types = [ 'float64' ]; const data = [ nullary ]; const f = dispatch( ndarrayFcn, types, data, 1, 0, 1 ); f( '10' ); // $ExpectError f( 10 ); // $ExpectError f( true ); // $ExpectError f( false ); // $ExpectError f( null ); // $ExpectError f( undefined ); // $ExpectError f( [ '1' ] ); // $ExpectError f( {} ); // $ExpectError f( ( x: number ): number => x ); // $ExpectError } // The compiler throws an error if the returned function is provided a first argument which is not an ndarray (2 ndarrays)... { const types = [ 'float64', 'float64' ]; const data = [ unary ]; const y = array(); const f = dispatch( ndarrayFcn, types, data, 2, 1, 1 ); f( 10, y ); // $ExpectError f( '10', y ); // $ExpectError f( true, y ); // $ExpectError f( false, y ); // $ExpectError f( null, y ); // $ExpectError f( undefined, y ); // $ExpectError f( [ '1' ], y ); // $ExpectError f( {}, y ); // $ExpectError f( ( x: number ): number => x, y ); // $ExpectError } // The compiler throws an error if the returned function is provided a second argument which is not an ndarray (2 ndarrays)... { const types = [ 'float64', 'float64' ]; const data = [ unary ]; const x = array(); const f = dispatch( ndarrayFcn, types, data, 2, 1, 1 ); f( x, 10 ); // $ExpectError f( x, '10' ); // $ExpectError f( x, true ); // $ExpectError f( x, false ); // $ExpectError f( x, null ); // $ExpectError f( x, undefined ); // $ExpectError f( x, [ '1' ] ); // $ExpectError f( x, {} ); // $ExpectError f( x, ( x: number ): number => x ); // $ExpectError } // The compiler throws an error if the returned function is provided a first argument which is not an ndarray (3 ndarrays)... { const types = [ 'float64', 'float64', 'float64' ]; const data = [ binary ]; const y = array(); const z = array(); const f = dispatch( ndarrayFcn, types, data, 3, 2, 1 ); f( 10, y, z ); // $ExpectError f( '10', y, z ); // $ExpectError f( true, y, z ); // $ExpectError f( false, y, z ); // $ExpectError f( null, y, z ); // $ExpectError f( undefined, y, z ); // $ExpectError f( [ '1' ], y, z ); // $ExpectError f( {}, y, z ); // $ExpectError f( ( x: number ): number => x, y, z ); // $ExpectError } // The compiler throws an error if the returned function is provided a second argument which is not an ndarray (3 ndarrays)... { const types = [ 'float64', 'float64', 'float64' ]; const data = [ binary ]; const x = array(); const z = array(); const f = dispatch( ndarrayFcn, types, data, 3, 2, 1 ); f( x, 10, z ); // $ExpectError f( x, '10', z ); // $ExpectError f( x, true, z ); // $ExpectError f( x, false, z ); // $ExpectError f( x, null, z ); // $ExpectError f( x, undefined, z ); // $ExpectError f( x, [ '1' ], z ); // $ExpectError f( x, {}, z ); // $ExpectError f( x, ( x: number ): number => x, z ); // $ExpectError } // The compiler throws an error if the returned function is provided a third argument which is not an ndarray (3 ndarrays)... { const types = [ 'float64', 'float64', 'float64' ]; const data = [ binary ]; const x = array(); const y = array(); const f = dispatch( ndarrayFcn, types, data, 3, 2, 1 ); f( x, y, '10' ); // $ExpectError f( x, y, true ); // $ExpectError f( x, y, false ); // $ExpectError f( x, y, null ); // $ExpectError f( x, y, undefined ); // $ExpectError f( x, y, [ '1' ] ); // $ExpectError f( x, y, {} ); // $ExpectError f( x, y, ( x: number ): number => x ); // $ExpectError } // The compiler throws an error if the returned function is provided a first argument which is not an ndarray (4 ndarrays)... { const types = [ 'float64', 'float64', 'float64', 'float64' ]; const data = [ ternary ]; const y = array(); const z = array(); const w = array(); const f = dispatch( ndarrayFcn, types, data, 4, 3, 1 ); f( 10, y, z, w ); // $ExpectError f( '10', y, z, w ); // $ExpectError f( true, y, z, w ); // $ExpectError f( false, y, z, w ); // $ExpectError f( null, y, z, w ); // $ExpectError f( undefined, y, z, w ); // $ExpectError f( [ '1' ], y, z, w ); // $ExpectError f( {}, y, z, w ); // $ExpectError f( ( x: number ): number => x, y, z, w ); // $ExpectError } // The compiler throws an error if the returned function is provided a second argument which is not an ndarray (4 ndarrays)... { const types = [ 'float64', 'float64', 'float64', 'float64' ]; const data = [ ternary ]; const x = array(); const z = array(); const w = array(); const f = dispatch( ndarrayFcn, types, data, 4, 3, 1 ); f( x, 10, z, w ); // $ExpectError f( x, '10', z, w ); // $ExpectError f( x, true, z, w ); // $ExpectError f( x, false, z, w ); // $ExpectError f( x, null, z, w ); // $ExpectError f( x, undefined, z, w ); // $ExpectError f( x, [ '1' ], z, w ); // $ExpectError f( x, {}, z, w ); // $ExpectError f( x, ( x: number ): number => x, z, w ); // $ExpectError } // The compiler throws an error if the returned function is provided a third argument which is not an ndarray (4 ndarrays)... { const types = [ 'float64', 'float64', 'float64', 'float64' ]; const data = [ ternary ]; const x = array(); const y = array(); const w = array(); const f = dispatch( ndarrayFcn, types, data, 4, 3, 1 ); f( x, y, 10, w ); // $ExpectError f( x, y, '10', w ); // $ExpectError f( x, y, true, w ); // $ExpectError f( x, y, false, w ); // $ExpectError f( x, y, null, w ); // $ExpectError f( x, y, undefined, w ); // $ExpectError f( x, y, [ '1' ], w ); // $ExpectError f( x, y, {}, w ); // $ExpectError f( x, y, ( x: number ): number => x, w ); // $ExpectError } // The compiler throws an error if the returned function is provided a fourth argument which is not an ndarray (4 ndarrays)... { const types = [ 'float64', 'float64', 'float64', 'float64' ]; const data = [ ternary ]; const x = array(); const y = array(); const z = array(); const f = dispatch( ndarrayFcn, types, data, 4, 3, 1 ); f( x, y, z, 10 ); // $ExpectError f( x, y, z, '10' ); // $ExpectError f( x, y, z, true ); // $ExpectError f( x, y, z, false ); // $ExpectError f( x, y, z, null ); // $ExpectError f( x, y, z, undefined ); // $ExpectError f( x, y, z, [ '1' ] ); // $ExpectError f( x, y, z, {} ); // $ExpectError f( x, y, z, ( x: number ): number => x ); // $ExpectError } // The compiler throws an error if the returned function is provided a first argument which is not an ndarray (5 ndarrays)... { const types = [ 'float64', 'float64', 'float64', 'float64', 'float64' ]; const data = [ quaternary ]; const y = array(); const z = array(); const w = array(); const u = array(); const f = dispatch( ndarrayFcn, types, data, 5, 4, 1 ); f( 10, y, z, w, u ); // $ExpectError f( '10', y, z, w, u ); // $ExpectError f( true, y, z, w, u ); // $ExpectError f( false, y, z, w, u ); // $ExpectError f( null, y, z, w, u ); // $ExpectError f( undefined, y, z, w, u ); // $ExpectError f( [ '1' ], y, z, w, u ); // $ExpectError f( {}, y, z, w, u ); // $ExpectError f( ( x: number ): number => x, y, z, w, u ); // $ExpectError } // The compiler throws an error if the returned function is provided a second argument which is not an ndarray (5 ndarrays)... { const types = [ 'float64', 'float64', 'float64', 'float64', 'float64' ]; const data = [ quaternary ]; const x = array(); const z = array(); const w = array(); const u = array(); const f = dispatch( ndarrayFcn, types, data, 5, 4, 1 ); f( x, 10, z, w, u ); // $ExpectError f( x, '10', z, w, u ); // $ExpectError f( x, true, z, w, u ); // $ExpectError f( x, false, z, w, u ); // $ExpectError f( x, null, z, w, u ); // $ExpectError f( x, undefined, z, w, u ); // $ExpectError f( x, [ '1' ], z, w, u ); // $ExpectError f( x, {}, z, w, u ); // $ExpectError f( x, ( x: number ): number => x, z, w, u ); // $ExpectError } // The compiler throws an error if the returned function is provided a third argument which is not an ndarray (5 ndarrays)... { const types = [ 'float64', 'float64', 'float64', 'float64', 'float64' ]; const data = [ quaternary ]; const x = array(); const y = array(); const w = array(); const u = array(); const f = dispatch( ndarrayFcn, types, data, 5, 4, 1 ); f( x, y, 10, w, u ); // $ExpectError f( x, y, '10', w, u ); // $ExpectError f( x, y, true, w, u ); // $ExpectError f( x, y, false, w, u ); // $ExpectError f( x, y, null, w, u ); // $ExpectError f( x, y, undefined, w, u ); // $ExpectError f( x, y, [ '1' ], w, u ); // $ExpectError f( x, y, {}, w, u ); // $ExpectError f( x, y, ( x: number ): number => x, w, u ); // $ExpectError } // The compiler throws an error if the returned function is provided a fourth argument which is not an ndarray (5 ndarrays)... { const types = [ 'float64', 'float64', 'float64', 'float64', 'float64' ]; const data = [ quaternary ]; const x = array(); const y = array(); const z = array(); const u = array(); const f = dispatch( ndarrayFcn, types, data, 5, 4, 1 ); f( x, y, z, 10, u ); // $ExpectError f( x, y, z, '10', u ); // $ExpectError f( x, y, z, true, u ); // $ExpectError f( x, y, z, false, u ); // $ExpectError f( x, y, z, null, u ); // $ExpectError f( x, y, z, undefined, u ); // $ExpectError f( x, y, z, [ '1' ], u ); // $ExpectError f( x, y, z, {}, u ); // $ExpectError f( x, y, z, ( x: number ): number => x, u ); // $ExpectError } // The compiler throws an error if the returned function is provided a fifth argument which is not an ndarray (5 ndarrays)... { const types = [ 'float64', 'float64', 'float64', 'float64', 'float64' ]; const data = [ quaternary ]; const x = array(); const y = array(); const z = array(); const w = array(); const f = dispatch( ndarrayFcn, types, data, 5, 4, 1 ); f( x, y, z, w, 10 ); // $ExpectError f( x, y, z, w, '10' ); // $ExpectError f( x, y, z, w, true ); // $ExpectError f( x, y, z, w, false ); // $ExpectError f( x, y, z, w, null ); // $ExpectError f( x, y, z, w, undefined ); // $ExpectError f( x, y, z, w, [ '1' ] ); // $ExpectError f( x, y, z, w, {} ); // $ExpectError f( x, y, z, w, ( x: number ): number => x ); // $ExpectError }
the_stack
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed, fakeAsync, flushMicrotasks} from '@angular/core/testing'; import { EditableExplorationBackendApiService } from 'domain/exploration/editable-exploration-backend-api.service'; import { ExplorationDataService } from './exploration-data.service'; import { LocalStorageService } from 'services/local-storage.service'; import { LoggerService } from 'services/contextual/logger.service'; import { CsrfTokenService } from 'services/csrf-token.service'; import { UrlService } from 'services/contextual/url.service'; import { WindowRef } from 'services/contextual/window-ref.service'; import { ExplorationDraft } from 'domain/exploration/exploration-draft.model'; import { ExplorationBackendDict } from 'domain/exploration/ExplorationObjectFactory'; import { FetchExplorationBackendResponse } from 'domain/exploration/read-only-exploration-backend-api.service'; describe('Exploration data service', function() { let eds: ExplorationDataService = null; let eebas: EditableExplorationBackendApiService = null; let lss: LocalStorageService = null; let ls: LoggerService = null; let httpTestingController: HttpTestingController; let csrfService: CsrfTokenService = null; let sampleDataResults: ExplorationBackendDict = { draft_change_list_id: 3, version: 1, draft_changes: [], is_version_of_draft_valid: true, init_state_name: 'init', param_changes: [], param_specs: {randomProp: {obj_type: 'randomVal'}}, states: {}, title: 'Test Exploration', language_code: 'en', correctness_feedback_enabled: false }; let sampleExploration: FetchExplorationBackendResponse = { can_edit: true, exploration: { init_state_name: 'Introduction', states: { Introduction: { param_changes: [], content: { html: '', audio_translations: {} }, unresolved_answers: {}, interaction: { customization_args: {}, answer_groups: [], default_outcome: {}, confirmed_unclassified_answers: [], id: null } } } }, exploration_id: '1', is_logged_in: true, session_id: '1', version: 1, preferred_audio_language_code: 'en', auto_tts_enabled: true, correctness_feedback_enabled: false, record_playthrough_probability: 1, } as unknown as FetchExplorationBackendResponse; class MockEditableExplorationBackendApiService { resolve: boolean = true; async fetchApplyDraftExplorationAsync() { return new Promise((resolve, reject) => { if (this.resolve) { resolve(sampleDataResults); } else { reject(); } }); } async updateExplorationAsync() { return new Promise((resolve, reject) => { if (this.resolve) { resolve(sampleDataResults); } else { reject(); } }); } } const windowMock = { nativeWindow: { location: { reload: function() {} } } }; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ { provide: UrlService, useValue: {getPathname: () => '/create/0'} }, { provide: EditableExplorationBackendApiService, useClass: MockEditableExplorationBackendApiService }, {provide: WindowRef, useValue: windowMock } ] }); }); beforeEach(() => { eds = TestBed.inject(ExplorationDataService); lss = TestBed.inject(LocalStorageService); ls = TestBed.inject(LoggerService); eebas = TestBed.inject(EditableExplorationBackendApiService); csrfService = TestBed.inject(CsrfTokenService); httpTestingController = TestBed.inject(HttpTestingController); spyOn(csrfService, 'getTokenAsync').and.callFake(async() => { return Promise.resolve('sample-csrf-token'); }); }); afterEach(function() { httpTestingController.verify(); }); it('should trigger success handler when auto saved successfully', fakeAsync( () => { eds.data = sampleDataResults; const errorCallback = jasmine.createSpy('error'); const successCallback = jasmine.createSpy('success'); eds.autosaveChangeListAsync([], successCallback, errorCallback); const req = httpTestingController.expectOne( '/createhandler/autosave_draft/0'); expect(req.request.method).toBe('PUT'); req.flush(sampleDataResults); flushMicrotasks(); expect(successCallback).toHaveBeenCalledWith(sampleDataResults); expect(errorCallback).not.toHaveBeenCalled(); } )); it('should trigger errorcallback handler when auto save fails', fakeAsync( () => { eds.data = sampleDataResults; const errorCallback = jasmine.createSpy('error'); const successCallback = jasmine.createSpy('success'); eds.autosaveChangeListAsync([], successCallback, errorCallback); const req = httpTestingController.expectOne( '/createhandler/autosave_draft/0'); expect(req.request.method).toBe('PUT'); req.error(new ErrorEvent('Server error')); flushMicrotasks(); expect(successCallback).not.toHaveBeenCalled(); expect(errorCallback).toHaveBeenCalled(); } )); it('should autosave draft changes when draft ids match', fakeAsync(() => { const errorCallback = jasmine.createSpy('error'); const successCallback = jasmine.createSpy('success'); const explorationDraft: ExplorationDraft = new ExplorationDraft([], 1); spyOn(explorationDraft, 'isValid').and.callFake(() => true); spyOn(lss, 'getExplorationDraft').and.returnValue(explorationDraft); eds.getDataAsync(errorCallback).then(successCallback); flushMicrotasks(); const req = httpTestingController.expectOne( '/createhandler/autosave_draft/0'); expect(req.request.method).toBe('PUT'); req.flush(sampleDataResults); flushMicrotasks(); expect(successCallback).toHaveBeenCalledWith(sampleDataResults); })); it('should not autosave draft changes when draft is already cached', fakeAsync(() => { const errorCallback = jasmine.createSpy('error'); const explorationDraft: ExplorationDraft = new ExplorationDraft([], 1); spyOn(explorationDraft, 'isValid').and.callFake(() => true); spyOn(lss, 'getExplorationDraft').and.returnValue(explorationDraft); // Save draft. eds.getDataAsync(errorCallback).then(data => { expect(data).toEqual(sampleDataResults); expect(errorCallback).not.toHaveBeenCalled(); }); flushMicrotasks(); const req = httpTestingController.expectOne( '/createhandler/autosave_draft/0'); expect(req.request.method).toBe('PUT'); req.flush(sampleDataResults); flushMicrotasks(); httpTestingController.verify(); const logInfoSpy = spyOn(ls, 'info').and.callThrough(); // Draft is already saved and it's in cache. eds.getDataAsync(errorCallback).then(data => { expect(logInfoSpy).toHaveBeenCalledWith( 'Found exploration data in cache.'); expect(data).toEqual(sampleDataResults); expect(errorCallback).not.toHaveBeenCalled(); }); flushMicrotasks(); })); it('should autosave draft changes when draft ids match', fakeAsync(() => { const errorCallback = jasmine.createSpy('error'); const explorationDraft: ExplorationDraft = new ExplorationDraft([], 1); spyOn(explorationDraft, 'isValid').and.callFake(() => true); spyOn(lss, 'getExplorationDraft').and.returnValue(explorationDraft); const windowRefSpy = spyOn(windowMock.nativeWindow.location, 'reload') .and.callThrough(); eds.getDataAsync(errorCallback).then(data => { expect(data).toEqual(sampleDataResults); expect(errorCallback).not.toHaveBeenCalled(); expect(windowRefSpy).not.toHaveBeenCalled(); }); flushMicrotasks(); const req = httpTestingController.expectOne( '/createhandler/autosave_draft/0'); expect(req.request.method).toBe('PUT'); req.flush('Whoops!', { status: 500, statusText: 'Internal Server error' }); flushMicrotasks(); })); it('should call error callback when draft ids do not match', fakeAsync(() => { const explorationDraft: ExplorationDraft = new ExplorationDraft([], 1); spyOn(explorationDraft, 'isValid').and.callFake(() => false); spyOn(lss, 'getExplorationDraft').and.returnValue(explorationDraft); const errorCallback = jasmine.createSpy('error'); eds.getDataAsync(errorCallback).then(data => { expect(data).toEqual(sampleDataResults); expect(errorCallback).toHaveBeenCalled(); }); flushMicrotasks(); })); it('should discard draft', fakeAsync(() => { const successHandler = jasmine.createSpy('success'); const failHandler = jasmine.createSpy('fail'); eds.discardDraftAsync().then(successHandler, failHandler); const req = httpTestingController.expectOne( '/createhandler/autosave_draft/0'); req.flush({}); flushMicrotasks(); expect(successHandler).toHaveBeenCalled(); expect(failHandler).not.toHaveBeenCalled(); })); it('should use reject handler when discard draft fails', fakeAsync(() => { const successHandler = jasmine.createSpy('success'); const failHandler = jasmine.createSpy('fail'); eds.discardDraftAsync().then(successHandler, failHandler); const req = httpTestingController.expectOne( '/createhandler/autosave_draft/0'); req.error(new ErrorEvent('Internal server error')); flushMicrotasks(); expect(successHandler).not.toHaveBeenCalled(); expect(failHandler).toHaveBeenCalled(); })); it('should get last saved data', fakeAsync(() => { const successHandler = jasmine.createSpy('success'); const failHandler = jasmine.createSpy('fail'); const logInfoSpy = spyOn(ls, 'info').and.callThrough(); eds.getLastSavedDataAsync().then(successHandler, failHandler); let req = httpTestingController.expectOne('/explorehandler/init/0'); expect(req.request.method).toEqual('GET'); req.flush(sampleExploration); flushMicrotasks(); expect(successHandler).toHaveBeenCalledWith( sampleExploration.exploration); expect(logInfoSpy).toHaveBeenCalledTimes(2); })); it('should save an exploration to the backend', fakeAsync(() => { const successHandler = jasmine.createSpy('success'); const failHandler = jasmine.createSpy('fail'); const errorCallback = jasmine.createSpy('error'); const explorationDraft: ExplorationDraft = new ExplorationDraft([], 1); spyOn(explorationDraft, 'isValid').and.callFake(() => true); spyOn(lss, 'getExplorationDraft').and.returnValue(explorationDraft); const changeList = []; eds.getDataAsync(errorCallback).then(data => { expect(data).toEqual(sampleDataResults); expect(errorCallback).not.toHaveBeenCalled(); }); flushMicrotasks(); const req = httpTestingController.expectOne( '/createhandler/autosave_draft/0'); req.flush(sampleDataResults); flushMicrotasks(); eds.save(changeList, 'Commit Message', successHandler, failHandler); flushMicrotasks(); expect(successHandler).toHaveBeenCalledWith( sampleDataResults.is_version_of_draft_valid, sampleDataResults.draft_changes); expect(failHandler).not.toHaveBeenCalled(); })); it('should save an exploration to the backend even when ' + 'data.exploration is not defined', fakeAsync(() => { const successHandler = jasmine.createSpy('success'); const failHandler = jasmine.createSpy('fail'); const errorCallback = jasmine.createSpy('error'); const explorationDraft: ExplorationDraft = new ExplorationDraft([], 1); spyOn(explorationDraft, 'isValid').and.callFake(() => false); spyOn(lss, 'getExplorationDraft').and.returnValue(explorationDraft); const changeList = []; let toBeResolved = false; // The data.exploration won't receive a value. spyOn(eebas, 'updateExplorationAsync').and.callFake( async() => { return new Promise((resolve, reject) => { if (toBeResolved) { resolve(sampleDataResults); } else { reject(); } }); } ); eds.getDataAsync(errorCallback); flushMicrotasks(); expect(errorCallback).toHaveBeenCalled(); toBeResolved = true; eds.save(changeList, 'Commit Message', successHandler, failHandler); flushMicrotasks(); expect(successHandler).toHaveBeenCalledWith( sampleDataResults.is_version_of_draft_valid, sampleDataResults.draft_changes); expect(failHandler).not.toHaveBeenCalled(); })); it('should use reject handler when save an exploration to the backend fails', fakeAsync(() => { const successHandler = jasmine.createSpy('success'); const failHandler = jasmine.createSpy('fail'); const errorCallback = jasmine.createSpy('error'); const explorationDraft: ExplorationDraft = new ExplorationDraft([], 1); spyOn(explorationDraft, 'isValid').and.callFake(() => true); spyOn(lss, 'getExplorationDraft').and.returnValue(explorationDraft); const changeList = []; eds.getDataAsync(errorCallback).then(function(data) { expect(data).toEqual(sampleDataResults); expect(errorCallback).not.toHaveBeenCalled(); }); flushMicrotasks(); const req = httpTestingController.expectOne( '/createhandler/autosave_draft/0'); req.flush(sampleDataResults); spyOn(eebas, 'updateExplorationAsync').and.callFake( async() => { return new Promise((resolve, reject) => { reject(); }); } ); flushMicrotasks(); eds.save(changeList, 'Commit Message', successHandler, failHandler); flushMicrotasks(); expect(successHandler).not.toHaveBeenCalled(); expect(failHandler).toHaveBeenCalled(); })); }); describe('Exploration data service', function() { var eds = null; var ls = null; var logErrorSpy; var pathname = '/exploration/0'; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ { provide: UrlService, useValue: {getPathname: () => '/exploration/0'} } ] }); }); beforeEach(() => { ls = TestBed.inject(LoggerService); logErrorSpy = spyOn(ls, 'error').and.callThrough(); eds = TestBed.inject(ExplorationDataService); }); it('should throw error when pathname is not valid', () => { expect(logErrorSpy).toHaveBeenCalledWith( 'Unexpected call to ExplorationDataService for pathname: ' + pathname); var errorCallback = jasmine.createSpy('error'); expect(function() { eds.getData(errorCallback); }).toThrowError('eds.getData is not a function'); }); });
the_stack
import { SagaIterator } from 'redux-saga'; import { all, call, put, select, take } from 'redux-saga/effects'; import { logger } from '../api/logger'; import { getFocusedTabId } from '../app/selectors'; import { FRONT_ACTIVE_TAB_CHANGE } from '../tab-webcontents/duck'; import { getWebcontentsIdForTabId } from '../tab-webcontents/selectors'; import { callService, takeEveryWitness } from '../utils/sagas'; import { getApplicationById } from '../applications/selectors'; import { getApplicationManifestURL } from '../applications/get'; import { accounts, AccountsStep, ADD_LINK, ADD_PASSWORD_MANAGER, addLink, addPasswordManager, CLOSE_ALL, ConfigurationStep, displayBanner, displayRemoveLinkBanner, LOAD_ACCOUNTS, loadCredentials, REMOVE_LINK, REMOVE_PASSWORD_MANAGER, removeLink, RemovePasswordManagerAction, UNLOCK, unlock, UnlockStep, } from './duck'; import Providers from './providers'; import { getAccounts, getConfigurationProcess, getLinkForActiveApplication, getLinks, getPasswordManager, getProviderId, getProviderJS, getUnlockProcess, } from './selectors'; const autoSubmits = new Map(); const canAutoSubmit = (webcontentsId: number) => { if (autoSubmits.has(webcontentsId)) { return false; } autoSubmits.set(webcontentsId, Date.now()); return true; }; const currentlySendLoginToWebContents = new Map(); export const canSendLoginToWebContents = (webcontentsId: number) => { if (currentlySendLoginToWebContents.has(webcontentsId)) { return false; } return true; }; export function* getCredentialsForWebContents(webContentsId: number): SagaIterator { currentlySendLoginToWebContents.set(webContentsId, Date.now()); const providerId = yield select(getProviderId); const runtime = Providers[providerId].runtime; const link = yield select(getLinkForActiveApplication); if (link) { const passwordManager = yield select(getPasswordManager); const applicationId = link.get('applicationId'); const application = yield select(getApplicationById, applicationId); const manifestURL = getApplicationManifestURL(application); if (runtime.hasValidSession()) { try { yield put(loadCredentials(true)); const passwordManagerItemId = link.get('passwordManagerItemId'); const credentials = yield call([runtime, runtime.getAccountById], passwordManagerItemId); yield put(addLink({ passwordManager, applicationId, passwordManagerItemId, login: credentials.username, avatar: credentials.avatar, })); return { account: credentials, canAutoSubmit: canAutoSubmit(webContentsId) }; } catch (error) { yield put(removeLink({ applicationId })); const opts = { step: AccountsStep.Load, passwordManager, }; yield put(accounts(opts)); } finally { yield put(loadCredentials(false)); } } else { yield put(unlock({ step: UnlockStep.Ask, passwordManager, webcontentsId: webContentsId })); } } else { yield put(displayBanner(true)); } currentlySendLoginToWebContents.delete(webContentsId); return { status: false }; } function* unlockPasswordManagerFlow(): SagaIterator { const unlockProcess = yield select(getUnlockProcess); const { step, passwordManager, webcontentsId, payload } = unlockProcess; if (step === UnlockStep.NotAsked) return; const runtime = Providers[passwordManager.providerId].runtime; if (step === UnlockStep.Ask) { yield put(displayRemoveLinkBanner(false)); if (runtime.hasValidSession()) { const opts = { ...unlockProcess, step: UnlockStep.Exit, }; yield put(unlock(opts)); if (webcontentsId && canSendLoginToWebContents(webcontentsId)) { yield callService('tabWebContents', 'askAutoLoginCredentials', webcontentsId); } return; } } if (step === UnlockStep.Test) { try { const credentials = { ...passwordManager, ...payload }; // @ts-ignore: can't understand promise yield call([runtime, runtime.setSession], credentials); const opts = { ...unlockProcess, step: UnlockStep.Finish, }; autoSubmits.clear(); yield put(unlock(opts)); if (webcontentsId && canSendLoginToWebContents(webcontentsId)) { yield callService('tabWebContents', 'askAutoLoginCredentials', webcontentsId); } } catch (error) { logger.notify(error); const opts = { ...unlockProcess, step: UnlockStep.Error, payload: 'Wrong master password', }; yield put(unlock(opts)); } } if (step === UnlockStep.Finish) { // do what you want before exiting the process const opts = { ...unlockProcess, step: UnlockStep.Exit, }; yield put(unlock(opts)); } if (step === UnlockStep.ExitFromAutofill) { yield put(displayRemoveLinkBanner(true)); const opts = { ...unlockProcess, step: UnlockStep.Exit, }; yield put(unlock(opts)); } } function* loadAccountsFlow(): SagaIterator { const process = yield select(getAccounts); const { step, passwordManager } = process; if (step === AccountsStep.NotAsked) return; if (step === AccountsStep.WaitConfiguration) { const provider = yield select(getProviderJS); yield put(addPasswordManager({ step: ConfigurationStep.Credentials, provider })); return; } const runtime = Providers[passwordManager.providerId].runtime; if (step === AccountsStep.Ask) { yield put(displayBanner(false)); if (!runtime.hasValidSession()) { yield put(unlock({ step: UnlockStep.Ask, passwordManager, })); const endUnlock = yield take((action: any) => action.type === UNLOCK && [UnlockStep.Finish, UnlockStep.Exit].includes(action.step)); const nextStep = endUnlock.step === UnlockStep.Exit ? AccountsStep.Unload : AccountsStep.Load; yield put(accounts({ step: nextStep, passwordManager, })); } else { yield put(accounts({ step: AccountsStep.Load, passwordManager, })); } } if (step === AccountsStep.Load) { try { const data = yield call([runtime, runtime.getAccounts]); yield put(accounts({ step: AccountsStep.Loaded, passwordManager, data, })); } catch (e) { logger.notify(e); } } if (step === AccountsStep.Loaded) { } } function* addPasswordManagerFlow(): SagaIterator { const configuration = yield select(getConfigurationProcess); const { step, provider, payload } = configuration; if (step === ConfigurationStep.NotStarted) return; yield put(displayBanner(false)); if (step === ConfigurationStep.Test) { const runtime = Providers[provider.id].runtime; // @ts-ignore: can't understand promise const isValid = yield call([runtime, runtime.isValidCredentials], payload); if (isValid) { yield put(addPasswordManager({ step: ConfigurationStep.Save, provider, payload, })); } else { yield put(addPasswordManager({ step: ConfigurationStep.Error, provider, payload: 'Wrong credentials. Please verify your login information.', })); } } if (step === ConfigurationStep.Cancel) { const accountsProcess = yield select(getAccounts); if (accountsProcess.step === AccountsStep.WaitConfiguration) { yield put(accounts({ step: AccountsStep.Unload, })); } yield put(addPasswordManager({ step: ConfigurationStep.Exit, provider, })); } if (step === ConfigurationStep.Saved) { // do what you want before exiting the process const accountsProcess = yield select(getAccounts); if (accountsProcess.step === AccountsStep.WaitConfiguration) { const passwordManager = yield select(getPasswordManager); const accountsOpts = { ...accountsProcess, passwordManager, step: AccountsStep.Load }; yield put(accounts(accountsOpts)); yield put(setVisibilityTeamApp(false)); } yield put(addPasswordManager({ step: ConfigurationStep.Exit, provider, })); } } function* onRemovePasswordManager(action: RemovePasswordManagerAction): SagaIterator { yield call(exitCurrentFlow); const { providerId, id } = action.passwordManager; const links = yield select(getLinks); const linksToRemove = Array.from(links.values()) .filter((v: any) => v.get('providerId') === providerId && v.get('passwordManagerId') === id) .map((v: any) => v.get('applicationId')); yield all(linksToRemove.map(applicationId => put(removeLink({ applicationId })))); } function* addLinkFlow(): SagaIterator { const process = yield select(getAccounts); const { passwordManager } = process; const tabId = yield select(getFocusedTabId); const webContentsId = yield select(getWebcontentsIdForTabId, tabId); yield put(accounts({ step: AccountsStep.Unload, passwordManager, })); if (canSendLoginToWebContents(webContentsId)) { yield callService('tabWebContents', 'askAutoLoginCredentials', webContentsId); } } function* removeLinkFlow(): SagaIterator { yield put(displayRemoveLinkBanner(false)); } function* exitCurrentFlow(): SagaIterator { const configurationProcess = yield select(getConfigurationProcess); const { configurationStep, configurationProvider } = configurationProcess; const unlockProcess = yield select(getUnlockProcess); const { unlockStep, unlockPasswordManager } = unlockProcess; const accountProcess = yield select(getAccounts); const { accountStep, accountPasswordManager } = accountProcess; if (configurationStep !== ConfigurationStep.NotStarted) { yield put(addPasswordManager({ step: ConfigurationStep.Exit, provider: configurationProvider, })); } if (unlockStep !== UnlockStep.NotAsked) { yield put(unlock({ step: UnlockStep.Exit, passwordManager: unlockPasswordManager, })); } if (accountStep !== AccountsStep.NotAsked) { yield put(accounts({ step: AccountsStep.Unload, passwordManager: accountPasswordManager, })); } yield put(displayBanner(false)); } export default function* main() { yield all([ takeEveryWitness(UNLOCK, unlockPasswordManagerFlow), takeEveryWitness(LOAD_ACCOUNTS, loadAccountsFlow), takeEveryWitness(ADD_PASSWORD_MANAGER, addPasswordManagerFlow), takeEveryWitness(REMOVE_PASSWORD_MANAGER, onRemovePasswordManager), takeEveryWitness(ADD_LINK, addLinkFlow), takeEveryWitness(REMOVE_LINK, removeLinkFlow), takeEveryWitness([CLOSE_ALL, FRONT_ACTIVE_TAB_CHANGE], exitCurrentFlow), ]); }
the_stack
import * as React from "react"; import { isMenuRef, isComponentFlyout } from "../utils/type-guards"; import { IDOMElementMetrics, FlyoutVisibilitySet, GenericEvent } from "../api/common"; import { ToolbarContext } from "./context"; import { STR_EMPTY } from "../utils/string"; import { ImageIcon } from "./icon"; import { BlueprintSvgIconNames } from "../constants/assets"; import { Icon } from '@blueprintjs/core'; import { NBSP } from '../constants'; export const DEFAULT_TOOLBAR_SIZE = 29; export const TOOLBAR_BACKGROUND_COLOR = "#f0f0f0"; // Custom type guard to workaround: https://github.com/microsoft/TypeScript/issues/39879 function isNumeric(arg: any): arg is number { return typeof(arg) == 'number'; } // Size is based on the default toolbar height of 29 (with base image icon size of 16x16) // This ratio will help "scale" SVG icons to match const SVG_SIZE_RATIO = 16 / DEFAULT_TOOLBAR_SIZE; function getSelected(item: IItem): boolean { const sel = item.selected; if (sel != null) { if (typeof sel === 'function') { return sel(); } else { return sel; } } return false; } export function getEnabled(item: IItem): boolean { const en = item.enabled; if (en != null) { if (typeof en === 'function') { return en(); } else { return en; } } return true; } function getIconElement(item: IItem, enabled: boolean, size: number): React.ReactNode { const iconStyle = getIconStyle(enabled, size); if (item.iconClass || item.icon) { return <ImageIcon style={iconStyle} url={item.icon} spriteClass={item.iconClass} /> } else if (item.bpIconName) { const { opacity } = iconStyle; //For SVG, we only care about opacity return <Icon style={{ opacity }} icon={item.bpIconName} iconSize={size * SVG_SIZE_RATIO} /> } else { return <></>; } } function getFlyoutIconElement(isFlownOut: boolean | undefined, size: number) { return <Icon icon={isFlownOut ? "chevron-up" : "chevron-down"} iconSize={size * SVG_SIZE_RATIO} /> } function getTooltip(item: IItem): string { const tt = item.tooltip; if (tt != null) { if (typeof tt === 'function') { return tt(); } else { return tt; } } return STR_EMPTY; } export function getIconStyle(enabled: boolean, height: number): React.CSSProperties { const imgStyle: React.CSSProperties = { verticalAlign: "middle", lineHeight: height }; return imgStyle; } function getItemStyle(enabled: boolean, selected: boolean, size: number, isMouseOver: boolean, vertical?: boolean): React.CSSProperties { const pad = ((size - 16) / 2); const vertPad = 6; const style: React.CSSProperties = { display: vertical === true ? "block" : "inline-block", //height: height, paddingLeft: pad, paddingRight: pad, paddingTop: vertPad, paddingBottom: vertPad }; if ((isMouseOver === true && enabled === true) || selected) { style.borderWidth = 1; style.paddingLeft = pad - 1; //To compensate for border style.paddingRight = pad - 1; //To compensate for border style.paddingTop = vertPad - 1; //To compensate for border style.paddingBottom = vertPad - 1; //To compensate for border } return style; } function getToolbarSeparatorItemStyle(vertical?: boolean): React.CSSProperties { const style: React.CSSProperties = { display: vertical === true ? "block" : "inline-block" }; if (vertical === true) { style.paddingTop = 2; style.paddingBottom = -2; style.marginLeft = 0; style.marginRight = 0; } else { style.paddingTop = 0; style.paddingBottom = 0; style.marginLeft = 2; style.marginRight = -2; } return style; } function getMenuItemStyle(enabled: boolean, selected: boolean, height: number, isMouseOver: boolean): React.CSSProperties { const pad = ((height - 16) / 2); const vertPad = 6; const style: React.CSSProperties = { //height: height, paddingLeft: pad, paddingRight: pad, paddingTop: vertPad, paddingBottom: vertPad }; if (enabled && (isMouseOver === true || selected)) { style.cursor = "pointer"; style.border = "1px solid rgb(153, 181, 202)"; style.paddingLeft = pad - 1; //To compensate for border style.paddingRight = pad - 1; //To compensate for border style.paddingTop = vertPad - 1; //To compensate for border style.paddingBottom = vertPad - 1; //To compensate for border } return style; } export interface IFlyoutMenuChildItemProps { item: IItem | IInlineMenu; onInvoked?: () => void; } export const FlyoutMenuChildItem = (props: IFlyoutMenuChildItemProps) => { const { item } = props; const [isMouseOver, setIsMouseOver] = React.useState(false); const onClick = () => { if (getEnabled(item)) { item.invoke?.(); props.onInvoked?.(); } }; const onMouseLeave = () => { setIsMouseOver(false); }; const onMouseEnter = () => { setIsMouseOver(true); }; const height = DEFAULT_TOOLBAR_SIZE; const selected = getSelected(item); const enabled = getEnabled(item); const tt = getTooltip(item); const style = getMenuItemStyle(enabled, selected, height, isMouseOver); const iconEl = getIconElement(item, enabled, height); return <li className="noselect flyout-menu-child-item" title={tt} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} onClick={onClick}> <div style={style}> {iconEl} {item.label} </div> </li>; } interface IComponentFlyoutItemProps { size: number; item: IComponentFlyoutItem; vertical?: boolean; isFlownOut?: boolean; } const ComponentFlyoutItem = (props: IComponentFlyoutItemProps) => { const { size, item, vertical, isFlownOut } = props; const toolbarCtx = React.useContext(ToolbarContext); const [isMouseOver, setIsMouseOver] = React.useState(false); const onClick = (e: GenericEvent) => { e.preventDefault(); const { flyoutId, componentName, componentProps } = item; const newState = !!!isFlownOut; if (newState) { const rect = e.currentTarget.getBoundingClientRect(); const metrics: IDOMElementMetrics = { posX: rect.left, // e.clientX, posY: rect.top, // e.clientY, width: rect.width, // e.currentTarget.offsetWidth, height: rect.height, // e.currentTarget.offsetHeight vertical: vertical }; toolbarCtx.openComponent(flyoutId, metrics, componentName, componentProps); } else { toolbarCtx.closeComponent(flyoutId); } return false; }; const onMouseLeave = () => { setIsMouseOver(false); }; const onMouseEnter = () => { setIsMouseOver(true); }; const selected = getSelected(item); const enabled = getEnabled(item); const style = getItemStyle(enabled, selected, size, isMouseOver, vertical); let label: any = item.label; if (vertical === true) { label = <div className="rotated-text"><span className="rotated-text__inner rotated-text-ccw">{item.label}</span></div>; } const ttip = getTooltip(item); const iconEl = getIconElement(item, enabled, size); return <div className={`noselect toolbar-flyout-btn ${selected ? "selected-item" : ""} ${isMouseOver ? "mouse-over" : ""}`} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} onClick={onClick} style={style} title={ttip}> <div data-flyout-id={`flyout-${item.flyoutId}`}> {iconEl} {label} {getFlyoutIconElement(isFlownOut, size)} </div> </div>; }; interface IFlyoutMenuReferenceItemProps { size: number; menu: IFlyoutMenu; vertical?: boolean; isFlownOut?: boolean; } const FlyoutMenuReferenceItem = (props: IFlyoutMenuReferenceItemProps) => { const { size, menu, vertical, isFlownOut } = props; const toolbarCtx = React.useContext(ToolbarContext); const [isMouseOver, setIsMouseOver] = React.useState(false); const onClick = (e: GenericEvent) => { e.preventDefault(); const newState = !!!isFlownOut; if (newState) { const rect = e.currentTarget.getBoundingClientRect(); const metrics: IDOMElementMetrics = { posX: rect.left, // e.clientX, posY: rect.top, // e.clientY, width: rect.width, // e.currentTarget.offsetWidth, height: rect.height, // e.currentTarget.offsetHeight vertical: vertical }; toolbarCtx.openFlyout(menu.flyoutId, metrics); } else { toolbarCtx.closeFlyout(menu.flyoutId); } return false; } const onMouseLeave = () => { setIsMouseOver(false); }; const onMouseEnter = () => { setIsMouseOver(true); }; const selected = getSelected(menu); const enabled = getEnabled(menu); const style = getItemStyle(enabled, selected, size, isMouseOver, vertical); let label: any = menu.label; if (vertical === true) { label = <div className="rotated-text"><span className="rotated-text__inner rotated-text-ccw">{menu.label}</span></div>; } let align = menu.flyoutAlign; if (!align) { align = (vertical === true) ? "right bottom" : "bottom right"; } const ttip = getTooltip(menu); const iconEl = getIconElement(menu, enabled, size); return <div className={`noselect toolbar-flyout-btn ${selected ? "selected-item" : ""} ${isMouseOver ? "mouse-over" : ""}`} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} onClick={onClick} style={style} title={ttip}> <div data-flyout-id={`flyout-${menu.flyoutId}`}> {iconEl} {label} {getFlyoutIconElement(isFlownOut, size)} </div> </div>; }; interface IToolbarSeparatorProps { size: number; vertical?: boolean; } const ToolbarSeparator = (props: IToolbarSeparatorProps) => { const style = getToolbarSeparatorItemStyle(props.vertical); if (props.vertical === true) { return <div className="noselect toolbar-separator-vertical" style={style} />; } else { return <div className="noselect toolbar-separator-horizontal" style={style}>{NBSP}</div>; } } interface IToolbarButtonProps { height: number; item: IItem; vertical?: boolean; hideVerticalLabels?: boolean; } const ToolbarButton = (props: IToolbarButtonProps) => { const { height, item, vertical, hideVerticalLabels } = props; const [isMouseOver, setIsMouseOver] = React.useState(false); const onMouseLeave = () => { setIsMouseOver(false); } const onMouseEnter = () => { setIsMouseOver(true); } const onClick = (e: any) => { e.preventDefault(); const { item } = props; const enabled = getEnabled(item); if (enabled && item.invoke) { item.invoke(); } return false; } const selected = getSelected(item); const enabled = getEnabled(item); const style = getItemStyle(enabled, selected, height, isMouseOver, vertical); let ttip = null; if (typeof (item.tooltip) == 'function') { ttip = item.tooltip(); } else { ttip = item.tooltip; } if (!enabled) { style.opacity = 0.3; } const iconEl = getIconElement(item, enabled, height); return <div className={`noselect toolbar-btn ${selected ? "selected-item" : ""} ${(isMouseOver && enabled) ? "mouse-over" : ""}`} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} style={style} title={ttip} onClick={onClick}> {iconEl} {(vertical == true && hideVerticalLabels == true) ? null : item.label} </div>; } export interface IItem { label?: string | (() => string); tooltip?: string | (() => string); icon?: string; iconClass?: string; bpIconName?: BlueprintSvgIconNames; invoke?: () => void; enabled?: boolean | (() => boolean); selected?: boolean | (() => boolean); isSeparator?: boolean; } export interface IInlineMenu extends IItem { childItems: IItem[]; flyoutAlign?: string; } export interface IFlyoutMenu extends IItem { flyoutId: string; flyoutAlign?: string; } export interface IComponentFlyoutItem extends IItem { flyoutId: string; componentName: string; componentProps?: any; } export interface IContainerItem extends IItem { renderContainerContent: () => JSX.Element; } /** * Toolbar component props * * @export * @interface IToolbarProps */ export interface IToolbarProps { childItems: IItem[]; containerClass?: string; containerStyle?: React.CSSProperties; vertical?: boolean; hideVerticalLabels?: boolean; onOpenFlyout?: (id: string, metrics: IDOMElementMetrics) => void; onCloseFlyout?: (id: string) => void; onOpenComponent?: (id: string, metrics: IDOMElementMetrics, name: string, props?: any) => void; onCloseComponent?: (id: string) => void; flyoutStates?: FlyoutVisibilitySet; } /** * A generic toolbar component * @param props */ export const Toolbar = (props: IToolbarProps) => { const { containerStyle, containerClass, childItems, vertical, hideVerticalLabels, flyoutStates, onOpenFlyout, onCloseFlyout, onOpenComponent, onCloseComponent } = props; const openFlyout = (id: string, metrics: IDOMElementMetrics) => onOpenFlyout?.(id, metrics); const closeFlyout = (id: string) => onCloseFlyout?.(id); const openComponent = (id: string, metrics: IDOMElementMetrics, name: string, props?: any) => onOpenComponent?.(id, metrics, name, props); const closeComponent = (id: string) => onCloseComponent?.(id); let height = DEFAULT_TOOLBAR_SIZE; if (containerStyle) { const ch = containerStyle.height; if (isNumeric(ch)) { height = ch; } } const providerImpl = { openFlyout: openFlyout, closeFlyout: closeFlyout, openComponent: openComponent, closeComponent: closeComponent }; return <ToolbarContext.Provider value={providerImpl}> <div style={containerStyle} className={`has-flyout noselect ${containerClass}`}> {childItems.map((item, index) => { if (isComponentFlyout(item)) { const isFlownOut = flyoutStates && !!flyoutStates[item.flyoutId]; return <ComponentFlyoutItem key={index} size={height} item={item} vertical={vertical} isFlownOut={isFlownOut} />; } else if (isMenuRef(item)) { const isFlownOut = flyoutStates && !!flyoutStates[item.flyoutId]; return <FlyoutMenuReferenceItem key={index} size={height} menu={item} vertical={vertical} isFlownOut={isFlownOut} />; } else if (item.isSeparator === true) { return <ToolbarSeparator key={index} size={height} vertical={vertical} />; } else { return <ToolbarButton key={index} height={height} item={item} vertical={vertical} hideVerticalLabels={hideVerticalLabels} />; } })} </div> </ToolbarContext.Provider>; }
the_stack
import { KubernetesObject } from 'kpt-functions'; import * as apisMetaV1 from './io.k8s.apimachinery.pkg.apis.meta.v1'; export class BackendConfig implements KubernetesObject { // APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources public apiVersion: string; // Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds public kind: string; // Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata public metadata: apisMetaV1.ObjectMeta; // BackendConfigSpec is the spec for a BackendConfig resource public spec?: BackendConfig.Spec; public status?: object; constructor(desc: BackendConfig.Interface) { this.apiVersion = BackendConfig.apiVersion; this.kind = BackendConfig.kind; this.metadata = desc.metadata; this.spec = desc.spec; this.status = desc.status; } } export function isBackendConfig(o: any): o is BackendConfig { return ( o && o.apiVersion === BackendConfig.apiVersion && o.kind === BackendConfig.kind ); } export namespace BackendConfig { export const apiVersion = 'cloud.google.com/v1'; export const group = 'cloud.google.com'; export const version = 'v1'; export const kind = 'BackendConfig'; // named constructs a BackendConfig with metadata.name set to name. export function named(name: string): BackendConfig { return new BackendConfig({ metadata: { name } }); } export interface Interface { // Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata metadata: apisMetaV1.ObjectMeta; // BackendConfigSpec is the spec for a BackendConfig resource spec?: BackendConfig.Spec; status?: object; } // BackendConfigSpec is the spec for a BackendConfig resource export class Spec { // CDNConfig contains configuration for CDN-enabled backends. public cdn?: BackendConfig.Spec.Cdn; // ConnectionDrainingConfig contains configuration for connection draining. For now the draining timeout. May manage more settings in the future. public connectionDraining?: BackendConfig.Spec.ConnectionDraining; // CustomRequestHeadersConfig contains configuration for custom request headers public customRequestHeaders?: BackendConfig.Spec.CustomRequestHeaders; // HealthCheckConfig contains configuration for the health check. public healthCheck?: BackendConfig.Spec.HealthCheck; // IAPConfig contains configuration for IAP-enabled backends. public iap?: BackendConfig.Spec.Iap; // LogConfig contains configuration for logging. public logging?: BackendConfig.Spec.Logging; // SecurityPolicyConfig contains configuration for CloudArmor-enabled backends. public securityPolicy?: BackendConfig.Spec.SecurityPolicy; // SessionAffinityConfig contains configuration for stickyness parameters. public sessionAffinity?: BackendConfig.Spec.SessionAffinity; public timeoutSec?: number; } export namespace Spec { // CDNConfig contains configuration for CDN-enabled backends. export class Cdn { // CacheKeyPolicy contains configuration for how requests to a CDN-enabled backend are cached. public cachePolicy?: BackendConfig.Spec.Cdn.CachePolicy; public enabled: boolean; constructor(desc: BackendConfig.Spec.Cdn) { this.cachePolicy = desc.cachePolicy; this.enabled = desc.enabled; } } export namespace Cdn { // CacheKeyPolicy contains configuration for how requests to a CDN-enabled backend are cached. export class CachePolicy { // If true, requests to different hosts will be cached separately. public includeHost?: boolean; // If true, http and https requests will be cached separately. public includeProtocol?: boolean; // If true, query string parameters are included in the cache key according to QueryStringBlacklist and QueryStringWhitelist. If neither is set, the entire query string is included and if false the entire query string is excluded. public includeQueryString?: boolean; // Names of query strint parameters to exclude from cache keys. All other parameters are included. Either specify QueryStringBlacklist or QueryStringWhitelist, but not both. public queryStringBlacklist?: string[]; // Names of query string parameters to include in cache keys. All other parameters are excluded. Either specify QueryStringBlacklist or QueryStringWhitelist, but not both. public queryStringWhitelist?: string[]; } } // ConnectionDrainingConfig contains configuration for connection draining. For now the draining timeout. May manage more settings in the future. export class ConnectionDraining { // Draining timeout in seconds. public drainingTimeoutSec?: number; } // CustomRequestHeadersConfig contains configuration for custom request headers export class CustomRequestHeaders { public headers?: string[]; } // HealthCheckConfig contains configuration for the health check. export class HealthCheck { // CheckIntervalSec is a health check parameter. See https://cloud.google.com/compute/docs/reference/rest/v1/healthChecks. public checkIntervalSec?: number; // HealthyThreshold is a health check parameter. See https://cloud.google.com/compute/docs/reference/rest/v1/healthChecks. public healthyThreshold?: number; // Port is a health check parameter. See https://cloud.google.com/compute/docs/reference/rest/v1/healthChecks. If Port is used, the controller updates portSpecification as well public port?: number; // RequestPath is a health check parameter. See https://cloud.google.com/compute/docs/reference/rest/v1/healthChecks. public requestPath?: string; // TimeoutSec is a health check parameter. See https://cloud.google.com/compute/docs/reference/rest/v1/healthChecks. public timeoutSec?: number; // Type is a health check parameter. See https://cloud.google.com/compute/docs/reference/rest/v1/healthChecks. public type?: string; // UnhealthyThreshold is a health check parameter. See https://cloud.google.com/compute/docs/reference/rest/v1/healthChecks. public unhealthyThreshold?: number; } // IAPConfig contains configuration for IAP-enabled backends. export class Iap { public enabled: boolean; // OAuthClientCredentials contains credentials for a single IAP-enabled backend. public oauthclientCredentials: BackendConfig.Spec.Iap.OauthclientCredentials; constructor(desc: BackendConfig.Spec.Iap) { this.enabled = desc.enabled; this.oauthclientCredentials = desc.oauthclientCredentials; } } export namespace Iap { // OAuthClientCredentials contains credentials for a single IAP-enabled backend. export class OauthclientCredentials { // Direct reference to OAuth client id. public clientID?: string; // Direct reference to OAuth client secret. public clientSecret?: string; // The name of a k8s secret which stores the OAuth client id & secret. public secretName: string; constructor(desc: BackendConfig.Spec.Iap.OauthclientCredentials) { this.clientID = desc.clientID; this.clientSecret = desc.clientSecret; this.secretName = desc.secretName; } } } // LogConfig contains configuration for logging. export class Logging { // This field denotes whether to enable logging for the load balancer traffic served by this backend service. public enable?: boolean; // This field can only be specified if logging is enabled for this backend service. The value of the field must be in [0, 1]. This configures the sampling rate of requests to the load balancer where 1.0 means all logged requests are reported and 0.0 means no logged requests are reported. The default value is 1.0. public sampleRate?: number; } // SecurityPolicyConfig contains configuration for CloudArmor-enabled backends. export class SecurityPolicy { // Name of the security policy that should be associated. public name: string; constructor(desc: BackendConfig.Spec.SecurityPolicy) { this.name = desc.name; } } // SessionAffinityConfig contains configuration for stickyness parameters. export class SessionAffinity { public affinityCookieTtlSec?: number; public affinityType?: string; } } } // BackendConfigList is a list of BackendConfig export class BackendConfigList { // APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources public apiVersion: string; // List of backendconfigs. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md public items: BackendConfig[]; // Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds public kind: string; // ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}. public metadata?: BackendConfigList.Metadata; constructor(desc: BackendConfigList) { this.apiVersion = BackendConfigList.apiVersion; this.items = desc.items.map((i) => new BackendConfig(i)); this.kind = BackendConfigList.kind; this.metadata = desc.metadata; } } export function isBackendConfigList(o: any): o is BackendConfigList { return ( o && o.apiVersion === BackendConfigList.apiVersion && o.kind === BackendConfigList.kind ); } export namespace BackendConfigList { export const apiVersion = 'cloud.google.com/v1'; export const group = 'cloud.google.com'; export const version = 'v1'; export const kind = 'BackendConfigList'; // BackendConfigList is a list of BackendConfig export interface Interface { // List of backendconfigs. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md items: BackendConfig[]; // ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}. metadata?: BackendConfigList.Metadata; } // ListMeta describes metadata that synthetic resources must have, including lists and various status objects. A resource may have only one of {ObjectMeta, ListMeta}. export class Metadata { // continue may be set if the user set a limit on the number of items returned, and indicates that the server has more data available. The value is opaque and may be used to issue another request to the endpoint that served this list to retrieve the next set of available objects. Continuing a consistent list may not be possible if the server configuration has changed or more than a few minutes have passed. The resourceVersion field returned when using this continue value will be identical to the value in the first response, unless you have received this token from an error message. public continue?: string; // remainingItemCount is the number of subsequent items in the list which are not included in this list response. If the list request contained label or field selectors, then the number of remaining items is unknown and the field will be left unset and omitted during serialization. If the list is complete (either because it is not chunking or because this is the last chunk), then there are no more remaining items and this field will be left unset and omitted during serialization. Servers older than v1.15 do not set this field. The intended use of the remainingItemCount is *estimating* the size of a collection. Clients should not rely on the remainingItemCount to be set or to be exact. public remainingItemCount?: number; // String that identifies the server's internal version of this object that can be used by clients to determine when objects have changed. Value must be treated as opaque by clients and passed unmodified back to the server. Populated by the system. Read-only. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency public resourceVersion?: string; // selfLink is a URL representing this object. Populated by the system. Read-only. // // DEPRECATED Kubernetes will stop propagating this field in 1.20 release and the field is planned to be removed in 1.21 release. public selfLink?: string; } }
the_stack
declare module "@hmscore/react-native-hms-ads" { import * as React from "react"; import { NativeSyntheticEvent, ViewProps } from "react-native"; /** * Ad content rating. * Refer this page https://developer.huawei.com/consumer/en/doc/development/HMS-References/ads-api-contentcassification */ export enum ContentClassification { AD_CONTENT_CLASSIFICATION_W = "W", AD_CONTENT_CLASSIFICATION_PI = "PI", AD_CONTENT_CLASSIFICATION_J = "J", AD_CONTENT_CLASSIFICATION_A = "A", AD_CONTENT_CLASSIFICATION_UNKNOWN = "", } /** * Whether to request only non-personalized ads. * Refer this page https://developer.huawei.com/consumer/en/doc/development/HMS-References/ads-api-nonpersonalizedad */ export enum NonPersonalizedAd { ALLOW_ALL = 0, ALLOW_NON_PERSONALIZED = 1, } /** * Child-directed setting. * Refer this page https://developer.huawei.com/consumer/en/doc/development/HMS-References/ads-api-tagforchild */ export enum TagForChild { TAG_FOR_CHILD_PROTECTION_FALSE = 0, TAG_FOR_CHILD_PROTECTION_TRUE = 1, TAG_FOR_CHILD_PROTECTION_UNSPECIFIED = -1, } /** * Setting directed to users under the age of consent. * Refer this page https://developer.huawei.com/consumer/en/doc/development/HMS-References/ads-api-underage */ export enum UnderAge { PROMISE_FALSE = 0, PROMISE_TRUE = 1, PROMISE_UNSPECIFIED = -1, } /** * Gender type * Refer this page https://developer.huawei.com/consumer/en/doc/development/HMS-References/ads-api-gender */ export enum Gender { UNKNOWN = 0, MALE = 1, FEMALE = 2, } /** * Whether to obtain the audio focus during video playback * Refer this page https://developer.huawei.com/consumer/en/doc/development/HMS-References/ads-api-banneradSize */ export enum BannerAdSizes { B_300_250 = "300_250", B_320_50 = "320_50", B_320_100 = "320_100", B_360_57 = "360_57", B_360_144 = "360_144", B_SMART = "smart", B_DYNAMIC = "dynamic", B_INVALID = "invalid", } /** * Option for functions that can use Huawei SDK or * [Aidl](https://developer.android.com/guide/components/aidl) service. */ export enum CallMode { SDK = "sdk", AIDL = "aidl", // Will not be used anymore } /** * Debug consent setting. */ export enum DebugNeedConsent { DEBUG_DISABLED = 0, DEBUG_NEED_CONSENT = 1, DEBUG_NOT_NEED_CONSENT = 2, } /** * Consent status. */ export enum ConsentStatus { PERSONALIZED = 0, NON_PERSONALIZED = 1, UNKNOWN = 2, } /** * Choice icon position constants * Refer this page https://developer.huawei.com/consumer/en/doc/development/HMS-References/ads-api-nativeadconfiguration-choicesposition */ export enum ChoicesPosition { TOP_LEFT = 0, TOP_RIGHT = 1, BOTTOM_RIGHT = 2, BOTTOM_LEFT = 3, INVISIBLE = 4, } /** * Orientation constant * Refer this page https://developer.huawei.com/consumer/en/doc/development/HMS-References/ads-api-nativeadconfiguration-direction */ export enum Direction { ANY = 0, PORTRAIT = 1, LANDSCAPE = 2, } /** * Whether to obtain the audio focus during video playback * Refer this page https://developer.huawei.com/consumer/en/doc/development/HMS-References/ads-api-audiofocustype */ export enum AudioFocusType { GAIN_AUDIO_FOCUS_ALL = 0, NOT_GAIN_AUDIO_FOCUS_WHEN_MUTE = 1, NOT_GAIN_AUDIO_FOCUS_ALL = 2, } /** * Native ad media types */ export enum NativeMediaTypes { VIDEO = "video", IMAGE_SMALL = "image_small", IMAGE_LARGE = "image_large", } /** * Options for scaling the bounds of an image * Refer this page https://developer.android.com/reference/android/widget/ImageView.ScaleType */ export enum ScaleTypes { MATRIX = "MATRIX", FIT_XY = "FIT_XY", FIT_START = "FIT_START", FIT_CENTER = "FIT_CENTER", FIT_END = "FIT_END", CENTER = "CENTER", CENTER_CROP = "CENTER_CROP", CENTER_INSIDE = "CENTER_INSIDE", } /** * Options for scaling the bounds of an image * Refer this page https://developer.android.com/reference/android/widget/ImageView.ScaleType */ export enum DetailedCreativeTypes { BIG_IMG = 901, VIDEO = 903, THREE_IMG = 904, SMALL_IMG = 905, SINGLE_IMG = 909, SHORT_TEXT = 913, LONG_TEXT = 914, } /** * Ad request options. */ interface RequestOptions { /** * The OAID. */ adContentClassification?: ContentClassification; /** * The OAID. */ appCountry?: string; /** * The OAID. */ appLang?: string; /** * The OAID. */ nonPersonalizedAd?: NonPersonalizedAd; /** * The OAID. */ tagForChildProtection?: TagForChild; /** * The OAID. */ tagForUnderAgeOfPromise?: UnderAge; /** * Whether the location information is carried in an ad request. */ requestLocation?: boolean; } /** * Ad provider. */ interface AdProvider { /** * Id of ad provider. */ id: ContentClassification; /** * Name of ad provider. */ name: string; /** * The url for privacy policy. */ privacyPolicyUrl: string; /** * The service area for ad (ex: 'Global' or 'Asia'). */ serviceArea: string; } /** * Consent information from api result. */ interface ConsentResult { /** * Status of consent. */ consentStatus: ConsentStatus; /** * Shows whether consent is needed. */ isNeedConsent: boolean; /** * Ad provider list */ adProviders: AdProvider[]; } /** * Ad consent object to be submitted. */ interface Consent { /** * Consent option. */ consentStatus?: ConsentStatus; /** * DebugNeedConsent option. */ debugNeedConsent?: DebugNeedConsent; /** * UnderAge option. */ underAgeOfPromise?: UnderAge; /** * Device Id */ testDeviceId?: string; } /** * Information about advertised clients. */ interface AdvertisingIdClientInfo { /** * The OAID. */ id: string; /** * 'Limit ad tracking' setting. */ isLimitAdTrackingEnabled: boolean; } /** * HMSOaid module. */ export const HMSOaid = { /** * Obtains the OAID and 'Limit ad tracking' setting. */ getAdvertisingIdInfo(callMode: CallMode): Promise<AdvertisingIdClientInfo>;, /** * Verifies the OAID and 'Limit ad tracking' setting */ verifyAdvertisingId(advertisingInfo: AdvertisingIdClientInfo): Promise<boolean>;, }; /** * Server-side verification parameter. */ interface VerifyConfig { /** * User Id. */ userId: number; /** * 'Custom data. */ data: boolean; } /** * Ad request parameters. */ interface AdParam { /** * Ad content rating. Check ContentClassification for possible values. */ adContentClassification?: ContentClassification; /** * Country code corresponding to the language in which an ad needs to be * returned for an app. */ appCountry?: string; /** * Language in which an ad needs to be returned for an app. */ appLang?: string; /** * Home country code. */ belongCountryCode?: string; /** * Gender. Check Gender for possible values. */ gender?: Gender; /** * The setting of requesting personalized ads. Check NonPersonalizedAd * for possible values. */ nonPersonalizedAd?: NonPersonalizedAd; /** * Origin of request. */ requestOrigin?: string; /** * The setting of processing ad requests according to the COPPA. * Check TagForChild for possible values. */ tagForChildProtection?: TagForChild; /** * The setting of processing ad requests as directed to users under * the age of consent. Check UnderAge for possible values. */ tagForUnderAgeOfPromise?: UnderAge; /** * Targeting content url. */ targetingContentUrl?: string; /** * Whether the location information is carried in an ad request. */ requestLocation?: boolean; /** * Requested creative type of a native ad. */ detailedCreativeTypes?: number[]; } /** * Information about the reward item in a rewarded ad. */ interface Reward { /** * The name of a reward item. */ name: string; /** * The number of reward items. */ amount: number; } /** * Information about the reward item in a rewarded ad. */ interface RewardAd { /** * User id. */ userId: string; /** * Custom data. */ data: string; /** * Reward item. */ reward: Reward; /** * Shows whether a rewarded ad is successfully loaded. */ isLoaded: boolean; } /** * HMSReward module for reward ads. */ export const HMSReward = { /** * Sets ad slot id. */ setAdId(adSlotId: string): Promise<null>;, /** * Sets to display ad on HMS Core app */ loadWithAdId(loadWithAdId: boolean): Promise<null>;, /** * Sets user id */ setUserId(userID: string): Promise<null>;, /** * Sets custom data in string */ setData(data: string): Promise<null>;, /** * Sets custom data in string */ setVerifyConfig(verifyConfig: VerifyConfig): Promise<null>;, /** * Sets parameters of ad request */ setAdParam(adParam: AdParam): Promise<null>;, /** * Sets custom data in string */ pause(): Promise<null>;, /** * Resumes the ad. */ resume(): Promise<null>;, /** * Destroys the ad. */ destroy(): Promise<null>;, /** * Shows the ad. */ show(): Promise<null>;, /** * Requests ad. */ loadAd(): Promise<null>;, /** * Checks whether ad is successfully loaded */ isLoaded(): Promise<boolean>;, /** * Add listener for the event when ad loads. */ adLoadedListenerAdd(listenerFn: (response: RewardAd) => void): void;, /** * Remove the listener for the event when ad loads. */ adLoadedListenerRemove(): void;, /** * Add listener for the event when fails to load. */ adFailedToLoadListenerAdd(listenerFn: (response: Error) => void): void;, /** * Remove the listener for the event when fails to load. */ adFailedToLoadListenerRemove(): void;, /** * Add listener for the event when ad fails to be displayed. */ adFailedToShowListenerAdd(listenerFn: (response: Error) => void): void;, /** * Remove the listener for the event when ad fails to be displayed. */ adFailedToShowListenerRemove(): void;, /** * Add listener for the event when ad is opened. */ adOpenedListenerAdd(listenerFn: () => void): void;, /** * Remove the listener for the event when ad is opened. */ adOpenedListenerRemove(): void;, /** * Add listener for the event when ad is closed. */ adClosedListenerAdd(listenerFn: () => void): void;, /** * Remove the listener for the event when ad is closed. */ adClosedListenerRemove(): void;, /** * Add listener for the event when a reward is provided. */ adRewardedListenerAdd(listenerFn: (response: Reward) => void): void;, /** * Remove the listener for the event when a reward is provided. */ adRewardedListenerRemove(): void;, /** * Add listener for the event when user leaves the app. */ adLeftAppListenerAdd(listenerFn: () => void): void;, /** * Remove the listener for the event when user leaves the app. */ adLeftAppListenerRemove(): void;, /** * Add listener for the event when ad is completed. */ adCompletedListenerAdd(listenerFn: () => void): void;, /** * Remove the listener for the event when ad is completed. */ adCompletedListenerRemove(): void;, /** * Add listener for the event when ad is started. */ adStartedListenerAdd(listenerFn: () => void): void;, /** * Remove the listener for the event when ad is started. */ adStartedListenerRemove(): void;, /** * Remove all listeners for events of HMSReward */ allListenersRemove(): void;, }; /** * HMSSplash module for splash ads */ export const HMSSplash = { /** * Sets ad slot id. */ setAdId(adSlotId: string): Promise<null>;, /** * Sets logo text. */ setLogoText(logoText: string): Promise<null>;, /** * Sets copyright text. */ setCopyrightText(cpyrightText: string): Promise<null>;, /** * Sets screen orientation */ setOrientation(orientation: number): Promise<null>;, /** * Sets default app launch image in portrait mode, * which is displayed before a splash ad is displayed */ setSloganResource(sloganResource: string): Promise<null>;, /** * Sets default app launch image in landscape mode, * which is displayed before a splash ad is displayed. */ setWideSloganResource(wideSloganResource: string): Promise<null>;, /** * Sets app logo. */ setLogoResource(logoResource: string): Promise<null>;, /** * Sets app text resource. */ setMediaNameResource(mediaNameResource: string): Promise<null>;, /** * Sets the audio focus preemption policy for a video splash ad. */ setAudioFocusType(audioFocusType: AudioFocusType): Promise<null>;, /** * Sets parameters of ad request */ setAdParam(adParam: AdParam): Promise<null>;, /** * Pauses ad. */ pause(): Promise<null>;, /** * Resumes the ad. */ resume(): Promise<null>;, /** * Destroys the ad. */ destroy(): Promise<null>;, /** * Shows the ad. */ show(): Promise<null>;, /** * Checks whether ad is successfully loaded. */ isLoaded(): Promise<boolean>;, /** * Checks whether a splash ad is being loaded. */ isLoading(): Promise<boolean>;, /** * Add listener for the event when ad loads. */ adLoadedListenerAdd(listenerFn: () => void): void;, /** * Remove the listener for the event when ad loads. */ adLoadedListenerRemove(): void;, /** * Add listener for the event when ad fails to load. */ adFailedToLoadListenerAdd(listenerFn: (response: Error) => void): void;, /** * Remove the listener for the event when ad fails to load. */ adFailedToLoadListenerRemove(): void;, /** * Add listener for the event when ad is dismissed. */ adDismissedListenerAdd(listenerFn: (response: Error) => void): void;, /** * Remove the listener for the event when ad is dismissed. */ adDismissedListenerRemove(): void;, /** * Add listener for the event when ad is shown. */ adShowedListenerAdd(listenerFn: (response: Error) => void): void;, /** * Remove the listener for the event when ad is shown. */ adShowedListenerRemove(): void;, /** * Add listener for the event when ad is clicked. */ adClickListenerAdd(listenerFn: (response: Error) => void): void;, /** * Remove the listener for the event when ad is clicked. */ adClickListenerRemove(): void;, /** * Remove all listeners for events of HMSSplash */ allListenersRemove(): void;, }; /** * Interstitial ad. */ interface InterstitialAd { /** * The ad slot id. */ adId: string; /** * Shows whether ad loading is complete. */ isLoaded: boolean; /** * Shows whether ads are being loaded. */ isLoading: boolean; } /** * HMSInterstitial module for Interstitial ads */ export const HMSInterstitial = { /** * Sets ad slot id. */ setAdId(adSlotId: string): Promise<null>;, /** * Sets parameters of ad request */ setAdParam(adParam: AdParam): Promise<null>;, /** * Initiates a request to load an ad. */ loadAd(): Promise<null>;, /** * Displays an interstitial ad. */ show(): Promise<null>;, /** * Checks whether ad loading is complete. */ isLoaded(): Promise<boolean>;, /** * Checks whether ad is loading. */ isLoading(): Promise<boolean>;, /** * Add listener for the event when ad fails to load. */ adFailedListenerAdd(listenerFn: (response: Error) => void): void;, /** * Remove the listener for the event when ad fails to load. */ adFailedListenerRemove(): void;, /** * Add listener for the event when ad is closed. */ adClosedListenerAdd(listenerFn: () => void): void;, /** * Remove the listener for the event when ad is closed. */ adClosedListenerRemove(): void;, /** * Add listener for the event when the user leaves the app. */ adLeaveListenerAdd(listenerFn: () => void): void;, /** * Remove the listener for the event the user leaves the app. */ adLeaveListenerRemove(): void;, /** * Add listener for the event when ad is displayed. */ adOpenedListenerAdd(listenerFn: () => void): void;, /** * Remove the listener for the event when ad is displayed. */ adOpenedListenerRemove(): void;, /** * Add listener for the event when ad loads. */ adLoadedListenerAdd(listenerFn: (response: InterstitialAd) => void): void;, /** * Remove the listener for the event when ad loads. */ adLoadedListenerRemove(): void;, /** * Add listener for the event when ad is clicked. */ adClickedListenerAdd(listenerFn: () => void): void;, /** * Remove the listener for the event when ad is clicked. */ adClickedListenerRemove(): void;, /** * Add listener for the event when ad impression is detected. */ adImpressionListenerAdd(listenerFn: () => void): void;, /** * Remove the listener for the event when ad impression is detected. */ adImpressionListenerRemove(): void;, /** * Add listener for the event when ad is completed. */ adCompletedListenerAdd(listenerFn: () => void): void;, /** * Remove the listener for the event when ad is completed. */ adCompletedListenerRemove(): void;, /** * Add listener for the event when ad starts. */ adStartedListenerAdd(listenerFn: () => void): void;, /** * Remove the listener for the event when ad starts. */ adStartedListenerRemove(): void;, /** * Remove all listeners for events of HMSInterstitial */ allListenersRemove(): void;, }; /** * Describes the install referrer information. */ interface ReferrerDetails { /** * Install referrer information. */ installReferrer: string; /** * The app installation timestamp, in milliseconds. */ installBeginTimestampMillisecond: number; /** * The app installation timestamp, in seconds. */ installBeginTimestampSeconds: number; /** * The ad click timestamp, in milliseconds. */ referrerClickTimestampMillisecond: number; /** * The ad click timestamp, in seconds. */ referrerClickTimestampSeconds: number; } /** * Install referrer connection response. */ interface InstallReferrerResponse { /** * Response code. */ responseCode: number; /** * Response message. */ responseMessage: string; } /** * HMSInstallReferrer module for install referrer functions */ export const HMSInstallReferrer = { /** * Starts to connect to the install referrer service. The first string * argument should be one of values of [CallMode](#callmode). And the * boolean argument indicates test mode. The last string argument is the * name of the package that the service receives information about. */ startConnection(callMode: CallMode, isTest: boolean, pkgName: string): Promise<null>;, /** * Ends the service connection and releases all occupied resources. */ endConnection(): Promise<null>;, /** * Obtains install referrer information. */ getReferrerDetails(): Promise<ReferrerDetails>;, /** * Indicates whether the service connection is ready. */ isReady(): Promise<boolean>;, /** * Add listener for the event when service connection is complete */ serviceConnectedListenerAdd(listenerFn: (response: InstallReferrerResponse) => void): void;, /** * Remove the listener for the event when service connection is complete */ serviceConnectedListenerRemove(): void;, /** * Add listener for the event when service is crashed or killed. */ serviceDisconnectedListenerAdd(listenerFn: () => void): void;, /** * Remove the listener for the event when service is crashed or killed. */ serviceDisconnectedListenerRemove(): void;, /** * Remove all listeners for events of HMSInstallReferrer */ allListenersRemove(): void;, }; /** * React prop defining banner ad sizes. */ interface BannerAdSizeProp { /** * Banner ad sizes. `BannerAdSizes` for possible values. */ bannerAdSize: BannerAdSizes; } /** * Banner information from banner load event. */ interface BannerInfo { /** * Ad slot id. */ adId: string; /** * Shows whether banner is loading. */ isLoading: boolean; /** * BannerAdSize information. */ bannerAdSize: BannerAdSizes; } /** * Ad error. */ interface Error { /** * Error code. */ errorCode: number; /** * Error message. */ errorMessage: string; } /** * Events triggered by the map. */ interface AdEvent<T = {}> extends NativeSyntheticEvent<T> {} /** * Props for <HMSBanner> component. */ interface HMSBannerProps extends ViewProps { /** * The banner ad size. */ bannerAdSize: BannerAdSizeProp; /** * Ad slot id. */ adId: string; /** * Ad request parameter. */ adParam?: AdParam; /** * Listener for the event called when ad loads. */ onAdLoaded?: (event: AdEvent<{}>) => void; /** * Listener for the event called when ad fails to load. */ onAdFailed?: (event: AdEvent<Error>) => void; /** * Listener for the event called when ad is opened. */ onAdOpened?: (event: AdEvent<{}>) => void; /** * Listener for the event called when ad is clicked. */ onAdClicked?: (event: AdEvent<{}>) => void; /** * Listener for the event called when ad is closed. */ onAdClosed?: (event: AdEvent<{}>) => void; /** * Listener for the event called when ad impression is detected. */ onAdImpression?: (event: AdEvent<{}>) => void; /** * Listener for the event called when user leaves the app. */ onAdLeave?: (event: AdEvent<{}>) => void; } /** * React component that shows banner ads. */ export class HMSBanner extends React.Component<HMSBannerProps, any> { /** * Gets information related to HMSBanner component. */ getInfo(): Promise<BannerInfo>; /** * Loads banner. */ loadAd(): void; /** * Sets a rotation interval for banner ads. Input is rotation * interval, in seconds. It should range from 30 to 120. */ setRefresh(interval: number): void; /** * Pauses any additional processing related to ad. */ pause(): void; /** * Resumes ad after the pause() method is called last time. */ resume(): void; /** * Destroys ad. */ destroy(): void; } interface PlayTime { /** * Played duration, in milliseconds. */ playTime: number; } interface WithPercentage { /** * Playback progress, in percentage. */ percentage: number; } interface WithExtra { /** * Additional information. */ extra: number; } interface WithError { /** * Error information. */ error: Error; } /** * Instream ad information. */ interface InstreamAd { /** * Indicates whether ad has been clicked. */ isClicked: boolean; /** * Indicates whether an ad has expired. */ isExpired: boolean; /** * Indicates whether ad is an image ad */ isImageAd: boolean; /** * Indicates whether ad has been displayed. */ isShown: boolean; /** * Indicates whether ad is a video ad */ isVideoAd: boolean; /** * Duration of a roll ad, in milliseconds. */ duration: number; /** * Redirection link to `Why this ad`. */ whyThisAd: string; /** * Text to be displayed on a button. */ callToAction: string; /** * Indicates whether a task is an ad task. */ adSign: string; /** * Ad source. */ adSource: string; } interface InstreamInfo { /** * Indicates whether ad is being played. */ isPlaying: boolean; /** * Indicates whether ad is loading. */ isLoading: boolean; /** * Ad slot id */ adId: string; /** * Maximum total duration of roll ads, in seconds */ totalDuration: number; /** * Maximum number of roll ads. */ maxCount: number; /** * List of roll ads. */ instreamAds: InstreamAd[]; } /** * Props for <HMSInstream> component. */ interface HMSInstreamProps extends ViewProps { /** * Ad slot id. */ adId: string; /** * Maximum number of roll ads. */ maxCount: number; /** * Maximum total duration of roll ads, in seconds */ totalDuration: number; /** * Ad request parameter. */ adParam?: AdParam; /** * Listener for the event called when ad is muted */ onMute?: (event: AdEvent<{}>) => void; /** * Listener for the event called when ad is unmuted */ onUnmute?: (event: AdEvent<{}>) => void; /** * Listener for the event called when roll ads are successfully loaded. */ onAdLoaded?: (event: AdEvent<{}>) => void; /** * Listener for the event called when roll ads fail to be loaded. */ onAdFailed?: (event: AdEvent<Error>) => void; /** * Listener for the event called when a roll ad is switched to another. */ onSegmentMediaChange?: (event: AdEvent<InstreamAd>) => void; /** * Listener for the event called during the playback of a roll ad. */ onMediaProgress?: (event: AdEvent<PlayTime | WithPercentage>) => void; /** * Listener for the event called when the playback of a roll ad starts. */ onMediaStart?: (event: AdEvent<PlayTime>) => void; /** * Listener for the event called when the playback of a roll ad is paused. */ onMediaPause?: (event: AdEvent<PlayTime>) => void; /** * Listener for the event called when the playback of a roll ad stops. */ onMediaStop?: (event: AdEvent<PlayTime>) => void; /** * Listener for the event called when the playback of a roll ad * is complete. */ onMediaCompletion?: (event: AdEvent<PlayTime>) => void; /** * Listener for the event called when a roll ad fails to be played. */ onMediaError?: (event: AdEvent<PlayTime | WithExtra | WithError>) => void; /** * Listener for the event called when ad is clicked. */ onClick?: (event: AdEvent<{}>) => void; } /** * React component that shows instream ads. */ export class HMSInstream extends React.Component<HMSInstreamProps, any> { /** * Gets information related to HMSInstream component. */ getInfo(): Promise<InstreamInfo>; /** * Loads instream ad. */ loadAd(): void; /** * Sets loaded ads to view in order to show them */ register(): void; /** * Mutes ad. */ mute(): void; /** * Unmutes ad. */ unmute(): void; /** * Stops ad. */ stop(): void; /** * Pauses ad. */ pause(): void; /** * Plays ad. */ play(): void; /** * Destroys ad. */ destroy(): void; } /** * React prop defining media type of the ad. */ interface DisplayFormProp { /** * Error code. */ mediaType: NativeMediaTypes; /** * Ad slot id. */ adId: string; } /** * Ad size. */ interface AdSize { /** * Ad height, in dp. */ height: number; /** * Ad width, in dp. */ width: number; } /** * Video configuration used to control video playback. */ interface VideoConfiguration { /** * The video playback scenario where the audio focus needs to be obtained. */ audioFocusType?: AudioFocusType; /** * The setting for using custom video control. */ isCustomizeOperateRequested?: boolean; /** * Setting indicating whether a video ad can be displayed * in full-screen mode upon a click. */ isClickToFullScreenRequested?: boolean; /** * The setting for muting video when it starts. */ isStartMuted?: boolean; } /** * Native ad configuration. */ interface NativeAdConfiguration { /** * Ad size. */ adSize?: AdSize; /** * Position of an ad choice icon. */ choicesPosition?: ChoicesPosition; /** * Direction of an ad image. */ mediaDirection?: Direction; /** * Aspect ratio of an ad image. */ mediaAspect?: number; /** * Video Configuration. */ videoConfiguration?: VideoConfiguration; /** * The setting for requesting multiple ad images. */ isRequestMultiImages?: boolean; /** * The setting for enabling the SDK to download native ad images. */ isReturnUrlsForImages?: boolean; } /** * Styles of the components in native ads. */ interface AdTextStyle { /** * Font size. */ fontSize?: number; /** * Color. */ color?: number; /** * Background color. */ backgroundColor?: number; /** * Visibility. */ visibility?: boolean; } /** * View options for components in Native ads. */ interface ViewOptionsProp { /** * The option for showing media content. */ showMediaContent?: boolean; /** * The image scale type. */ mediaImageScaleType?: ScaleTypes; /** * The style of ad source. */ adSourceTextStyle?: AdTextStyle; /** * The style of ad flag. */ adFlagTextStyle?: AdTextStyle; /** * The style of ad title. */ titleTextStyle?: AdTextStyle; /** * The style of ad description. */ descriptionTextStyle?: AdTextStyle; /** * The style of ad call-to-action button. */ callToActionStyle?: AdTextStyle; } interface DislikeAdReason { /** * The reason why a user dislikes an ad. */ description: string; } /** * Video controller, which implements video control such as * playing, pausing, and muting a video. */ interface VideoOperator { /** * The video aspect ratio. */ aspectRatio: number; /** * Shows whether ad content contains a video. */ hasVideo: boolean; /** * Shows whether a custom video control is used for a video ad. */ isCustomizeOperateEnabled: boolean; /** * Shows whether click to full screen option enabled for a video ad. */ isClickToFullScreenEnabled: boolean; } /** * Native ad information. */ interface NativeAd { /** * Indicates whether a task is an ad task. */ adSign: string; /** * Ad source. */ adSource: string; /** * Ad description. */ description: string; /** * The text to be displayed on a button, for example, * View Details or Install. */ callToAction: string; /** * Ad title. */ title: string; /** * The choices of not displaying the current ad. */ dislikeAdReasons: DislikeAdReason[]; /** * Redirection link to Why this ad. */ whyThisAd: string; /** * Unique ID of an ad. */ uniqueId: string; /** * Ad creative type. */ creativeType: string; /** * Video operator used for the ad. */ videoOperator: VideoOperator | Muted; /** * Shows whether custom tap gestures are enabled. */ isCustomClickAllowed: boolean; /** * Shows whether custom ad closing is enabled. */ isCustomDislikeThisAdEnabled: boolean; } interface NativeAdLoader { /** * Shows whether ads are being loaded. */ isLoading: boolean; } /** * Information related to native ad returned when ad is loaded. */ interface NativeInfo { /** * Native ad information. */ nativeAd: NativeAd; /** * Native ad configuration information. */ nativeAdConfiguration: NativeAdConfiguration; /** * Native ad loader information. */ nativeAdLoader: NativeAdLoader; } interface Muted { /** * Shows whether a video is muted. */ isMuted: boolean; } /** * Props for <HMSNative> component. */ interface HMSNativeProps extends ViewProps { /** * The object parameter that has ad slot id and media type information. */ displayForm: DisplayFormProp; /** * Ad request parameter. */ adParam?: AdParam; /** * Native ad configuration parameter. */ nativeConfig?: NativeAdConfiguration; /** * View options parameter. */ viewOptions?: ViewOptionsProp; /** * Listener for the event called when ad loads. */ onNativeAdLoaded?: (event: AdEvent<{}>) => void; /** * Listener for the event called when ad is disliked. */ onAdDisliked?: (event: AdEvent<{}>) => void; /** * Listener for the event called when ad fails to load. */ onAdFailed?: (event: AdEvent<Error>) => void; /** * Listener for the event called when ad impression is detected. */ onAdImpression?: (event: AdEvent<{}>) => void; /** * Listener for the event called when ad video starts playing. */ onVideoStart?: (event: AdEvent<{}>) => void; /** * Listener for the event called when ad video plays. */ onVideoPlay?: (event: AdEvent<{}>) => void; /** * Listener for the event called when ad video ends. */ onVideoEnd?: (event: AdEvent<{}>) => void; /** * Listener for the event called when ad video pauses. */ onVideoPause?: (event: AdEvent<{}>) => void; /** * Listener for the event called when the mute status of a video changes. */ onVideoMute?: (event: AdEvent<Muted>) => void; } /** * React component that shows native ads. */ export class HMSNative extends React.Component<HMSNativeProps, any> { /** * Gets information related to HMSNative component. */ getInfo(): Promise<NativeInfo>; /** * Loads native ad. */ loadAd(): void; /** * Dislikes ad with description. */ dislikeAd(reason: string): void; /** * Destroys ad. */ destroy(): void; /** * Goes to the page explaining why an ad is displayed. */ gotoWhyThisAdPage(): void; /** * Enables custom tap gestures. */ setAllowCustomClick(): void; /** * Reports a custom tap gesture. */ recordClickEvent(): void; /** * Reports an ad impression. */ recordImpressionEvent(data: object): void; } /** * HMSAds module */ export default { /** * Initializes the HUAWEI Ads SDK. The function returns * a promise that resolves a string 'Hw Ads Initialized'. */ init(): Promise<string>;, /** * Enables HMSLogger capability which is used for sending usage * analytics of Ads SDK's methods to improve the service quality. */ enableLogger(): Promise<null>;, /** * Disables HMSLogger capability which is used for sending usage * analytics of Ads SDK's methods to improve the service quality. */ disableLogger(): Promise<null>;, /** * Obtains the version number of the HUAWEI Ads SDK. The function * returns a promise that resolves a string of the version number. */ getSDKVersion(): Promise<string>;, /** * Provides the global ad request configuration. */ setRequestOptions(requestOptions: RequestOptions): Promise<RequestOptions>;, /** * Obtains the global request configuration. */ getRequestOptions(): Promise<RequestOptions>;, /** * Provides ad consent configuration. */ setConsent(consent: Consent): Promise<ConsentResult>;, /** * Sets the user consent string that complies with [TCF 2.0](https://iabeurope.eu/tcf-2-0/) */ setConsentString(consent: string): Promise<null>;, /** * Obtains ad consent configuration. */ checkConsent(): Promise<ConsentResult>;, }; }
the_stack
import { Wallet, providers, BigNumber } from 'ethers'; import { ExtensionTypes, PaymentTypes, RequestLogicTypes } from '@requestnetwork/types'; import { _getPaymentUrl, hasSufficientFunds, payRequest, swapToPayRequest, isSolvent, } from '../../src/payment'; import { payNearInputDataRequest } from '../../src/payment/near-input-data'; import * as btcModule from '../../src/payment/btc-address-based'; import * as erc20Module from '../../src/payment/erc20'; import * as ethModule from '../../src/payment/eth-input-data'; import * as nearUtils from '../../src/payment/utils-near'; /* eslint-disable @typescript-eslint/no-unused-expressions */ /* eslint-disable @typescript-eslint/await-thenable */ const mnemonic = 'candy maple cake sugar pudding cream honey rich smooth crumble sweet treat'; const provider = new providers.JsonRpcProvider('http://localhost:8545'); const wallet = Wallet.fromMnemonic(mnemonic).connect(provider); const fakeErc20: RequestLogicTypes.ICurrency = { type: RequestLogicTypes.CURRENCY.ERC20, value: 'any', network: 'live', }; const nearCurrency = { type: RequestLogicTypes.CURRENCY.ETH, network: 'aurora', value: 'near', }; describe('payRequest', () => { afterEach(() => { jest.resetAllMocks(); }); it('cannot pay a declarative request', async () => { const request: any = { extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.DECLARATIVE]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ANY_DECLARATIVE, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: {}, version: '1.0', }, }, }; await expect(payRequest(request, wallet)).rejects.toThrowError( 'Payment network pn-any-declarative is not supported', ); }); it('cannot pay a BTC request', async () => { const request: any = { extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.BITCOIN_ADDRESS_BASED]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_BITCOIN_ADDRESS_BASED, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: {}, version: '1.0', }, }, }; await expect(payRequest(request, wallet)).rejects.toThrowError( 'Payment network pn-bitcoin-address-based is not supported', ); }); it('should call the ETH payment method', async () => { const mock = jest.fn(); (ethModule as any).payEthInputDataRequest = mock; const request: any = { extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.ETH_INPUT_DATA]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ETH_INPUT_DATA, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: {}, version: '1.0', }, }, }; await payRequest(request, wallet); expect(mock).toHaveBeenCalledTimes(1); }); it('should call the ERC20 payment method', async () => { const spy = jest.fn(); (erc20Module as any).payErc20Request = spy; const request: any = { extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.ERC20_PROXY_CONTRACT]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_PROXY_CONTRACT, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: {}, version: '1.0', }, }, }; await payRequest(request, wallet); expect(spy).toHaveBeenCalledTimes(1); }); it('cannot pay if the currency network is not implemented with web3', async () => { const request: any = { currencyInfo: { network: 'aurora', }, extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.ETH_INPUT_DATA]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_PROXY_CONTRACT, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: {}, version: '1.0', }, }, }; await expect(payRequest(request, wallet)).rejects.toThrowError( 'Payment currency network aurora is not supported', ); }); }); describe('payNearInputDataRequest', () => { afterEach(() => { jest.resetAllMocks(); }); it('pays a NEAR request with NEAR payment method (with mock)', async () => { // A mock is used to bypass Near wallet connection for address validation and contract interaction const paymentSpy = jest .spyOn(nearUtils, 'processNearPayment') .mockReturnValue(Promise.resolve()); const mockedNearWalletConnection = { account: () => ({ functionCall: () => true, state: () => Promise.resolve({ amount: 100 }), }), } as any; const request: any = { requestId: '0x123', currencyInfo: nearCurrency, extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.NATIVE_TOKEN]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_NATIVE_TOKEN, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: { salt: '0x456', paymentAddress: '0x789', }, version: '0.2.0', }, }, }; await payNearInputDataRequest(request, mockedNearWalletConnection, '1'); expect(paymentSpy).toHaveBeenCalledWith( expect.anything(), 'aurora', '1', '0x789', '700912030bd973e3', '0.2.0', ); }); it('throws when tyring to pay another payment extension', async () => { // A mock is used to bypass Near wallet connection for address validation and contract interaction const paymentSpy = jest .spyOn(nearUtils, 'processNearPayment') .mockReturnValue(Promise.resolve()); const mockedNearWalletConnection = { account: () => ({ functionCall: () => true, state: () => Promise.resolve({ amount: 100 }), }), } as any; const request: any = { requestId: '0x123', currencyInfo: nearCurrency, extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.ETH_INPUT_DATA]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ETH_INPUT_DATA, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: { salt: '0x456', paymentAddress: '0x789', }, version: '0.2.0', }, }, }; await expect( payNearInputDataRequest(request, mockedNearWalletConnection, '1'), ).rejects.toThrowError('request cannot be processed, or is not an pn-native-token request'); expect(paymentSpy).toHaveBeenCalledTimes(0); }); }); describe('swapToPayRequest', () => { const swapSettings = { // eslint-disable-next-line no-magic-numbers deadline: Date.now() + 1000, maxInputAmount: BigNumber.from('204'), path: ['0xany', '0xanyother'], }; it('cannot pay a declarative request', async () => { const request: any = { extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.DECLARATIVE]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ANY_DECLARATIVE, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: {}, version: '1.0', }, }, }; await expect(swapToPayRequest(request, swapSettings, wallet)).rejects.toThrowError( 'Payment network pn-any-declarative is not supported', ); }); it('cannot pay a BTC request', async () => { const request: any = { extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.BITCOIN_ADDRESS_BASED]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_BITCOIN_ADDRESS_BASED, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: {}, version: '1.0', }, }, }; await expect(swapToPayRequest(request, swapSettings, wallet)).rejects.toThrowError( 'Payment network pn-bitcoin-address-based is not supported', ); }); it('cannot swap to pay an ETH request', async () => { const request: any = { extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.ETH_INPUT_DATA]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ETH_INPUT_DATA, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: {}, version: '1.0', }, }, }; await expect(swapToPayRequest(request, swapSettings, wallet)).rejects.toThrowError( 'Payment network pn-eth-input-data is not supported', ); }); it('cannot swap to pay a non-EVM request currency', async () => { const request: any = { currencyInfo: { network: 'aurora', }, extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.ETH_INPUT_DATA]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ETH_INPUT_DATA, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: {}, version: '1.0', }, }, }; await expect(swapToPayRequest(request, swapSettings, wallet)).rejects.toThrowError( 'Payment currency network aurora is not supported', ); }); it('should call the ERC20 payment method', async () => { const spy = jest.fn(); (erc20Module as any).payErc20Request = spy; const request: any = { extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.ERC20_FEE_PROXY_CONTRACT]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_FEE_PROXY_CONTRACT, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: {}, version: '1.0', }, }, }; await swapToPayRequest(request, swapSettings, wallet); expect(spy).toHaveBeenCalledTimes(1); }); }); describe('hasSufficientFunds', () => { afterEach(() => { jest.resetAllMocks(); }); it('should throw an error on unsupported network', async () => { const request: any = { currencyInfo: { network: 'testnet', }, extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.BITCOIN_ADDRESS_BASED]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_BITCOIN_ADDRESS_BASED, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: {}, version: '1.0', }, }, }; await expect(hasSufficientFunds(request, '')).rejects.toThrowError( 'Payment network pn-bitcoin-address-based is not supported', ); }); it('should call the ETH getBalance method', async () => { const fakeProvider: any = { getBalance: jest.fn().mockReturnValue(Promise.resolve(BigNumber.from('200'))), }; const request: any = { balance: { balance: '0', }, currencyInfo: { network: 'rinkeby', type: RequestLogicTypes.CURRENCY.ETH, }, expectedAmount: '100', extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.ETH_INPUT_DATA]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ETH_INPUT_DATA, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: {}, version: '1.0', }, }, }; await hasSufficientFunds(request, 'abcd', { provider: fakeProvider }); expect(fakeProvider.getBalance).toHaveBeenCalledTimes(1); }); it('should call the ERC20 payment method', async () => { const spy = jest .spyOn(erc20Module, 'getAnyErc20Balance') .mockReturnValue(Promise.resolve(BigNumber.from('200'))); const fakeProvider: any = { getBalance: () => Promise.resolve(BigNumber.from('200')), }; const request: any = { balance: { balance: '0', }, currencyInfo: { network: 'rinkeby', type: RequestLogicTypes.CURRENCY.ERC20, value: '0xany', }, expectedAmount: '100', extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.ERC20_PROXY_CONTRACT]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_PROXY_CONTRACT, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: {}, version: '1.0', }, }, }; await hasSufficientFunds(request, 'abcd', { provider: fakeProvider }); expect(spy).toHaveBeenCalledTimes(1); }); it('should skip ETH balance checks for smart contract wallets', async () => { const walletConnectProvider = { ...provider, getBalance: jest.fn().mockReturnValue(Promise.resolve(BigNumber.from('0'))), provider: { wc: { _peerMeta: { name: 'Gnosis Safe Multisig', }, }, }, }; const mock = jest .spyOn(erc20Module, 'getAnyErc20Balance') .mockReturnValue(Promise.resolve(BigNumber.from('200'))); // eslint-disable-next-line no-magic-numbers const solvency = await isSolvent('any', fakeErc20, 100, { provider: walletConnectProvider as any, }); expect(solvency).toBeTruthy(); expect(mock).toHaveBeenCalledTimes(1); }); it('should check ETH balance checks for non-smart contract wallets', async () => { const walletConnectProvider = { ...provider, getBalance: jest.fn().mockReturnValue(Promise.resolve(BigNumber.from('0'))), provider: { wc: { _peerMeta: { name: 'Definitely not a smart contract wallet', }, }, }, }; const mock = jest .spyOn(erc20Module, 'getAnyErc20Balance') .mockReturnValue(Promise.resolve(BigNumber.from('200'))); // eslint-disable-next-line no-magic-numbers const solvency = await isSolvent('any', fakeErc20, 100, { provider: walletConnectProvider as any, }); expect(solvency).toBeFalsy(); expect(mock).toHaveBeenCalledTimes(1); }); it('should check NEAR solvency with NEAR methods', async () => { const mockedNearWalletConnection = { account: () => ({ state: jest.fn().mockReturnValue(Promise.resolve({ amount: 100 })), }), } as any; const solvency = await isSolvent('any', nearCurrency, 100, { nearWalletConnection: mockedNearWalletConnection, }); expect(solvency).toBeTruthy(); }); it('should check NEAR non-solvency with NEAR methods', async () => { const nearWalletConnection = { account: () => ({ state: jest.fn().mockReturnValue(Promise.resolve({ amount: 99 })), }), } as any; const solvency = await isSolvent('any', nearCurrency, 100, { nearWalletConnection }); expect(solvency).toBeFalsy(); }); }); describe('_getPaymentUrl', () => { it('should throw an error on unsupported network', () => { const request: any = { extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.DECLARATIVE]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ANY_DECLARATIVE, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: {}, version: '1.0', }, }, }; expect(() => _getPaymentUrl(request)).toThrowError( 'Payment network pn-any-declarative is not supported', ); }); it('should call the BTC payment url method', async () => { const mock = jest.fn(); (btcModule as any).getBtcPaymentUrl = mock; const request: any = { extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.BITCOIN_ADDRESS_BASED]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_BITCOIN_ADDRESS_BASED, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: {}, version: '1.0', }, }, }; _getPaymentUrl(request); expect(mock).toHaveBeenCalledTimes(1); }); it('should call the ETH payment url method', async () => { const spy = jest.fn(); (ethModule as any)._getEthPaymentUrl = spy; const request: any = { extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.ETH_INPUT_DATA]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ETH_INPUT_DATA, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: {}, version: '1.0', }, }, }; _getPaymentUrl(request); expect(spy).toHaveBeenCalledTimes(1); }); it('should call the ERC20 payment url method', async () => { const spy = jest.fn(); (erc20Module as any)._getErc20PaymentUrl = spy; const request: any = { extensions: { [PaymentTypes.PAYMENT_NETWORK_ID.ERC20_PROXY_CONTRACT]: { events: [], id: ExtensionTypes.ID.PAYMENT_NETWORK_ERC20_PROXY_CONTRACT, type: ExtensionTypes.TYPE.PAYMENT_NETWORK, values: {}, version: '1.0', }, }, }; _getPaymentUrl(request); expect(spy).toHaveBeenCalledTimes(1); }); });
the_stack
/// <reference types="node" /> /** * The OSRM method is the main constructor for creating an OSRM instance. * An OSRM instance requires a .osrm network, which is prepared by the OSRM Backend C++ library. * * https://github.com/Project-OSRM/node-osrm/blob/master/docs/api.md */ declare class OSRM { constructor(options: string); // tslint:disable-next-line:unified-signatures constructor(options: OSRM.PathConstructorOptions); // tslint:disable-next-line:unified-signatures constructor(options: OSRM.SharedMemoryConstructorOptions); /** * Returns the fastest route between two or more coordinates while visiting the waypoints in order. */ route(options: OSRM.RouteOptions, callback: (err: Error, results: OSRM.RouteResults) => void): void; /** * Returns Object containing waypoints. waypoints: array of Ẁaypoint objects sorted by distance to the input coordinate. * Each object has an additional distance property, which is the distance in meters to the supplied input coordinate. */ nearest(options: OSRM.NearestOptions, callback: (err: Error, results: OSRM.NearestResults) => void): void; /** * Returns Object containing durations, sources, and destinations. durations: array of arrays that stores the matrix in * row-major order. durations[i][j] gives the travel time from the i-th waypoint to the j-th waypoint. Values are given * in seconds. sources: array of Ẁaypoint objects describing all sources in order. destinations: array of Ẁaypoint * objects describing all destinations in order. fallback_speed_cells: (optional) if fallback_speed is used, will be an * array of arrays of row,column values, indicating which cells contain estimated values. */ table(options: OSRM.TableOptions, callback: (err: Error, results: OSRM.TableResults) => void): void; /** * Returns Buffer contains a Protocol Buffer encoded vector tile. */ tile(XYZ: OSRM.Tile, callback: (err: Error, results: Buffer) => void): void; /** * Returns Object containing tracepoints and matchings. tracepoints Array of Ẁaypoint objects representing all points * of the trace in order. If the trace point was ommited by map matching because it is an outlier, the entry will be * null. Each Waypoint object includes two additional properties, 1) matchings_index: Index to the Route object in * matchings the sub-trace was matched to, 2) waypoint_index: Index of the waypoint inside the matched route. matchings * is an array of Route objects that assemble the trace. Each Route object has an additional confidence property, which * is the confidence of the matching. float value between 0 and 1. 1 is very confident that the matching is correct. */ match(options: OSRM.MatchOptions, callback: (err: Error, results: OSRM.MatchResults) => void): void; /** * Returns Object containing waypoints and trips. waypoints: an array of Waypoint objects representing all waypoints * in input order. Each Waypoint object has the following additional properties, 1) trips_index: index to trips of the * sub-trip the point was matched to, and 2) waypoint_index: index of the point in the trip. trips: an array of Route * objects that assemble the trace. */ trip(options: OSRM.TripOptions, callback: (err: Error, results: OSRM.TripResults) => void): void; } declare namespace OSRM { const version: number; type AlgorithmTypes = 'CH' | 'CoreCH' | 'MLD'; type GeometriesTypes = 'polyline' | 'geojson' | 'polyline6'; type OverviewTypes = 'full' | 'simplified' | 'false'; type SnappingTypes = 'default' | 'any'; type ApproachTypes = 'unrestricted' | 'curb'; type FallbackCoordinateTypes = 'input' | 'snapped'; type GapTypes = 'split' | 'ignore'; type Coordinate = number[]; type Polyline = string; type Bearing = number[]; type Radius = number; type Hint = string; type Duration = number; type Distance = number; type Tile = [number, number, number]; type StepManeuverTypes = 'turn' | 'new name' | 'depart' | 'arrive' | 'merge' | 'ramp' | 'on ramp' | 'off ramp' | 'fork' | 'end of road' | 'use lane' | 'continue' | 'roundabout' | 'rotary' | 'roundabout turn' | 'notification' | 'exit roundabout' | 'exit rotary'; type Indication = 'uturn' | 'sharp right' | 'right' | 'slight rigth' | 'straight' |'slight left' | 'left' | 'sharp left'; interface LineString { type: 'LineString'; coordinates: Coordinate[]; } interface Waypoint { hint: string; distance: number; name: string; location: Coordinate; } /** * Annotation of the whole route leg with fine-grained information about each segment or node id. * * https://github.com/Project-OSRM/osrm-backend/blob/master/docs/http.md#annotation-object */ interface Annotation { /** * The distance, in metres, between each pair of coordinates */ distance: number[]; /** * The duration between each pair of coordinates, in seconds. Does not include the duration of any turns. */ duration: number[]; /** * The index of the datasource for the speed between each pair of coordinates. 0 is the default profile, other values are supplied via --segment-speed-file to osrm-contract */ datasources: number[]; /** * The OSM node ID for each coordinate along the route, excluding the first/last user-supplied coordinates */ nodes: number[]; /** * The weights between each pair of coordinates. Does not include any turn costs. */ weight: number[]; /** * Convenience field, calculation of distance / duration rounded to one decimal place */ speed: number[]; } /** * Represents a route between two waypoints. * * https://github.com/Project-OSRM/osrm-backend/blob/master/docs/http.md#routeleg-object */ interface RouteLeg { /** * The distance traveled by this route leg, in float meters. */ distance: number; /** * The estimated travel time, in float number of seconds. */ duration: number; /** * The calculated weight of the route leg. */ weight: number; /** * Summary of the route taken as string. Depends on the summary parameter: * - true: Names of the two major roads used. Can be empty if route is too short. * - false: empty string */ summary: string; /** * Depends on the steps parameter. * - true: array of RouteStep objects describing the turn-by-turn instructions * - false: empty array */ steps: RouteStep[]; /** * Additional details about each coordinate along the route geometry: * - true: An Annotation object containing node ids, durations distances and * - false: weights undefined */ annotation: Annotation; } /** * A step consists of a maneuver such as a turn or merge, followed by a distance of travel along a single way to the subsequent step. * * https://github.com/Project-OSRM/osrm-backend/blob/master/docs/http.md#routestep-object */ interface RouteStep { /** * The distance of travel from the maneuver to the subsequent step, in float meters. */ distance: number; /** * The estimated travel time, in float number of seconds. */ duration: number; /** * The unsimplified geometry of the route segment, depending on the geometries parameter. */ geometry: Polyline | LineString; /** * The calculated weight of the step. */ weight: number; /** * The name of the way along which travel proceeds. */ name: string; /** * A reference number or code for the way. Optionally included, if ref data is available for the given way. */ ref: string; /** * The pronunciation hint of the way name. Will be undefined if there is no pronunciation hit. */ pronunciation: string; /** * The destinations of the way. Will be undefined if there are no destinations. */ destinations: string; /** * The exit numbers or names of the way. Will be undefined if there are no exit numbers or names. */ exits: string; /** * A string signifying the mode of transportation. */ mode: string; /** * A StepManeuver object representing the maneuver. */ maneuver: StepManeuver; /** * A list of Intersection objects that are passed along the segment, the very first belonging to the StepManeuver */ intersections: Intersection[]; /** * The name for the rotary. Optionally included, if the step is a rotary and a rotary name is available. */ rotary_name: string; /** * The pronunciation hint of the rotary name. Optionally included, if the step is a rotary and a rotary pronunciation is available. */ rotary_pronunciation: string; } /** * https://github.com/Project-OSRM/osrm-backend/blob/master/docs/http.md#stepmaneuver-object */ interface StepManeuver { /** * A [longitude, latitude] pair describing the location of the turn. */ location: Coordinate; /** * The clockwise angle from true north to the direction of travel immediately before the maneuver. Range 0-359. */ bearing_before: number; /** * The clockwise angle from true north to the direction of travel immediately after the maneuver. Range 0-359. */ bearing_after: number; /** * A string indicating the type of maneuver. * new identifiers might be introduced without API change Types unknown to the client should be handled like the turn type, * the existence of correct modifier values is guranteed. */ type: StepManeuverTypes; /** * An optional string indicating the direction change of the maneuver. */ modifier: Indication; } /** * A Lane represents a turn lane at the corresponding turn location. * * https://github.com/Project-OSRM/osrm-backend/blob/master/docs/http.md#lane-object */ interface Lane { indications: Indication[]; valid: boolean; } /** * An intersection gives a full representation of any cross-way the path passes bay. * For every step, the very first intersection (intersections[0]) corresponds to the location of the StepManeuver. * Further intersections are listed for every cross-way until the next turn instruction. * * https://github.com/Project-OSRM/osrm-backend/blob/master/docs/http.md#intersection-object */ interface Intersection { /** * A [longitude, latitude] pair describing the location of the turn. */ location: Coordinate; /** * A list of bearing values (e.g. [0,90,180,270]) that are available at the intersection. * The bearings describe all available roads at the intersection. Values are between 0-359 (0=true north) */ bearings: number[]; /** * An array of strings signifying the classes (as specified in the profile) of the road exiting the intersection. */ classes: string[]; /** * A list of entry flags, corresponding in a 1:1 relationship to the bearings. * A value of true indicates that the respective road could be entered on a valid route. * false indicates that the turn onto the respective road would violate a restriction. */ entry: string[]; /** * index into bearings/entry array. Used to calculate the bearing just before the turn. * Namely, the clockwise angle from true north to the direction of travel immediately before the maneuver/passing the intersection. * Bearings are given relative to the intersection. To get the bearing in the direction of driving, the bearing has to be rotated by a value of 180. * The value is not supplied for depart maneuvers. */ in: number; /** * index into the bearings/entry array. Used to extract the bearing just after the turn. * Namely, The clockwise angle from true north to the direction of travel immediately after the maneuver/passing the intersection. * The value is not supplied for arrive maneuvers. */ out: number; /** * Array of Lane objects that denote the available turn lanes at the intersection. * If no lane information is available for an intersection, the lanes property will not be present. */ lanes: Lane; } /** * Object used to describe waypoint on a route. * * https://github.com/Project-OSRM/osrm-backend/blob/master/docs/http.md#waypoint-object */ interface Waypoint { distance: number; /** * Name of the street the coordinate snapped to */ name: string; /** * Array that contains the [longitude, latitude] pair of the snapped coordinate */ location: Coordinate; /** * Unique internal identifier of the segment (ephemeral, not constant over data updates) * This can be used on subsequent request to significantly speed up the query and to connect multiple services. * E.g. you can use the hint value obtained by the nearest query as hint values for route inputs. */ hint: string; } /** * Represents a route through (potentially multiple) waypoints. * * https://github.com/Project-OSRM/osrm-backend/blob/master/docs/http.md#route-object */ interface Route { /** * The distance traveled by the route, in float meters. */ distance: number; /** * The estimated travel time, in float number of seconds. */ duration: number; /** * The whole geometry of the route value depending on overview parameter, format depending on the geometries parameter. See RouteStep's geometry property for a parameter documentation. */ geometry?: any; /** * The calculated weight of the route. */ weight: number; /** * The name of the weight profile used during extraction phase. */ weight_name: string; /** * The legs between the given waypoints, an array of RouteLeg objects. */ legs: RouteLeg[]; } /** * Each Waypoint object includes two additional properties, * * 1) matchings_index: Index to the Route object in matchings the sub-trace was matched to, * 2) waypoint_index: Index of the waypoint inside the matched route. * * https://github.com/Project-OSRM/node-osrm/blob/master/docs/api.md#match */ interface MatchWaypoint extends Waypoint { matchings_index: number[]; waypoint_index: number[]; } /** * matchings is an array of Route objects that assemble the trace. * Each Route object has an additional confidence property, * which is the confidence of the matching. * float value between 0 and 1. 1 is very confident that the matching is correct. * * https://github.com/Project-OSRM/node-osrm/blob/master/docs/api.md#match */ interface MatchRoute extends Route { confidence: number; } /** * Each Waypoint object has the following additional properties, * * 1) trips_index: index to trips of the sub-trip the point was matched to, and * 2) waypoint_index: index of the point in the trip. * * https://github.com/Project-OSRM/node-osrm/blob/master/docs/api.md#trip */ interface TripWaypoint extends Waypoint { trips_index: number; waypoint_index: number; } interface Options { /** * The coordinates this request will use, coordinates as [{lon},{lat}] values, in decimal degrees. */ coordinates?: Coordinate[]; /** * Limits the search to segments with given bearing in degrees towards true north in clockwise direction. Can be null or an array of [{value},{range}] with integer 0 .. 360,integer 0 .. 180. */ bearings?: Bearing[] | null; /** * Limits the coordinate snapping to streets in the given radius in meters. Can be null (unlimited, default) or double >= 0. */ radiuses?: Radius[] | null; /** * Hints for the coordinate snapping. Array of base64 encoded strings. */ hints?: Hint[]; /** * Whether or not adds a Hint to the response which can be used in subsequent requests. (optional, default true) */ generate_hints?: boolean; } /** * https://github.com/Project-OSRM/osrm-backend/blob/master/docs/nodejs/api.md */ interface ConstructorOptions { /** * The algorithm to use for routing. Can be 'CH', 'CoreCH' or 'MLD'. Default is 'CH'. Make sure you prepared the dataset with the correct toolchain. */ algorithm?: AlgorithmTypes; /** * DEPRECATED Old behaviour: Path to a file on disk to store the memory using mmap. Current behaviour: setting this * value is the same as setting mmap_memory: true. */ memory_file?: string; /** * Map on-disk files to virtual memory addresses (mmap), rather than loading into RAM. */ mmap_memory?: boolean; /** * Max. locations supported in trip query (default: unlimited). */ max_locations_trip?: number; /** * Max. locations supported in viaroute query (default: unlimited). */ max_locations_viaroute?: number; /** * Max. locations supported in distance table query (default: unlimited). */ max_locations_distance_table?: number; /** * Max. locations supported in map-matching query (default: unlimited). */ max_locations_map_matching?: number; /** * Max. results supported in nearest query (default: unlimited). */ max_results_nearest?: number; /** * Max.number of alternatives supported in alternative routes query (default: 3). */ max_alternatives?: number; } interface PathConstructorOptions extends ConstructorOptions { /** * The path to the .osrm files. This is mutually exclusive with setting {options.shared_memory} to true. */ path?: string; } interface SharedMemoryConstructorOptions extends ConstructorOptions { /** * Connects to the persistent shared memory datastore. This requires you to run osrm-datastore prior to creating an OSRM object. */ shared_memory?: boolean; /** * Connects to the persistent shared memory datastore defined by --dataset_name option when running osrm-datastore. * This requires you to run osrm-datastore --dataset_name prior to creating an OSRM object. */ dataset_name?: string; } /** * Returns the fastest route between two or more coordinates while visiting the waypoints in order. * * https://github.com/Project-OSRM/osrm-backend/blob/master/docs/nodejs/api.md#route */ interface RouteOptions extends Options { /** * Boolean: Search for alternative routes. (optional, default false) * Number: Search for up to this many alternative routes. Please note that even if alternative routes are requested, a result cannot be guaranteed. (optional, default 0) */ alternatives?: boolean | number; /** * Return route steps for each route leg. (optional, default false) */ steps?: boolean; /** * An array with strings of duration, nodes, distance, weight, datasources, speed or boolean for enabling/disabling all. (optional, default false) */ annotations?: boolean | Array<('duration' | 'nodes' | 'distance' | 'weight' | 'datasources' | 'speed')> | boolean; /** * Returned route geometry format (influences overview and per step). Can also be geojson. (optional, default polyline) */ geometries?: GeometriesTypes; /** * Add overview geometry either full, simplified according to highest zoom level it could be display on, or not at all (false). (optional, default simplified) */ overview?: OverviewTypes; /** * Forces the route to keep going straight at waypoints and don't do a uturn even if it would be faster. Default value depends on the profile. */ continue_straight?: boolean; /** * Keep waypoints on curb side. Can be null (unrestricted, default) or curb. */ approaches?: ApproachTypes[] | null; /** * Indices to coordinates to treat as waypoints. If not supplied, all coordinates are waypoints. Must include first and last coordinate index. null/true/false */ waypoints?: number[]; /** * Which edges can be snapped to, either default, or any. default only snaps to edges marked by the profile as is_startpoint, any will allow snapping to any edge in the routing graph. */ snapping?: SnappingTypes; } /** * Snaps a coordinate to the street network and returns the nearest n matches. * * Note: coordinates in the general options only supports a single {longitude},{latitude} entry. * * https://github.com/Project-OSRM/osrm-backend/blob/master/docs/nodejs/api.md#nearest */ interface NearestOptions extends Options { /** * Number of nearest segments that should be returned. Must be an integer greater than or equal to 1. (optional, default 1) */ number?: number; /** * Keep waypoints on curb side. Can be null (unrestricted, default) or curb. */ approaches?: ApproachTypes[] | null; /** * Which edges can be snapped to, either default, or any. default only snaps to edges marked by the profile as is_startpoint, any will allow snapping to any edge in the routing graph. */ snapping?: SnappingTypes; } /** * Computes duration table for the given locations. Allows for both symmetric and asymmetric tables. Optionally returns distance table. * * https://github.com/Project-OSRM/osrm-backend/blob/master/docs/nodejs/api.md#table */ interface TableOptions extends Options { /** * An array of index elements (0 <= integer < #coordinates) to use location with given index as source. Default is to use all. */ sources?: number[]; /** * An array of index elements (0 <= integer < #coordinates) to use location with given index as destination. Default is to use all. */ destinations?: number[]; /** * Keep waypoints on curb side. Can be null (unrestricted, default) or curb. */ approaches?: ApproachTypes | null; /** * Replace null responses in result with as-the-crow-flies estimates based on fallback_speed. Value is in metres/second. */ fallback_speed?: number; /** * Either input (default) or snapped. If using a fallback_speed, use either the user-supplied coordinate (input), * or the snapped coordinate (snapped) for calculating the as-the-crow-flies distance between two points. */ fallback_coordinate?: FallbackCoordinateTypes; /** * Multiply the table duration values in the table by this number for more controlled input into a route optimization solver. */ scale_factor?: number; /** * Which edges can be snapped to, either default, or any. default only snaps to edges marked by the profile as is_startpoint, * any will allow snapping to any edge in the routing graph. */ snapping?: SnappingTypes; /** * Return the requested table or tables in response. Can be ['duration'] (return the duration matrix, default) or * ['duration', distance'] (return both the duration matrix and the distance matrix). */ annotations?: Array<('duration' | 'distance')>; } /** * Map matching matches given GPS points to the road network in the most plausible way. Please note the request might * result multiple sub-traces. Large jumps in the timestamps (>60s) or improbable transitions lead to trace splits if * a complete matching could not be found. The algorithm might not be able to match all points. Outliers are removed * if they can not be matched successfully. * * https://github.com/Project-OSRM/osrm-backend/blob/master/docs/nodejs/api.md#match */ interface MatchOptions extends Options { /** * Return route steps for each route. (optional, default false) */ steps?: boolean; /** * An array with strings of duration, nodes, distance, weight, datasources, speed or boolean for enabling/disabling all. (optional, default false) */ annotations?: Array<('duration' | 'nodes' | 'distance' | 'weight' | 'datasources' | 'speed')> | boolean; /** * Returned route geometry format (influences overview and per step). Can also be geojson. (optional, default polyline) */ geometries?: GeometriesTypes; /** * Add overview geometry either full, simplified according to highest zoom level it could be display on, or not at all (false). (optional, default simplified) */ overview?: OverviewTypes; /** * Timestamp of the input location (integers, UNIX-like timestamp). */ timestamps?: number[]; /** * Standard deviation of GPS precision used for map matching. If applicable use GPS accuracy. Can be null for default value 5 meters or double >= 0. */ radiuses?: number[]; /** * Allows the input track splitting based on huge timestamp gaps between points. Either split or ignore (optional, default split). */ gaps?: GapTypes; /** * Allows the input track modification to obtain better matching quality for noisy tracks (optional, default false). */ tidy?: boolean; /** * Indices to coordinates to treat as waypoints. If not supplied, all coordinates are waypoints. Must include first and last coordinate index. */ waypoints?: number[]; /** * Which edges can be snapped to, either default, or any. default only snaps to edges marked by the profile as is_startpoint, any will allow snapping to any edge in the routing graph. */ snapping?: SnappingTypes; } /** * The trip plugin solves the Traveling Salesman Problem using a greedy heuristic (farthest-insertion algorithm) for * 10 or _ more waypoints and uses brute force for less than 10 waypoints. The returned path does not have to be the * shortest path, _ as TSP is NP-hard it is only an approximation. * * https://github.com/Project-OSRM/osrm-backend/blob/master/docs/nodejs/api.md#trip */ interface TripOptions extends Options { /** * Return route steps for each route. (optional, default false) */ steps?: boolean; /** * An array with strings of duration, nodes, distance, weight, datasources, speed or boolean for enabling/disabling all. (optional, default false) */ annotations?: Array<('duration' | 'nodes' | 'distance' | 'weight' | 'datasources' | 'speed')> | boolean; /** * Returned route geometry format (influences overview and per step). Can also be geojson. (optional, default polyline) */ geometries?: GeometriesTypes; /** * Add overview geometry either full, simplified (optional, default simplified) */ overview?: OverviewTypes; /** * Return route is a roundtrip. (optional, default true) */ roundtrip?: boolean; /** * Return route starts at any or first coordinate. (optional, default any) */ source?: 'any' | 'first'; /** * Return route ends at any or last coordinate. (optional, default any) */ destination?: 'any' | 'last'; /** * Keep waypoints on curb side. Can be null (unrestricted, default) or curb. */ approaches?: ApproachTypes | null; /** * Which edges can be snapped to, either default, or any. default only snaps to edges marked by the profile as is_startpoint, any will allow snapping to any edge in the routing graph. */ snapping?: SnappingTypes; } interface RouteResults { waypoints: Waypoint[]; routes: Route[]; } interface NearestResults { waypoints: Waypoint[]; } interface TableResults { durations: Duration[][]; distances?: Distance[][]; sources: Waypoint[]; destinations: Waypoint[]; fallback_speed_cells?: number[]; } interface MatchResults { tracepoints: MatchWaypoint[]; matchings: MatchRoute[]; } interface TripResults { waypoints: TripWaypoint[]; trips: Route[]; } } export = OSRM;
the_stack
import {BaseFileSystem, FileSystem, BFSCallback, FileSystemOptions} from '../core/file_system'; import {ApiError, ErrorCode} from '../core/api_error'; import {FileFlag, ActionType} from '../core/file_flag'; import {copyingSlice} from '../core/util'; import {File} from '../core/file'; import Stats from '../core/node_fs_stats'; import {NoSyncFile} from '../generic/preload_file'; import {xhrIsAvailable, asyncDownloadFile, syncDownloadFile, getFileSizeAsync, getFileSizeSync} from '../generic/xhr'; import {fetchIsAvailable, fetchFileAsync, fetchFileSizeAsync} from '../generic/fetch'; import {FileIndex, isFileInode, isDirInode} from '../generic/file_index'; /** * Try to convert the given buffer into a string, and pass it to the callback. * Optimization that removes the needed try/catch into a helper function, as * this is an uncommon case. * @hidden */ function tryToString(buff: Buffer, encoding: string, cb: BFSCallback<string>) { try { cb(null, buff.toString(encoding)); } catch (e) { cb(e); } } /** * Configuration options for a HTTPRequest file system. */ export interface HTTPRequestOptions { // URL to a file index as a JSON file or the file index object itself, generated with the make_http_index script. // Defaults to `index.json`. index?: string | object; // Used as the URL prefix for fetched files. // Default: Fetch files relative to the index. baseUrl?: string; // Whether to prefer XmlHttpRequest or fetch for async operations if both are available. // Default: false preferXHR?: boolean; } interface AsyncDownloadFileMethod { (p: string, type: 'buffer', cb: BFSCallback<Buffer>): void; (p: string, type: 'json', cb: BFSCallback<any>): void; (p: string, type: string, cb: BFSCallback<any>): void; } interface SyncDownloadFileMethod { (p: string, type: 'buffer'): Buffer; (p: string, type: 'json'): any; (p: string, type: string): any; } function syncNotAvailableError(): never { throw new ApiError(ErrorCode.ENOTSUP, `Synchronous HTTP download methods are not available in this environment.`); } /** * A simple filesystem backed by HTTP downloads. You must create a directory listing using the * `make_http_index` tool provided by BrowserFS. * * If you install BrowserFS globally with `npm i -g browserfs`, you can generate a listing by * running `make_http_index` in your terminal in the directory you would like to index: * * ``` * make_http_index > index.json * ``` * * Listings objects look like the following: * * ```json * { * "home": { * "jvilk": { * "someFile.txt": null, * "someDir": { * // Empty directory * } * } * } * } * ``` * * *This example has the folder `/home/jvilk` with subfile `someFile.txt` and subfolder `someDir`.* */ export default class HTTPRequest extends BaseFileSystem implements FileSystem { public static readonly Name = "HTTPRequest"; public static readonly Options: FileSystemOptions = { index: { type: ["string", "object"], optional: true, description: "URL to a file index as a JSON file or the file index object itself, generated with the make_http_index script. Defaults to `index.json`." }, baseUrl: { type: "string", optional: true, description: "Used as the URL prefix for fetched files. Default: Fetch files relative to the index." }, preferXHR: { type: "boolean", optional: true, description: "Whether to prefer XmlHttpRequest or fetch for async operations if both are available. Default: false" } }; /** * Construct an HTTPRequest file system backend with the given options. */ public static Create(opts: HTTPRequestOptions, cb: BFSCallback<HTTPRequest>): void { if (opts.index === undefined) { opts.index = `index.json`; } if (typeof(opts.index) === "string") { asyncDownloadFile(opts.index, "json", (e, data?) => { if (e) { cb(e); } else { cb(null, new HTTPRequest(data, opts.baseUrl)); } }); } else { cb(null, new HTTPRequest(opts.index, opts.baseUrl)); } } public static isAvailable(): boolean { return xhrIsAvailable || fetchIsAvailable; } public readonly prefixUrl: string; private _index: FileIndex<{}>; private _requestFileAsyncInternal: AsyncDownloadFileMethod; private _requestFileSizeAsyncInternal: (p: string, cb: BFSCallback<number>) => void; private _requestFileSyncInternal: SyncDownloadFileMethod; private _requestFileSizeSyncInternal: (p: string) => number; private constructor(index: object, prefixUrl: string = '', preferXHR: boolean = false) { super(); // prefix_url must end in a directory separator. if (prefixUrl.length > 0 && prefixUrl.charAt(prefixUrl.length - 1) !== '/') { prefixUrl = prefixUrl + '/'; } this.prefixUrl = prefixUrl; this._index = FileIndex.fromListing(index); if (fetchIsAvailable && (!preferXHR || !xhrIsAvailable)) { this._requestFileAsyncInternal = fetchFileAsync; this._requestFileSizeAsyncInternal = fetchFileSizeAsync; } else { this._requestFileAsyncInternal = asyncDownloadFile; this._requestFileSizeAsyncInternal = getFileSizeAsync; } if (xhrIsAvailable) { this._requestFileSyncInternal = syncDownloadFile; this._requestFileSizeSyncInternal = getFileSizeSync; } else { this._requestFileSyncInternal = syncNotAvailableError; this._requestFileSizeSyncInternal = syncNotAvailableError; } } public empty(): void { this._index.fileIterator(function(file: Stats) { file.fileData = null; }); } public getName(): string { return HTTPRequest.Name; } public diskSpace(path: string, cb: (total: number, free: number) => void): void { // Read-only file system. We could calculate the total space, but that's not // important right now. cb(0, 0); } public isReadOnly(): boolean { return true; } public supportsLinks(): boolean { return false; } public supportsProps(): boolean { return false; } public supportsSynch(): boolean { // Synchronous operations are only available via the XHR interface for now. return xhrIsAvailable; } /** * Special HTTPFS function: Preload the given file into the index. * @param [String] path * @param [BrowserFS.Buffer] buffer */ public preloadFile(path: string, buffer: Buffer): void { const inode = this._index.getInode(path); if (isFileInode<Stats>(inode)) { if (inode === null) { throw ApiError.ENOENT(path); } const stats = inode.getData(); stats.size = buffer.length; stats.fileData = buffer; } else { throw ApiError.EISDIR(path); } } public stat(path: string, isLstat: boolean, cb: BFSCallback<Stats>): void { const inode = this._index.getInode(path); if (inode === null) { return cb(ApiError.ENOENT(path)); } let stats: Stats; if (isFileInode<Stats>(inode)) { stats = inode.getData(); // At this point, a non-opened file will still have default stats from the listing. if (stats.size < 0) { this._requestFileSizeAsync(path, function(e: ApiError, size?: number) { if (e) { return cb(e); } stats.size = size!; cb(null, Stats.clone(stats)); }); } else { cb(null, Stats.clone(stats)); } } else if (isDirInode(inode)) { stats = inode.getStats(); cb(null, stats); } else { cb(ApiError.FileError(ErrorCode.EINVAL, path)); } } public statSync(path: string, isLstat: boolean): Stats { const inode = this._index.getInode(path); if (inode === null) { throw ApiError.ENOENT(path); } let stats: Stats; if (isFileInode<Stats>(inode)) { stats = inode.getData(); // At this point, a non-opened file will still have default stats from the listing. if (stats.size < 0) { stats.size = this._requestFileSizeSync(path); } } else if (isDirInode(inode)) { stats = inode.getStats(); } else { throw ApiError.FileError(ErrorCode.EINVAL, path); } return stats; } public open(path: string, flags: FileFlag, mode: number, cb: BFSCallback<File>): void { // INVARIANT: You can't write to files on this file system. if (flags.isWriteable()) { return cb(new ApiError(ErrorCode.EPERM, path)); } const self = this; // Check if the path exists, and is a file. const inode = this._index.getInode(path); if (inode === null) { return cb(ApiError.ENOENT(path)); } if (isFileInode<Stats>(inode)) { const stats = inode.getData(); switch (flags.pathExistsAction()) { case ActionType.THROW_EXCEPTION: case ActionType.TRUNCATE_FILE: return cb(ApiError.EEXIST(path)); case ActionType.NOP: // Use existing file contents. // XXX: Uh, this maintains the previously-used flag. if (stats.fileData) { return cb(null, new NoSyncFile(self, path, flags, Stats.clone(stats), stats.fileData)); } // @todo be lazier about actually requesting the file this._requestFileAsync(path, 'buffer', function(err: ApiError, buffer?: Buffer) { if (err) { return cb(err); } // we don't initially have file sizes stats.size = buffer!.length; stats.fileData = buffer!; return cb(null, new NoSyncFile(self, path, flags, Stats.clone(stats), buffer)); }); break; default: return cb(new ApiError(ErrorCode.EINVAL, 'Invalid FileMode object.')); } } else { return cb(ApiError.EISDIR(path)); } } public openSync(path: string, flags: FileFlag, mode: number): File { // INVARIANT: You can't write to files on this file system. if (flags.isWriteable()) { throw new ApiError(ErrorCode.EPERM, path); } // Check if the path exists, and is a file. const inode = this._index.getInode(path); if (inode === null) { throw ApiError.ENOENT(path); } if (isFileInode<Stats>(inode)) { const stats = inode.getData(); switch (flags.pathExistsAction()) { case ActionType.THROW_EXCEPTION: case ActionType.TRUNCATE_FILE: throw ApiError.EEXIST(path); case ActionType.NOP: // Use existing file contents. // XXX: Uh, this maintains the previously-used flag. if (stats.fileData) { return new NoSyncFile(this, path, flags, Stats.clone(stats), stats.fileData); } // @todo be lazier about actually requesting the file const buffer = this._requestFileSync(path, 'buffer'); // we don't initially have file sizes stats.size = buffer.length; stats.fileData = buffer; return new NoSyncFile(this, path, flags, Stats.clone(stats), buffer); default: throw new ApiError(ErrorCode.EINVAL, 'Invalid FileMode object.'); } } else { throw ApiError.EISDIR(path); } } public readdir(path: string, cb: BFSCallback<string[]>): void { try { cb(null, this.readdirSync(path)); } catch (e) { cb(e); } } public readdirSync(path: string): string[] { // Check if it exists. const inode = this._index.getInode(path); if (inode === null) { throw ApiError.ENOENT(path); } else if (isDirInode(inode)) { return inode.getListing(); } else { throw ApiError.ENOTDIR(path); } } /** * We have the entire file as a buffer; optimize readFile. */ public readFile(fname: string, encoding: string, flag: FileFlag, cb: BFSCallback<string | Buffer>): void { // Wrap cb in file closing code. const oldCb = cb; // Get file. this.open(fname, flag, 0x1a4, function(err: ApiError, fd?: File) { if (err) { return cb(err); } cb = function(err: ApiError, arg?: Buffer) { fd!.close(function(err2: any) { if (!err) { err = err2; } return oldCb(err, arg); }); }; const fdCast = <NoSyncFile<HTTPRequest>> fd; const fdBuff = <Buffer> fdCast.getBuffer(); if (encoding === null) { cb(err, copyingSlice(fdBuff)); } else { tryToString(fdBuff, encoding, cb); } }); } /** * Specially-optimized readfile. */ public readFileSync(fname: string, encoding: string, flag: FileFlag): any { // Get file. const fd = this.openSync(fname, flag, 0x1a4); try { const fdCast = <NoSyncFile<HTTPRequest>> fd; const fdBuff = <Buffer> fdCast.getBuffer(); if (encoding === null) { return copyingSlice(fdBuff); } return fdBuff.toString(encoding); } finally { fd.closeSync(); } } private _getHTTPPath(filePath: string): string { if (filePath.charAt(0) === '/') { filePath = filePath.slice(1); } return this.prefixUrl + filePath; } /** * Asynchronously download the given file. */ private _requestFileAsync(p: string, type: 'buffer', cb: BFSCallback<Buffer>): void; private _requestFileAsync(p: string, type: 'json', cb: BFSCallback<any>): void; private _requestFileAsync(p: string, type: string, cb: BFSCallback<any>): void; private _requestFileAsync(p: string, type: string, cb: BFSCallback<any>): void { this._requestFileAsyncInternal(this._getHTTPPath(p), type, cb); } /** * Synchronously download the given file. */ private _requestFileSync(p: string, type: 'buffer'): Buffer; private _requestFileSync(p: string, type: 'json'): any; private _requestFileSync(p: string, type: string): any; private _requestFileSync(p: string, type: string): any { return this._requestFileSyncInternal(this._getHTTPPath(p), type); } /** * Only requests the HEAD content, for the file size. */ private _requestFileSizeAsync(path: string, cb: BFSCallback<number>): void { this._requestFileSizeAsyncInternal(this._getHTTPPath(path), cb); } private _requestFileSizeSync(path: string): number { return this._requestFileSizeSyncInternal(this._getHTTPPath(path)); } }
the_stack
import { Comparable } from "@siteimprove/alfa-comparable"; import { Length, Keyword, Number, Percentage, Token, Component, } from "@siteimprove/alfa-css"; import { Device } from "@siteimprove/alfa-device"; import { Equatable } from "@siteimprove/alfa-equatable"; import { Functor } from "@siteimprove/alfa-functor"; import { Iterable } from "@siteimprove/alfa-iterable"; import { Serializable } from "@siteimprove/alfa-json"; import { Mapper } from "@siteimprove/alfa-mapper"; import { Option, None } from "@siteimprove/alfa-option"; import { Parser } from "@siteimprove/alfa-parser"; import { Predicate } from "@siteimprove/alfa-predicate"; import { Refinement } from "@siteimprove/alfa-refinement"; import { Result, Err, Ok } from "@siteimprove/alfa-result"; import { Slice } from "@siteimprove/alfa-slice"; import * as json from "@siteimprove/alfa-json"; import { Resolver } from "./resolver"; const { either, delimited, end, left, right, map, mapResult, option, pair, oneOrMore, zeroOrMore, takeUntil, separated, separatedList, } = Parser; const { property, equals } = Predicate; /** * @public */ export namespace Media { /** * {@link https://drafts.csswg.org/mediaqueries/#media-query-modifier} */ export enum Modifier { Only = "only", Not = "not", } const parseModifier = either( map(Token.parseIdent("only"), () => Modifier.Only), map(Token.parseIdent("not"), () => Modifier.Not) ); interface Matchable { readonly matches: Predicate<Device>; } /** * {@link https://drafts.csswg.org/mediaqueries/#media-type} */ export class Type implements Matchable, Equatable, Serializable<Type.JSON> { public static of(name: string): Type { return new Type(name); } private readonly _name: string; private constructor(name: string) { this._name = name; } public get name(): string { return this._name; } public matches(device: Device): boolean { switch (this._name) { case "screen": return device.type === Device.Type.Screen; case "print": return device.type === Device.Type.Print; case "speech": return device.type === Device.Type.Speech; case "all": return true; default: return false; } } public equals(value: unknown): value is this { return value instanceof Type && value._name === this._name; } public toJSON(): Type.JSON { return { name: this._name, }; } public toString(): string { return this._name; } } export namespace Type { export interface JSON { [key: string]: json.JSON; name: string; } export function isType(value: unknown): value is Type { return value instanceof Type; } } export const { of: type, isType } = Type; /** * {@link https://drafts.csswg.org/mediaqueries/#typedef-media-type} */ const parseType = map( Token.parseIdent((ident) => { switch (ident.value) { // These values are not allowed as media types. case "only": case "not": case "and": case "or": return false; default: return true; } }), (ident) => Type.of(ident.value) ); /** * {@link https://drafts.csswg.org/mediaqueries/#media-feature} */ export abstract class Feature<T = unknown> implements Matchable, Iterable<Feature<T>>, Equatable, Serializable<Feature.JSON> { protected readonly _value: Option<Value<T>>; protected constructor(value: Option<Value<T>>) { this._value = value; } public abstract get name(): string; public get value(): Option<Value<T>> { return this._value; } public abstract matches(device: Device): boolean; public equals(value: unknown): value is this { return ( value instanceof Feature && value.name === this.name && value._value.equals(this._value) ); } public *iterator(): Iterator<Feature<T>> { yield this; } public [Symbol.iterator](): Iterator<Feature<T>> { return this.iterator(); } public toJSON(): Feature.JSON { return { type: "feature", name: this.name, value: this._value.map((value) => value.toJSON()).getOr(null), }; } public toString(): string { return `${this.name}${this._value .map((value) => `: ${value}`) .getOr("")}`; } } export namespace Feature { export interface JSON { [key: string]: json.JSON; type: "feature"; name: string; value: Value.JSON | null; } export function tryFrom( value: Option<Value<any>>, name: string ): Result<Feature, string> { switch (name) { case "width": return Width.tryFrom(value); case "height": return Height.tryFrom(value); case "orientation": return Orientation.tryFrom(value); case "scripting": return Scripting.tryFrom(value); } return Err.of(`Unknown media feature ${name}`); } /** * {@link https://drafts.csswg.org/mediaqueries/#width} */ class Width extends Feature<Length> { public static of(value: Value<Length>): Width { return new Width(Option.of(value)); } private static _boolean = new Width(None); public static boolean(): Width { return Width._boolean; } public get name(): "width" { return "width"; } public matches(device: Device): boolean { const { viewport: { width }, } = device; const value = this._value.map((value) => value.map((length) => Resolver.length(length, device)) ); return width > 0 ? value.some((value) => value.matches(Length.of(width, "px"))) : value.every((value) => value.matches(Length.of(0, "px"))); } } namespace Width { export function tryFrom(value: Option<Value>): Result<Width, string> { return value .map((value) => { if (value.hasValue(Length.isLength)) { return Ok.of(Width.of(value)); } else { return Err.of(`Invalid value`); } }) .getOrElse(() => Ok.of(Width.boolean())); } } /** * {@link https://drafts.csswg.org/mediaqueries/#height} */ class Height extends Feature<Length> { public static of(value: Value<Length>): Height { return new Height(Option.of(value)); } private static _boolean = new Height(None); public static boolean(): Height { return Height._boolean; } public get name(): "height" { return "height"; } public matches(device: Device): boolean { const { viewport: { height }, } = device; const value = this._value.map((value) => value.map((length) => Resolver.length(length, device)) ); return height > 0 ? value.some((value) => value.matches(Length.of(height, "px"))) : value.every((value) => value.matches(Length.of(0, "px"))); } } namespace Height { export function tryFrom( value: Option<Value<any>> ): Result<Height, string> { return value .map((value) => { if (value.hasValue(Length.isLength)) { return Ok.of(Height.of(value)); } else { return Err.of(`Invalid value`); } }) .getOrElse(() => Ok.of(Height.boolean())); } } /** * {@link https://drafts.csswg.org/mediaqueries/#orientation} */ class Orientation extends Feature<Keyword> { public static of(value: Value<Keyword>): Orientation { return new Orientation(Option.of(value)); } private static _boolean = new Orientation(None); public static boolean(): Orientation { return Orientation._boolean; } public get name(): "orientation" { return "orientation"; } public matches(device: Device): boolean { return this._value.every((value) => value.matches(Keyword.of(device.viewport.orientation)) ); } } namespace Orientation { export function tryFrom( value: Option<Value<any>> ): Result<Orientation, string> { return value .map((value) => { if ( Value.isDiscrete(value) && value.hasValue( Refinement.and( Keyword.isKeyword, property("value", equals("landscape", "portrait")) ) ) ) { return Ok.of(Orientation.of(value)); } else { return Err.of(`Invalid value`); } }) .getOrElse(() => Ok.of(Orientation.boolean())); } } /** * {@link https://drafts.csswg.org/mediaqueries-5/#scripting} */ class Scripting extends Feature<Keyword> { public static of(value: Value<Keyword>): Scripting { return new Scripting(Option.of(value)); } private static _boolean = new Scripting(None); public static boolean(): Scripting { return Scripting._boolean; } public get name(): "scripting" { return "scripting"; } public matches(device: Device): boolean { return device.scripting.enabled ? this._value.every((value) => value.matches(Keyword.of("enabled"))) : this._value.some((value) => value.matches(Keyword.of("none"))); } } namespace Scripting { export function tryFrom( value: Option<Value<any>> ): Result<Scripting, string> { return value .map((value) => { if ( Value.isDiscrete(value) && value.hasValue( Refinement.and( Keyword.isKeyword, property("value", equals("none", "enabled", "initial-only")) ) ) ) { return Ok.of(Scripting.of(value)); } else { return Err.of(`Invalid value`); } }) .getOrElse(() => Ok.of(Scripting.boolean())); } } export function isFeature(value: unknown): value is Feature { return value instanceof Feature; } } export const { isFeature } = Feature; export enum Comparison { LessThan = "<", LessThanOrEqual = "<=", Equal = "=", GreaterThan = ">", GreaterThanOrEqual = ">=", } /** * {@link https://drafts.csswg.org/mediaqueries/#typedef-mf-name} */ const parseFeatureName = map(Token.parseIdent(), (ident) => ident.value.toLowerCase() ); /** * {@link https://drafts.csswg.org/mediaqueries/#typedef-mf-value} */ const parseFeatureValue = either( either( map(Token.parseNumber(), (number) => Number.of(number.value)), map(Token.parseIdent(), (ident) => Keyword.of(ident.value.toLowerCase())) ), either( map( separated( Token.parseNumber((number) => number.isInteger), delimited(option(Token.parseWhitespace), Token.parseDelim("/")), Token.parseNumber((number) => number.isInteger) ), ([left, right]) => Percentage.of(left.value / right.value) ), Length.parse ) ); /** * {@link https://drafts.csswg.org/mediaqueries/#typedef-mf-plain} */ const parseFeaturePlain = mapResult( separated( parseFeatureName, delimited(option(Token.parseWhitespace), Token.parseColon), parseFeatureValue ), ([name, value]) => { if (name.startsWith("min-") || name.startsWith("max-")) { const range = name.startsWith("min-") ? Value.minimumRange : Value.maximumRange; name = name.slice(4); return Feature.tryFrom( Option.of(range(Value.bound(value, /* isInclusive */ true))), name ); } else { return Feature.tryFrom(Option.of(Value.discrete(value)), name); } } ); /** * {@link https://drafts.csswg.org/mediaqueries/#typedef-mf-boolean} */ const parseFeatureBoolean = mapResult(parseFeatureName, (name) => Feature.tryFrom(None, name) ); /** * {@link https://drafts.csswg.org/mediaqueries/#typedef-mf-lt} */ const parseFeatureLessThan = map( right(Token.parseDelim("<"), option(Token.parseDelim("="))), (equal) => equal.isNone() ? Comparison.LessThan : Comparison.LessThanOrEqual ); /** * {@link https://drafts.csswg.org/mediaqueries/#typedef-mf-gt} */ const parseFeatureGreaterThan = map( right(Token.parseDelim(">"), option(Token.parseDelim("="))), (equal) => equal.isNone() ? Comparison.GreaterThan : Comparison.GreaterThanOrEqual ); /** * {@link https://drafts.csswg.org/mediaqueries/#typedef-mf-eq} */ const parseFeatureEqual = map(Token.parseDelim("="), () => Comparison.Equal); /** * {@link https://drafts.csswg.org/mediaqueries/#typedef-mf-comparison} */ const parseFeatureComparison = either( parseFeatureEqual, parseFeatureLessThan, parseFeatureGreaterThan ); /** * {@link https://drafts.csswg.org/mediaqueries/#typedef-mf-range} */ const parseFeatureRange = either( // <mf-value> <mf-lt> <mf-name> <mf-lt> <mf-value> mapResult( pair( map( pair( parseFeatureValue, delimited(option(Token.parseWhitespace), parseFeatureLessThan) ), ([value, comparison]) => Value.bound( value, /* isInclusive */ comparison === Comparison.LessThanOrEqual ) ), pair( delimited(option(Token.parseWhitespace), parseFeatureName), map( pair( delimited(option(Token.parseWhitespace), parseFeatureLessThan), parseFeatureValue ), ([comparison, value]) => Value.bound( value, /* isInclusive */ comparison === Comparison.LessThanOrEqual ) ) ) ), ([minimum, [name, maximum]]) => Feature.tryFrom(Option.of(Value.range(minimum, maximum)), name) ), // <mf-value> <mf-gt> <mf-name> <mf-gt> <mf-value> mapResult( pair( map( pair( parseFeatureValue, delimited(option(Token.parseWhitespace), parseFeatureGreaterThan) ), ([value, comparison]) => Value.bound( value, /* isInclusive */ comparison === Comparison.GreaterThanOrEqual ) ), pair( delimited(option(Token.parseWhitespace), parseFeatureName), map( pair( delimited(option(Token.parseWhitespace), parseFeatureGreaterThan), parseFeatureValue ), ([comparison, value]) => Value.bound( value, /* isInclusive */ comparison === Comparison.GreaterThanOrEqual ) ) ) ), ([maximum, [name, minimum]]) => Feature.tryFrom(Option.of(Value.range(minimum, maximum)), name) ), // <mf-name> <mf-comparison> <mf-value> mapResult( pair( parseFeatureName, pair( delimited(option(Token.parseWhitespace), parseFeatureComparison), parseFeatureValue ) ), ([name, [comparison, value]]) => { switch (comparison) { case Comparison.Equal: return Feature.tryFrom( Option.of( Value.range( Value.bound(value, /* isInclude */ true), Value.bound(value, /* isInclude */ true) ) ), name ); case Comparison.LessThan: case Comparison.LessThanOrEqual: return Feature.tryFrom( Option.of( Value.maximumRange( Value.bound( value, /* isInclusive */ comparison === Comparison.LessThanOrEqual ) ) ), name ); case Comparison.GreaterThan: case Comparison.GreaterThanOrEqual: return Feature.tryFrom( Option.of( Value.minimumRange( Value.bound( value, /* isInclusive */ comparison === Comparison.GreaterThanOrEqual ) ) ), name ); } } ), // <mf-value> <mf-comparison> <mf-name> mapResult( pair( parseFeatureValue, pair( delimited(option(Token.parseWhitespace), parseFeatureComparison), parseFeatureName ) ), ([value, [comparison, name]]) => { switch (comparison) { case Comparison.Equal: return Feature.tryFrom( Option.of( Value.range( Value.bound(value, /* isInclude */ true), Value.bound(value, /* isInclude */ true) ) ), name ); case Comparison.LessThan: case Comparison.LessThanOrEqual: return Feature.tryFrom( Option.of( Value.minimumRange( Value.bound( value, /* isInclusive */ comparison === Comparison.LessThanOrEqual ) ) ), name ); case Comparison.GreaterThan: case Comparison.GreaterThanOrEqual: return Feature.tryFrom( Option.of( Value.maximumRange( Value.bound( value, /* isInclusive */ comparison === Comparison.GreaterThanOrEqual ) ) ), name ); } } ) ); /** * {@link https://drafts.csswg.org/mediaqueries/#typedef-media-feature} */ const parseFeature = delimited( Token.parseOpenParenthesis, delimited( option(Token.parseWhitespace), either(parseFeatureRange, parseFeaturePlain, parseFeatureBoolean) ), Token.parseCloseParenthesis ); export interface Value<T = unknown> extends Functor<T>, Serializable<Value.JSON> { map<U>(mapper: Mapper<T, U>): Value<U>; matches(value: T): boolean; hasValue<U extends T>(refinement: Refinement<T, U>): this is Value<U>; toJSON(): Value.JSON; } export namespace Value { export interface JSON { [key: string]: json.JSON; type: string; } export class Discrete<T = unknown> implements Value<T>, Serializable<Discrete.JSON<T>> { public static of<T>(value: T): Discrete<T> { return new Discrete(value); } private readonly _value: T; private constructor(value: T) { this._value = value; } public get value(): T { return this._value; } public map<U>(mapper: Mapper<T, U>): Discrete<U> { return new Discrete(mapper(this._value)); } public matches(value: T): boolean { return Equatable.equals(this._value, value); } public hasValue<U extends T>( refinement: Refinement<T, U> ): this is Discrete<U> { return refinement(this._value); } public toJSON(): Discrete.JSON<T> { return { type: "discrete", value: Serializable.toJSON(this._value), }; } } export namespace Discrete { export interface JSON<T> { [key: string]: json.JSON; type: "discrete"; value: Serializable.ToJSON<T>; } export function isDiscrete<T>(value: unknown): value is Discrete<T> { return value instanceof Discrete; } } export const { of: discrete, isDiscrete } = Discrete; export class Range<T = unknown> implements Value<T>, Serializable<Range.JSON<T>> { public static of<T>(minimum: Bound<T>, maximum: Bound<T>): Range<T> { return new Range(Option.of(minimum), Option.of(maximum)); } public static minimum<T>(minimum: Bound<T>): Range<T> { return new Range(Option.of(minimum), None); } public static maximum<T>(maximum: Bound<T>): Range<T> { return new Range(None, Option.of(maximum)); } private readonly _minimum: Option<Bound<T>>; private readonly _maximum: Option<Bound<T>>; private constructor( minimum: Option<Bound<T>>, maximum: Option<Bound<T>> ) { this._minimum = minimum; this._maximum = maximum; } public get minimum(): Option<Bound<T>> { return this._minimum; } public get maximum(): Option<Bound<T>> { return this._maximum; } public map<U>(mapper: Mapper<T, U>): Range<U> { return new Range( this._minimum.map((bound) => bound.map(mapper)), this._maximum.map((bound) => bound.map(mapper)) ); } public matches(value: T): boolean { if (!Comparable.isComparable<T>(value)) { return false; } for (const minimum of this._minimum) { if (minimum.isInclusive) { if (value.compare(minimum.value) <= 0) { return false; } } else { if (value.compare(minimum.value) < 0) { return false; } } } for (const maximum of this._maximum) { if (maximum.isInclusive) { if (value.compare(maximum.value) >= 0) { return false; } } else { if (value.compare(maximum.value) > 0) { return false; } } } return true; } public hasValue<U extends T>( refinement: Refinement<T, U> ): this is Discrete<U> { return ( this._minimum.every((bound) => refinement(bound.value)) && this._maximum.every((bound) => refinement(bound.value)) ); } public toJSON(): Range.JSON<T> { return { type: "range", minimum: this._minimum.map((bound) => bound.toJSON()).getOr(null), maximum: this._maximum.map((bound) => bound.toJSON()).getOr(null), }; } } export namespace Range { export interface JSON<T> { [key: string]: json.JSON; type: "range"; minimum: Bound.JSON<T> | null; maximum: Bound.JSON<T> | null; } export function isRange<T>(value: unknown): value is Range<T> { return value instanceof Range; } } export const { of: range, minimum: minimumRange, maximum: maximumRange, isRange, } = Range; export class Bound<T = unknown> implements Functor<T>, Serializable<Bound.JSON<T>> { public static of<T>(value: T, isInclusive: boolean): Bound<T> { return new Bound(value, isInclusive); } private readonly _value: T; private readonly _isInclusive: boolean; private constructor(value: T, isInclusive: boolean) { this._value = value; this._isInclusive = isInclusive; } public get value(): T { return this._value; } public get isInclusive(): boolean { return this._isInclusive; } public map<U>(mapper: Mapper<T, U>): Bound<U> { return new Bound(mapper(this._value), this._isInclusive); } public toJSON(): Bound.JSON<T> { return { value: Serializable.toJSON(this._value), isInclusive: this._isInclusive, }; } } export namespace Bound { export interface JSON<T> { [key: string]: json.JSON; value: Serializable.ToJSON<T>; isInclusive: boolean; } } export const { of: bound } = Bound; } export class And implements Matchable, Iterable<Feature>, Equatable, Serializable<And.JSON> { public static of( left: Feature | Condition, right: Feature | Condition ): And { return new And(left, right); } private readonly _left: Feature | Condition; private readonly _right: Feature | Condition; private constructor(left: Feature | Condition, right: Feature | Condition) { this._left = left; this._right = right; } public get left(): Feature | Condition { return this._left; } public get right(): Feature | Condition { return this._right; } public matches(device: Device): boolean { return this._left.matches(device) && this._right.matches(device); } public equals(value: unknown): value is this { return ( value instanceof And && value._left.equals(this._left) && value._right.equals(this._right) ); } public *iterator(): Iterator<Feature> { for (const condition of [this._left, this._right]) { yield* condition; } } public [Symbol.iterator](): Iterator<Feature> { return this.iterator(); } public toJSON(): And.JSON { return { type: "and", left: this._left.toJSON(), right: this._right.toJSON(), }; } public toString(): string { return `(${this._left}) and (${this._right})`; } } export namespace And { export interface JSON { [key: string]: json.JSON; type: "and"; left: Feature.JSON | Condition.JSON; right: Feature.JSON | Condition.JSON; } export function isAnd(value: unknown): value is And { return value instanceof And; } } export const { of: and, isAnd } = And; export class Or implements Matchable, Iterable<Feature>, Equatable, Serializable<Or.JSON> { public static of( left: Feature | Condition, right: Feature | Condition ): Or { return new Or(left, right); } private readonly _left: Feature | Condition; private readonly _right: Feature | Condition; private constructor(left: Feature | Condition, right: Feature | Condition) { this._left = left; this._right = right; } public get left(): Feature | Condition { return this._left; } public get right(): Feature | Condition { return this._right; } public matches(device: Device): boolean { return this._left.matches(device) || this._right.matches(device); } public equals(value: unknown): value is this { return ( value instanceof Or && value._left.equals(this._left) && value._right.equals(this._right) ); } public *iterator(): Iterator<Feature> { for (const condition of [this._left, this._right]) { yield* condition; } } public [Symbol.iterator](): Iterator<Feature> { return this.iterator(); } public toJSON(): Or.JSON { return { type: "or", left: this._left.toJSON(), right: this._right.toJSON(), }; } public toString(): string { return `(${this._left}) or (${this._right})`; } } export namespace Or { export interface JSON { [key: string]: json.JSON; type: "or"; left: Feature.JSON | Condition.JSON; right: Feature.JSON | Condition.JSON; } export function isOr(value: unknown): value is Or { return value instanceof Or; } } export const { of: or, isOr } = Or; export class Not implements Matchable, Iterable<Feature>, Equatable, Serializable<Not.JSON> { public static of(condition: Feature | Condition): Not { return new Not(condition); } private readonly _condition: Feature | Condition; private constructor(condition: Feature | Condition) { this._condition = condition; } public get condition(): Feature | Condition { return this._condition; } public matches(device: Device): boolean { return !this._condition.matches(device); } public equals(value: unknown): value is this { return value instanceof Not && value._condition.equals(this._condition); } public *iterator(): Iterator<Feature> { yield* this._condition; } public [Symbol.iterator](): Iterator<Feature> { return this.iterator(); } public toJSON(): Not.JSON { return { type: "not", condition: this._condition.toJSON(), }; } public toString(): string { return `not (${this._condition})`; } } export namespace Not { export interface JSON { [key: string]: json.JSON; type: "not"; condition: Condition.JSON | Feature.JSON; } export function isNot(value: unknown): value is Not { return value instanceof Not; } } export const { of: not, isNot } = Not; /** * {@link https://drafts.csswg.org/mediaqueries/#media-condition} */ export type Condition = And | Or | Not; export namespace Condition { export type JSON = And.JSON | Or.JSON | Not.JSON; export function isCondition(value: unknown): value is Condition { return isAnd(value) || isOr(value) || isNot(value); } } export const { isCondition } = Condition; /** * @remarks * The condition parser is forward-declared as it is needed within its * subparsers. */ let parseCondition: Parser<Slice<Token>, Feature | Condition, string>; /** * {@link https://drafts.csswg.org/mediaqueries/#typedef-media-in-parens} */ const parseInParens = either( delimited( Token.parseOpenParenthesis, delimited(option(Token.parseWhitespace), (input) => parseCondition(input) ), Token.parseCloseParenthesis ), parseFeature ); /** * {@link https://drafts.csswg.org/mediaqueries/#typedef-media-not} */ const parseNot = map( right( delimited(option(Token.parseWhitespace), Token.parseIdent("not")), parseInParens ), not ); /** * {@link https://drafts.csswg.org/mediaqueries/#typedef-media-and} */ const parseAnd = right( delimited(option(Token.parseWhitespace), Token.parseIdent("and")), parseInParens ); /** * {@link https://drafts.csswg.org/mediaqueries/#typedef-media-or} */ const parseOr = right( delimited(option(Token.parseWhitespace), Token.parseIdent("or")), parseInParens ); /** * {@link https://drafts.csswg.org/mediaqueries/#typedef-media-condition} */ parseCondition = either( parseNot, either( map( pair( parseInParens, either( map(oneOrMore(parseAnd), (queries) => [and, queries] as const), map(oneOrMore(parseOr), (queries) => [or, queries] as const) ) ), ([left, [constructor, right]]) => Iterable.reduce( right, (left, right) => constructor(left, right), left ) ), parseInParens ) ); /** * {@link https://drafts.csswg.org/mediaqueries/#typedef-media-condition-without-or} */ const parseConditionWithoutOr = either( parseNot, map(pair(parseInParens, zeroOrMore(parseAnd)), ([left, right]) => [left, ...right].reduce((left, right) => and(left, right)) ) ); /** * {@link https://drafts.csswg.org/mediaqueries/#media-query} */ export class Query implements Matchable { public static of( modifier: Option<Modifier>, type: Option<Type>, condition: Option<Feature | Condition> ): Query { return new Query(modifier, type, condition); } private readonly _modifier: Option<Modifier>; private readonly _type: Option<Type>; private readonly _condition: Option<Feature | Condition>; private constructor( modifier: Option<Modifier>, type: Option<Type>, condition: Option<Feature | Condition> ) { this._modifier = modifier; this._type = type; this._condition = condition; } public get modifier(): Option<Modifier> { return this._modifier; } public get type(): Option<Type> { return this._type; } public get condition(): Option<Feature | Condition> { return this._condition; } public matches(device: Device): boolean { const negated = this._modifier.some( (modifier) => modifier === Modifier.Not ); const type = this._type.every((type) => type.matches(device)); const condition = this.condition.every((condition) => condition.matches(device) ); return negated !== (type && condition); } public equals(value: unknown): value is this { return ( value instanceof Query && value._modifier.equals(this._modifier) && value._type.equals(this._type) && value._condition.equals(this._condition) ); } public toJSON(): Query.JSON { return { modifier: this._modifier.getOr(null), type: this._type.map((type) => type.toJSON()).getOr(null), condition: this._condition .map((condition) => condition.toJSON()) .getOr(null), }; } public toString(): string { const modifier = this._modifier.getOr(""); const type = this._type .map((type) => (modifier === "" ? `${type}` : `${modifier} ${type}`)) .getOr(""); return this._condition .map((condition) => type === "" ? `${condition}` : `${type} and ${condition}` ) .getOr(type); } } export namespace Query { export interface JSON { [key: string]: json.JSON; modifier: string | null; type: Type.JSON | null; condition: Feature.JSON | Condition.JSON | Not.JSON | null; } export function isQuery(value: unknown): value is Query { return value instanceof Query; } } export const { of: query, isQuery } = Query; /** * {@link https://drafts.csswg.org/mediaqueries/#typedef-media-query} */ const parseQuery = left( either( map(parseCondition, (condition) => Query.of(None, None, Option.of(condition)) ), map( pair( pair( option(delimited(option(Token.parseWhitespace), parseModifier)), parseType ), option( right( delimited(option(Token.parseWhitespace), Token.parseIdent("and")), parseConditionWithoutOr ) ) ), ([[modifier, type], condition]) => Query.of(modifier, Option.of(type), condition) ) ), end(() => `Unexpected token`) ); /** * {@link https://drafts.csswg.org/mediaqueries/#media-query-list} */ export class List implements Matchable, Iterable<Query>, Equatable, Serializable<List.JSON> { public static of(queries: Iterable<Query>): List { return new List(queries); } private readonly _queries: Array<Query>; private constructor(queries: Iterable<Query>) { this._queries = Array.from(queries); } public get queries(): Iterable<Query> { return this._queries; } public matches(device: Device): boolean { return ( this._queries.length === 0 || this._queries.some((query) => query.matches(device)) ); } public equals(value: unknown): value is this { return ( value instanceof List && value._queries.length === this._queries.length && value._queries.every((query, i) => query.equals(this._queries[i])) ); } public *[Symbol.iterator](): Iterator<Query> { yield* this._queries; } public toJSON(): List.JSON { return this._queries.map((query) => query.toJSON()); } public toString(): string { return this._queries.join(", "); } } export namespace List { export type JSON = Array<Query.JSON>; export function isList(value: unknown): value is List { return value instanceof List; } } export const { of: list, isList } = List; const notAll = Query.of( Option.of(Modifier.Not), Option.of(Type.of("all")), None ); /** * {@link https://drafts.csswg.org/mediaqueries/#typedef-media-query-list} */ const parseList = map( separatedList( map( takeUntil( Component.consume, either( Token.parseComma, end(() => `Unexpected token`) ) ), (components) => Iterable.flatten(components) ), Token.parseComma ), (queries) => List.of( Iterable.map(queries, (tokens) => parseQuery(Slice.from(tokens).trim(Token.isWhitespace)) .map(([, query]) => query) .getOr(notAll) ) ) ); export const parse = parseList; }
the_stack
import { MatrixClient } from "matrix-js-sdk/src/client"; import { MatrixEvent } from "matrix-js-sdk/src/models/event"; import { Room } from "matrix-js-sdk/src/models/room"; import { EventType } from "matrix-js-sdk/src/@types/event"; import { logger } from "matrix-js-sdk/src/logger"; import { Playback, PlaybackState } from "./Playback"; import { UPDATE_EVENT } from "../stores/AsyncStore"; import { MatrixClientPeg } from "../MatrixClientPeg"; import { arrayFastClone } from "../utils/arrays"; import { PlaybackManager } from "./PlaybackManager"; import { isVoiceMessage } from "../utils/EventUtils"; import RoomViewStore from "../stores/RoomViewStore"; /** * Audio playback queue management for a given room. This keeps track of where the user * was at for each playback, what order the playbacks were played in, and triggers subsequent * playbacks. * * Currently this is only intended to be used by voice messages. * * The primary mechanics are: * * Persisted clock state for each playback instance (tied to Event ID). * * Limited memory of playback order (see code; not persisted). * * Autoplay of next eligible playback instance. */ export class PlaybackQueue { private static queues = new Map<string, PlaybackQueue>(); // keyed by room ID private playbacks = new Map<string, Playback>(); // keyed by event ID private clockStates = new Map<string, number>(); // keyed by event ID private playbackIdOrder: string[] = []; // event IDs, last == current private currentPlaybackId: string; // event ID, broken out from above for ease of use private recentFullPlays = new Set<string>(); // event IDs constructor(private client: MatrixClient, private room: Room) { this.loadClocks(); RoomViewStore.addListener(() => { if (RoomViewStore.getRoomId() === this.room.roomId) { // Reset the state of the playbacks before they start mounting and enqueuing updates. // We reset the entirety of the queue, including order, to ensure the user isn't left // confused with what order the messages are playing in. this.currentPlaybackId = null; // this in particular stops autoplay when the room is switched to this.recentFullPlays = new Set<string>(); this.playbackIdOrder = []; } }); } public static forRoom(roomId: string): PlaybackQueue { const cli = MatrixClientPeg.get(); const room = cli.getRoom(roomId); if (!room) throw new Error("Unknown room"); if (PlaybackQueue.queues.has(room.roomId)) { return PlaybackQueue.queues.get(room.roomId); } const queue = new PlaybackQueue(cli, room); PlaybackQueue.queues.set(room.roomId, queue); return queue; } private persistClocks() { localStorage.setItem( `mx_voice_message_clocks_${this.room.roomId}`, JSON.stringify(Array.from(this.clockStates.entries())), ); } private loadClocks() { const val = localStorage.getItem(`mx_voice_message_clocks_${this.room.roomId}`); if (!!val) { this.clockStates = new Map<string, number>(JSON.parse(val)); } } public unsortedEnqueue(mxEvent: MatrixEvent, playback: Playback) { // We don't ever detach our listeners: we expect the Playback to clean up for us this.playbacks.set(mxEvent.getId(), playback); playback.on(UPDATE_EVENT, (state) => this.onPlaybackStateChange(playback, mxEvent, state)); playback.clockInfo.liveData.onUpdate((clock) => this.onPlaybackClock(playback, mxEvent, clock)); } private onPlaybackStateChange(playback: Playback, mxEvent: MatrixEvent, newState: PlaybackState) { // Remember where the user got to in playback const wasLastPlaying = this.currentPlaybackId === mxEvent.getId(); if (newState === PlaybackState.Stopped && this.clockStates.has(mxEvent.getId()) && !wasLastPlaying) { // noinspection JSIgnoredPromiseFromCall playback.skipTo(this.clockStates.get(mxEvent.getId())); } else if (newState === PlaybackState.Stopped) { // Remove the now-useless clock for some space savings this.clockStates.delete(mxEvent.getId()); if (wasLastPlaying) { this.recentFullPlays.add(this.currentPlaybackId); const orderClone = arrayFastClone(this.playbackIdOrder); const last = orderClone.pop(); if (last === this.currentPlaybackId) { const next = orderClone.pop(); if (next) { const instance = this.playbacks.get(next); if (!instance) { logger.warn( "Voice message queue desync: Missing playback for next message: " + `Current=${this.currentPlaybackId} Last=${last} Next=${next}`, ); } else { this.playbackIdOrder = orderClone; PlaybackManager.instance.pauseAllExcept(instance); // This should cause a Play event, which will re-populate our playback order // and update our current playback ID. // noinspection JSIgnoredPromiseFromCall instance.play(); } } else { // else no explicit next event, so find an event we haven't played that comes next. The live // timeline is already most recent last, so we can iterate down that. const timeline = arrayFastClone(this.room.getLiveTimeline().getEvents()); let scanForVoiceMessage = false; let nextEv: MatrixEvent; for (const event of timeline) { if (event.getId() === mxEvent.getId()) { scanForVoiceMessage = true; continue; } if (!scanForVoiceMessage) continue; if (!isVoiceMessage(event)) { const evType = event.getType(); if (evType !== EventType.RoomMessage && evType !== EventType.Sticker) { continue; // Event can be skipped for automatic playback consideration } break; // Stop automatic playback: next useful event is not a voice message } const havePlayback = this.playbacks.has(event.getId()); const isRecentlyCompleted = this.recentFullPlays.has(event.getId()); if (havePlayback && !isRecentlyCompleted) { nextEv = event; break; } } if (!nextEv) { // if we don't have anywhere to go, reset the recent playback queue so the user // can start a new chain of playbacks. this.recentFullPlays = new Set<string>(); this.playbackIdOrder = []; } else { this.playbackIdOrder = orderClone; const instance = this.playbacks.get(nextEv.getId()); PlaybackManager.instance.pauseAllExcept(instance); // This should cause a Play event, which will re-populate our playback order // and update our current playback ID. // noinspection JSIgnoredPromiseFromCall instance.play(); } } } else { logger.warn( "Voice message queue desync: Expected playback stop to be last in order. " + `Current=${this.currentPlaybackId} Last=${last} EventID=${mxEvent.getId()}`, ); } } } if (newState === PlaybackState.Playing) { const order = this.playbackIdOrder; if (this.currentPlaybackId !== mxEvent.getId() && !!this.currentPlaybackId) { if (order.length === 0 || order[order.length - 1] !== this.currentPlaybackId) { const lastInstance = this.playbacks.get(this.currentPlaybackId); if ( lastInstance.currentState === PlaybackState.Playing || lastInstance.currentState === PlaybackState.Paused ) { order.push(this.currentPlaybackId); } } } this.currentPlaybackId = mxEvent.getId(); if (order.length === 0 || order[order.length - 1] !== this.currentPlaybackId) { order.push(this.currentPlaybackId); } } // Only persist clock information on pause/stop (end) to avoid overwhelming the storage. // This should get triggered from normal voice message component unmount due to the playback // stopping itself for cleanup. if (newState === PlaybackState.Paused || newState === PlaybackState.Stopped) { this.persistClocks(); } } private onPlaybackClock(playback: Playback, mxEvent: MatrixEvent, clocks: number[]) { if (playback.currentState === PlaybackState.Decoding) return; // ignore pre-ready values if (playback.currentState !== PlaybackState.Stopped) { this.clockStates.set(mxEvent.getId(), clocks[0]); // [0] is the current seek position } } }
the_stack
import { Component, OnInit, Input, ViewChild, AfterViewInit, ChangeDetectorRef } from '@angular/core'; import * as moment from 'moment'; import { UtilsService } from '../../core/services/utils.service'; import { ActivatedRoute } from '@angular/router'; import { RequestService, MessageService } from '../../core/services'; import { Observable } from 'rxjs/Observable'; import { environment } from '../../../environments/environment.oss' import { environment as env_oss } from './../../../environments/environment.oss'; import * as _ from 'lodash'; import { Subscription } from 'rxjs'; import { RenameFieldService } from '../../core/services/rename-field.service'; declare let Promise; @Component({ selector: 'service-metrics', templateUrl: './service-metrics.component.html', styleUrls: ['./service-metrics.component.scss'] }) export class ServiceMetricsComponent implements OnInit, AfterViewInit { @Input() service; @Input() assetTypeList; @ViewChild('filters') filters; public assetWithDefaultValue: any = []; payload: any = {}; public allData: any; public serviceType; assetsNameArray: any = []; metricsLoaded: boolean = false; selectedEnv: any; public assetFilter; lambdaResourceNameArr:any; public assetIdentifierFilter; public environmentFilter; public assetList: any = []; selectedAssetName: any; assetSelected; startTime: any; endTime: any; public formFields: any = [ { column: 'View By:', label: 'TIME RANGE', type: 'select', options: [ 'Last 15 Minutes', 'Last 1 Hour', 'Last 24 Hours', 'Last 7 Days', 'Last 30 Days', 'Last 3 Months', 'Last 12 Months' ], values: [ { range: moment().subtract(15, 'minute').toISOString(), format: 'hA', unit: 'minute' }, { range: moment().subtract(1, 'hour').toISOString(), format: 'hA', unit: 'hour' }, { range: moment().subtract(1, 'day').toISOString(), format: 'hA', unit: 'day' }, { range: moment().subtract(1, 'week').toISOString(), format: 'MMM Do', unit: 'week' }, { range: moment().subtract(1, 'month').toISOString(), format: 'M/D', unit: 'month' }, { range: moment().subtract(3, 'month').toISOString(), format: 'M/D', unit: 'month' }, { range: moment().subtract(1, 'year').toISOString(), format: 'MMM YYYY', unit: 'year' }], selected: 'Last 24 Hours' }, { column: 'View By:', label: 'PERIOD', type: 'select', options: ['1 Minute', '30 Minutes', '1 Hour', '3 Hours', '15 Hours', '4 Days'], values: [ moment(0).add(1, 'minutes').valueOf() / 1000, moment(0).add(30, 'minutes').valueOf() / 1000, moment(0).add(1, 'hour').valueOf() / 1000, moment(0).add(3, 'hour').valueOf() / 1000, moment(0).add(15, 'hour').valueOf() / 1000, moment(0).add(4, 'days').valueOf() / 1000, ], selected: '1 Hour' }, { column: 'View By:', label: 'AGGREGATION', type: 'select', options: ['Average', 'Sum'], values: ['Average', 'Sum'], selected: 'Average' } ]; public form; public selectedAsset; public selectedMetric; public selectedMetricDisplayName; public ylegend; public aggregation; public queryDataRaw; public sectionStatus = "empty"; public errorData = {}; public graphData; private http; public platform; slsapp: boolean = false; public assetType = []; errMessage: any; private toastmessage: any = ''; private slsLambdaselected; public provider: any; private metricSubscription: Subscription; private assetSubscription: Subscription; assetNameFilterWhiteList = [ 'lambda', 'cloudfront', 's3', 'dynamodb', 'sqs', 'kinesis', 'iam_role' ]; constructor(private request: RequestService, private utils: UtilsService, private cdr: ChangeDetectorRef, private messageservice: MessageService, private activatedRoute: ActivatedRoute, private renameFieldService: RenameFieldService) { this.http = this.request; this.toastmessage = messageservice; } ngAfterViewInit() { this.sectionStatus = 'loading'; if (!this.activatedRoute.snapshot.params['env']) { return (this.getEnvironments() && this.getAssetType()) .then(() => { return this.applyFilter(); }) .catch(err => { this.sectionStatus = 'error'; this.errorData['response'] = err; this.errMessage = this.toastmessage.errorMessage(err, "metricsResponse"); }); } else { // TODO: Condition prevents hydration of environments filter in some cases return this.getAssetType() .then(() => { return (this.applyFilter()); }) } } ngOnInit() { if(this.service.provider == 'azure'){ this.setFilters(); } this.serviceType = this.service.type || this.service.serviceType; if(this.service.assets){ this.selectedEnv = this.service.assets[0].environment; } this.setPeriodFilters(); } setPeriodFilters() { if (this.service.deployment_targets === 'gcp_apigee') { const periodFilterIndex = this.formFields.findIndex(formField => formField.label === 'PERIOD'); this.formFields[periodFilterIndex].options = ['1 Minutes', '3 Hours', '1 Day']; this.formFields[periodFilterIndex].values = [ moment(0).add(1, 'minute').valueOf() / 1000, moment(0).add(3, 'hour').valueOf() / 1000, moment(0).add(1, 'day').valueOf() / 1000, ]; this.formFields[periodFilterIndex].selected = '1 Minutes'; } if (this.service.platform || (this.service.assets && this.service.assets.length>0)){ this.platform = this.service.platform || this.service.assets[0].provider; } if (this.platform == 'azure'){ const azPeriodFilterIndex = this.formFields.findIndex(formField => formField.label === 'PERIOD'); this.formFields[azPeriodFilterIndex].options = ['1 Minutes', '1 Hour', '1 Day']; this.formFields[azPeriodFilterIndex].values = [ moment(0).add(1, 'minute').valueOf() / 1000, moment(0).add(1, 'hour').valueOf() / 1000, moment(0).add(1, 'day').valueOf() / 1000, ]; this.formFields[azPeriodFilterIndex].selected = '1 Hour'; const azPAggFilterIndex = this.formFields.findIndex(formField => formField.label === 'AGGREGATION'); this.formFields[azPAggFilterIndex].options = ['Total']; this.formFields[azPAggFilterIndex].values = ['total']; this.formFields[azPAggFilterIndex].selected = 'Total'; } } setFilters(){ // we are targeting the second object in the FormFields where values for AGGREGATION is there this.formFields[2].options = ['Average', 'Total', 'Maximum'] this.formFields[2].value = ['Average', 'Total', 'Maximum'] this.formFields[2].values = ['Average', 'Total', 'Maximum'] } refresh() { this.ngAfterViewInit(); } fetchAssetName(type, name) { let assetName; let tokens; switch(type) { case 'lambda': case 'sqs': case 'iam_role': tokens = name.split(':'); assetName = tokens[tokens.length - 1]; break; case 'dynamodb': case 'cloudfront': case 'kinesis': tokens = name.split('/'); assetName = tokens[tokens.length - 1]; break; case 's3': tokens = name.split(':::'); assetName = tokens[tokens.length - 1].split('/')[0]; break; } return assetName; } setAssetName(val,selected){ let assetIdentifierFilter = {}; this.slsapp = true; let assetObj = []; let assetNameObject = []; val[0].data.assets.map((item)=>{ assetObj.push({type: item.asset_type, name: item.provider_id ,env: item.environment}); }) assetObj.map((item)=>{ if(item.type === selected && item.env === this.selectedEnv){ this.selectedAssetName = this.fetchAssetName(item.type, item.name); if (this.selectedAssetName) { assetNameObject.push(this.selectedAssetName); } assetNameObject.sort(); } }) if(assetNameObject.length !== 0) { assetIdentifierFilter = { column: 'Filter By:', label: 'ASSET NAME', options:assetNameObject, values: assetNameObject, selected: assetNameObject[0] }; } else { let value = 'all'.split('0') assetIdentifierFilter = { column: 'Filter By:', label: 'ASSET NAME', options: value, values: value, selected: value }; } this.applyFilter(assetIdentifierFilter); } getAssetType(data?) { try{ if(this.assetSubscription) { this.assetSubscription.unsubscribe(); } let self = this; return self.http.get('/jazz/assets', { domain: self.service.domain, service: self.service.name, status: "active", limit: 1e3, // TODO: Address design shortcomings offset: 0, }, self.service.id).toPromise().then((response: any) => { if (response && response.data && response.data.assets) { self.provider = response.data.assets[0].provider; let assets = _(response.data.assets).map('asset_type').uniq().value(); // TODO: Consider hoisting to member or configuration const filterWhitelist = [ 'lambda', 'apigateway', 'cloudfront', 's3', 'dynamodb', 'sqs', 'kinesis_stream', 'apigee_proxy', 'storage_account' ]; assets = assets.filter(item => filterWhitelist.includes(item)); if(assets){ this.assetsNameArray = []; self.assetWithDefaultValue = assets; this.assetsNameArray.push(response); let validAssetList = assets.filter(asset => (env_oss.assetTypeList.indexOf(asset) > -1)); this.lambdaResourceNameArr = response.data.assets.map( asset => asset.provider_id ); this.lambdaResourceNameArr = _.uniq(this.lambdaResourceNameArr); self.assetWithDefaultValue = validAssetList; if(validAssetList.length){ for (var i = 0; i < self.assetWithDefaultValue.length; i++) { self.assetList[i] = self.assetWithDefaultValue[i].replace(/_/g, " "); } self.assetFilter = { column: 'Filter By:', label: 'ASSET TYPE', options: this.assetList, values: validAssetList, selected: validAssetList[0].replace(/_/g, " ") }; if (!data) { self.assetSelected = validAssetList[0].replace(/_/g, " "); } this.payload.asset_type = this.assetSelected.replace(/ /g, "_"); self.assetSelected = validAssetList[0].replace(/ /g, "_"); let assetField = self.filters.getFieldValueOfLabel('ASSET TYPE'); if (!assetField) { self.formFields.splice(1, 0, self.assetFilter); self.filters.setFields(self.formFields); } if (this.assetNameFilterWhiteList.indexOf(this.assetSelected) > -1) { self.setAssetName(self.assetsNameArray, self.assetSelected); } } } } }) .catch((error) => { return Promise.reject(error); }) } catch(ex){ console.log('ex:',ex); } } getEnvironments() { return this.http.get('/jazz/environments', { domain: this.service.domain, service: this.service.name }, this.service.id).toPromise() .then((response: any) => { if (response && response.data && response.data.environment && response.data.environment.length) { let serviceEnvironments = _(response.data.environment).map('logical_id').uniq().value(); this.environmentFilter = { column: 'Filter By:', label: 'ENVIRONMENT', type: 'select', options: serviceEnvironments, values: serviceEnvironments, selected: 'prod' }; this.selectedEnv = this.environmentFilter.selected; let environmentField = this.filters.getFieldValueOfLabel('ENVIRONMENT'); if (!environmentField) { this.formFields.splice(0, 0, this.environmentFilter); } } }) .catch((error) => { return Promise.reject(error); }) } findIndexOfObjectWithKey(array, key, value) { for (let i = 0; i < array.length; i++) { if (array[i][key] == value) { return i; } } } applyFilter(changedFilter?) { if (changedFilter) { if (this.platform != 'azure'){ let index = this.findIndexOfObjectWithKey(this.formFields, 'label', 'PERIOD'); if (this.service.deployment_targets === 'gcp_apigee') { switch (changedFilter.selected) { case 'Last 15 Minutes':{ this.formFields[index].options = ['1 Minute', '3 Hours', '1 Day']; this.formFields[index].values = [ moment(0).add(1, 'minute').valueOf() / 1000, moment(0).add(1, 'hour').valueOf() / 1000, moment(0).add(1, 'day').valueOf() / 1000,]; this.filters.changeFilter('1 Minute',this.formFields[index]); break; } case 'Last 1 Hour':{ this.formFields[index].options = ['1 Minute', '3 Hours', '1 Day']; this.formFields[index].values = [ moment(0).add(1, 'minute').valueOf() / 1000, moment(0).add(1, 'hour').valueOf() / 1000, moment(0).add(1, 'day').valueOf() / 1000,]; this.filters.changeFilter('1 Minute',this.formFields[index]); break; } case 'Last 24 Hours':{ this.formFields[index].options = ['1 Minutes', '3 Hours', '1 Day']; this.formFields[index].values = [ moment(0).add(1, 'minute').valueOf() / 1000, moment(0).add(1, 'hour').valueOf() / 1000, moment(0).add(1, 'day').valueOf() / 1000,]; this.filters.changeFilter('1 Minutes',this.formFields[index]); break; } case 'Last 7 Days':{ this.formFields[index].options = ['3 Hours', '1 Day', '7 Days']; this.formFields[index].values = [ moment(0).add(3, 'hours').valueOf() / 1000, moment(0).add(1, 'day').valueOf() / 1000, moment(0).add(7, 'day').valueOf() / 1000,]; this.filters.changeFilter('3 Hours',this.formFields[index]); break; } case 'Last 30 Days':{ this.formFields[index].options = ['1 Day', '7 Days', '30 Days']; this.formFields[index].values = [ moment(0).add(1, 'day').valueOf() / 1000, moment(0).add(7, 'day').valueOf() / 1000, moment(0).add(30, 'day').valueOf() / 1000]; this.filters.changeFilter('1 Day',this.formFields[index]); break; } case 'Last 3 Months':{ this.formFields[index].options = ['1 Day', '7 Days', '30 Days']; this.formFields[index].values = [ moment(0).add(1, 'day').valueOf() / 1000, moment(0).add(7, 'day').valueOf() / 1000, moment(0).add(30, 'day').valueOf() / 1000]; this.filters.changeFilter('7 Days',this.formFields[index]); break; } case 'Last 12 Months':{ this.formFields[index].options = ['1 Day', '7 Days', '30 Days']; this.formFields[index].values = [ moment(0).add(1, 'day').valueOf() / 1000, moment(0).add(7, 'day').valueOf() / 1000, moment(0).add(30, 'day').valueOf() / 1000]; this.filters.changeFilter('7 Days',this.formFields[index]); break; } } } else { switch (changedFilter.selected) { case 'Last 15 Minutes':{ this.formFields[index].options = ['1 Minute', '3 Hours', '1 Day']; this.formFields[index].values = [ moment(0).add(1, 'minute').valueOf() / 1000, moment(0).add(1, 'hour').valueOf() / 1000, moment(0).add(1, 'day').valueOf() / 1000,]; this.filters.changeFilter('1 Minute',this.formFields[index]); break; } case 'Last 1 Hour':{ this.formFields[index].options = ['1 Minute', '3 Hours', '1 Day']; this.formFields[index].values = [ moment(0).add(1, 'minute').valueOf() / 1000, moment(0).add(1, 'hour').valueOf() / 1000, moment(0).add(1, 'day').valueOf() / 1000,]; this.filters.changeFilter('1 Minute',this.formFields[index]); break; } case 'Last 24 Hours':{ this.formFields[index].options = ['1 Minutes', '3 Hours', '6 Hour', '1 Day']; this.formFields[index].values = [ moment(0).add(1, 'minute').valueOf() / 1000, moment(0).add(1, 'hour').valueOf() / 1000, moment(0).add(6, 'hour').valueOf() / 1000, moment(0).add(1, 'day').valueOf() / 1000,]; this.filters.changeFilter('1 Minutes',this.formFields[index]); break; } case 'Last 7 Days':{ this.formFields[index].options = ['3 Hours', '1 Day', '6 Hour', '7 Days']; this.formFields[index].values = [ moment(0).add(1, 'hour').valueOf() / 1000, moment(0).add(6, 'hour').valueOf() / 1000, moment(0).add(1, 'day').valueOf() / 1000, moment(0).add(7, 'day').valueOf() / 1000,]; this.filters.changeFilter('3 Hours',this.formFields[index]); break; } case 'Last 30 Days':{ this.formFields[index].options = ['1 Day', '7 Days', '30 Days']; this.formFields[index].values = [ moment(0).add(1, 'day').valueOf() / 1000, moment(0).add(7, 'day').valueOf() / 1000, moment(0).add(30, 'day').valueOf() / 1000]; this.filters.changeFilter('1 Day',this.formFields[index]); break; } case 'Last 3 Months':{ this.formFields[index].options = ['1 Day', '7 Days', '30 Days']; this.formFields[index].values = [ moment(0).add(1, 'day').valueOf() / 1000, moment(0).add(7, 'day').valueOf() / 1000, moment(0).add(30, 'day').valueOf() / 1000]; this.filters.changeFilter('7 Days',this.formFields[index]); break; } case 'Last 12 Months':{ this.formFields[index].options = ['1 Day', '7 Days', '30 Days']; this.formFields[index].values = [ moment(0).add(1, 'day').valueOf() / 1000, moment(0).add(7, 'day').valueOf() / 1000, moment(0).add(30, 'day').valueOf() / 1000]; this.filters.changeFilter('7 Days',this.formFields[index]); break; } } } } if (changedFilter.label === 'ASSET TYPE') { this.assetSelected = changedFilter.selected.replace(/ /g, "_"); if (this.assetNameFilterWhiteList.indexOf(this.assetSelected) > -1) { this.setAssetName(this.assetsNameArray,this.assetSelected); } else { let index = this.findIndexOfObjectWithKey(this.formFields, 'label', 'ASSET NAME'); if (index > -1) { this.formFields.splice(index, 1); this.filters.setFields(this.formFields); } } } if (changedFilter.label === 'ASSET NAME') { let lambda = changedFilter.selected; this.slsLambdaselected = changedFilter.selected; this.formFields.map((item,index)=>{ if(item.label === "ASSET NAME"){ this.formFields.splice(index,1); } }) this.formFields.splice(2, 0, changedFilter); this.filters.setFields(this.formFields); } if (changedFilter.label === 'ENVIRONMENT') { this.selectedEnv = changedFilter.selected; if (this.assetNameFilterWhiteList.indexOf(this.assetSelected) > -1) { this.setAssetName(this.assetsNameArray,this.assetSelected); } } } if (changedFilter && (changedFilter.label === 'ASSET' || changedFilter.label === 'METHOD' || changedFilter.label === 'PATH' || changedFilter.label === 'ASSET NAME')) { this.setAsset(); } else if(changedFilter && changedFilter.label !== 'TIME RANGE' || changedFilter === undefined) { return this.queryMetricsData(); } } setStartTime(val) { this.formFields.map((item) => { if (item.label === "TIME RANGE") { if (item.selected === "Last 24 Hours") { this.startTime = moment(val).subtract(1, 'day'); } else if (item.selected === "Last 15 Minutes") { this.startTime = moment(val).subtract(15, 'minute'); } else if (item.selected === "Last 1 Hour") { this.startTime = moment(val).subtract(1, 'hour'); } else if (item.selected === "Last 7 Days") { this.startTime = moment(val).subtract(7, 'days'); } else if (item.selected === "Last 12 Months") { this.startTime = moment(val).subtract(1, 'year'); } else if (item.selected === "Last 3 Months") { this.startTime = moment(val).subtract(3, 'month'); } else if (item.selected === "Last 30 Days") { this.startTime = moment(val).subtract(1, 'month'); } } }) } setEndTime() { this.endTime = moment(); this.setStartTime(this.endTime) } queryMetricsData() { if (this.metricSubscription) { this.metricSubscription.unsubscribe(); } this.setEndTime() this.sectionStatus = 'loading'; // TODO: Leverage TypeScript interfaces for data contracts at minimum let request = { url: '/jazz/metrics', body: { domain: this.service.domain, service: this.service.name, environment: this.filters.getFieldValueOfLabel('ENVIRONMENT') || this.activatedRoute.snapshot.params['env'] || 'prod', start_time: this.startTime, end_time: this.endTime, interval: this.filters.getFieldValueOfLabel('PERIOD'), statistics: this.filters.getFieldValueOfLabel('AGGREGATION') } }; if(this.assetSelected !== 'all') { request.body['asset_type'] = this.assetSelected; } return this.http.post(request.url, request.body, this.service.id) .toPromise() .then((response) => { this.sectionStatus = 'empty'; this.metricsLoaded = true; if (response && response.data && response.data.length) { this.queryDataRaw = response.data; this.getAllData(response.data); } }) .catch((error) => { this.sectionStatus = 'error'; this.metricsLoaded = true; // comment following 2 lines if there are any issues? this.errorData['response'] = error; this.errMessage = this.toastmessage.errorMessage(error, "metricsResponse"); }) } getAllData(data) { this.allData = data; this.queryDataRaw.assets = this.filterAssetType(this.allData[0]); if (this.queryDataRaw.assets.length !== 0) { this.setAssetsFilter(); this.setAsset(); } else { if(this.metricsLoaded = true) { this.sectionStatus = 'empty'; } } } filterAssetType(data) { return data.assets.filter((asset) => { return asset.type === this.assetSelected; }) } setAssetsFilter() { if (this.serviceType === 'api') { if(this.assetSelected === 'apigateway' || this.assetSelected === 'apigee_proxy') { let methods = _(this.queryDataRaw.assets) .map('asset_name.Method') .uniq().value(); let paths = _(this.queryDataRaw.assets) .map('asset_name.Resource') .uniq().value(); this.filters.removeField('Filter By:', 'ASSET NAME'); const filterIndex = _.findIndex(this.filters.form.columns, {'label': "Filter By:"}); if ( filterIndex > -1) { if(_.findIndex(this.filters.form.columns[filterIndex].fields, {'label': 'PATH'}) === -1) { this.filters.addField('Filter By:', 'PATH', paths); } if(_.findIndex(this.filters.form.columns[filterIndex].fields, {'label': 'METHOD'}) === -1) { this.filters.addField('Filter By:', 'METHOD', methods, null); } } } else if (this.assetSelected === 'lambda') { let functionName = _(this.queryDataRaw.assets) .map('asset_name.FunctionName') .uniq().value(); const filterIndex = _.findIndex(this.filters.form.columns, {'label': "Filter By:"}); if ( filterIndex > -1) { if(_.findIndex(this.filters.form.columns[filterIndex].fields, {'label': 'ASSET NAME'}) === -1) { this.filters.addField('Filter By:', 'ASSET NAME', functionName, null); } } } } } setAsset() { if(this.queryDataRaw){ this.selectedAsset = this.queryDataRaw.assets[0]; } if (this.selectedAsset) { this.sortAssetData(this.selectedAsset); this.setMetric(); this.sectionStatus = 'resolved'; } else { if(this.metricsLoaded === true) { this.sectionStatus = 'empty'; } } } setMetric(metric?) { if (metric) { this.selectedMetric = metric; } else if (this.selectedMetric) { let found = this.selectedAsset.metrics.find((metric) => { return metric.metric_name === this.selectedMetric.metric_name }); this.selectedMetric = found || this.selectedAsset.metrics[0] } else { this.selectedMetric = this.selectedAsset.metrics[0] } this.selectedMetricDisplayName = this.renameFieldService.getDisplayNameOfKey(this.selectedMetric.metric_name.toLowerCase()) || this.selectedMetric.metric_name; this.graphData = this.selectedMetric && this.formatGraphData(this.selectedMetric.datapoints); } formatGraphData(metricData) { let valueProperty = this.selectedAsset.statistics; let values = metricData .sort((pointA, pointB) => { return moment(pointA.Timestamp).diff(moment(pointB.Timestamp)); }) .map((dataPoint) => { let obj = { x: moment(dataPoint.Timestamp).valueOf(), y: parseInt(dataPoint[valueProperty]) }; return obj; }); let timeRange = this.filters.getFieldValueOfLabel('TIME RANGE'); this.aggregation = this.filters.getFieldValueOfLabel('AGGREGATION') === 'Sum' ? 'Sum': 'Avg.'; this.ylegend = this.selectedMetricDisplayName + ' (' + this.aggregation + ')'; let options = { tooltipXFormat: 'MMM DD YYYY, h:mm a', fromDateISO: timeRange.range, fromDateValue: moment(timeRange.range).valueOf(), toDateISO: moment().toISOString(), toDateValue: moment().valueOf(), xAxisFormat: timeRange.format, xAxisUnit: timeRange.unit, stepSize: this.filters.getFieldValueOfLabel('PERIOD') * 1000, yMin: values.length ? .9 * (values.map((point) => { return point.y; }) .reduce((a, b) => { return Math.min(a, b); })) : 0, yMax: values.length ? 1.1 * (values.map((point) => { return point.y; }) .reduce((a, b) => { return Math.max(a, b); })) : 100 }; return { datasets: [values], options: options } } sortAssetData(asset) { asset.metrics.forEach((metric) => { let datapoints = metric.datapoints .sort((pointA, pointB) => { return moment(pointA.Timestamp).diff(moment(pointB.Timestamp)); }); metric.datapoints = datapoints; }) } ngOnDestroy() { if (this.metricSubscription) { this.metricSubscription.unsubscribe(); } if(this.assetSubscription) { this.assetSubscription.unsubscribe(); } } }
the_stack
import { Component, NgZone, ChangeDetectorRef, ViewChild, ElementRef } from '@angular/core'; import { App, IonicPage, NavController, NavParams, LoadingController, ActionSheetController, MenuController, ToastController, AlertController, PopoverController, ModalController, Events } from 'ionic-angular'; import { PostsRes } from 'models/models'; import { postSinglePage } from './post-single.template'; import { AuthorProfilePage } from '../../pages/author-profile/author-profile'; import { SteemiaProvider } from 'providers/steemia/steemia'; import { SteeemActionsProvider } from 'providers/steeem-actions/steeem-actions'; import { SteemConnectProvider } from 'providers/steemconnect/steemconnect'; import { Subject } from 'rxjs/Subject'; import { AlertsProvider } from 'providers/alerts/alerts'; import { ERRORS } from '../../constants/constants'; import { UtilProvider } from 'providers/util/util'; import { Storage } from '@ionic/storage'; import { CameraProvider } from 'providers/camera/camera'; import { DomSanitizer } from '@angular/platform-browser'; import { TranslateService } from '@ngx-translate/core'; import { SharedServiceProvider } from 'providers/shared-service/shared-service'; import { Subscription } from 'rxjs/Subscription'; import { ImageViewerController } from 'ionic-img-viewer'; import { TextToSpeech } from '@ionic-native/text-to-speech'; @IonicPage({ priority: 'high' }) @Component({ selector: 'page-post-single', template: postSinglePage }) export class PostSinglePage { @ViewChild('myInput') myInput: ElementRef; private post: any; private is_voting: boolean = false; private is_bookmarked: boolean = false; private is_loading: boolean = true; private is_logged_in: boolean = false; private profile: any; private current_user: string = ""; private user; private chatBox: string = ''; private is_owner: boolean = false; private ref; private bookmarks; private caret: number = 0; private parsed_body: any = ''; private commentsTree: Array<any> = []; private subs: Array<Subscription> = []; private _imageViewerCtrl: ImageViewerController; private captured_images: any = []; private is_listening: boolean = false; constructor(private app: App, private zone: NgZone, private cdr: ChangeDetectorRef, public navCtrl: NavController, public navParams: NavParams, private events: Events, private imageViewerCtrl: ImageViewerController, private translate: TranslateService, private dom: DomSanitizer, private tts: TextToSpeech, public menu: MenuController, private camera: CameraProvider, private actionSheetCtrl: ActionSheetController, private service: SharedServiceProvider, public storage: Storage, private steemia: SteemiaProvider, private alerts: AlertsProvider, private popoverCtrl: PopoverController, private alertCtrl: AlertController, private toastCtrl: ToastController, public util: UtilProvider, private modalCtrl: ModalController, public loadingCtrl: LoadingController, private steemActions: SteeemActionsProvider, private steemConnect: SteemConnectProvider) { this.user = (this.steemConnect.user_temp as any); this._imageViewerCtrl = imageViewerCtrl; } ionViewDidLoad(): void { this.post = this.navParams.get('post'); this.parsed_body = this.getPostBody(); this.current_user = (this.steemConnect.user_temp as any).user; if (this.current_user === this.post.author) { this.is_owner = true; } this.zone.runOutsideAngular(() => { this.load_comments(); }); this.subs.push(this.service.reply_status.subscribe(status => { if (status === true) { this.zone.runOutsideAngular(() => { this.load_comments('refresh'); }); } })); this.storage.ready().then(() => { this.storage.get('bookmarks').then(data => { if (data) { this.containsObject(data); } }); }); } ionViewDidEnter(): void { // Grab all the images from the post and add a click event listener this.captured_images = document.getElementById("card-content").getElementsByTagName("img"); for (let i = 0; i < this.captured_images.length; i++) { // Listen for the click event and open the image when fired this.captured_images[i].addEventListener("click", () => { this.presentImage(this.captured_images[i]); }); } this.menu.enable(false); } ionViewWillLeave(): void { // Unsubscribe data from server this.subs.forEach(sub => { sub.unsubscribe(); }); // Re-enable drawer menu this.menu.enable(true); // Remove click listener for the images when component is about to be destroyed for (let i = 0; i < this.captured_images.length; i++) { this.captured_images[i].removeEventListener("click", () => { }); } // Stop any dictation this.tts.speak(''); } /** * Method to present image in a modal * @param {HTMLImageElement} image: Image object to re-draw * @private */ private presentImage(image: HTMLImageElement): void { const imageViewer = this._imageViewerCtrl.create(image); imageViewer.present(); } /** * Method to return a sanitized post body * @returns a string with the body of the post */ private getPostBody() { return this.dom.bypassSecurityTrustHtml(this.post.full_body); } /** * Method to load comments as tree * @param action */ private load_comments(action?: string) { this.steemia.get_comments_tree(this.post.author, encodeURIComponent(this.post.url), this.current_user).then((data: any) => { // Check if the action is to refresh. If so, we need to // reinitialize all the data after initializing the query // to avoid the data to dissapear if (action === "refresh") { this.reinitialize(); } this.commentsTree = data.results; // Set the loading spinner to false this.is_loading = false; // Tell Angular that changes were made since we detach the auto check this.cdr.detectChanges(); }); } /** * Method to initialize comments back to an empty array */ private reinitialize() { this.commentsTree = []; } /** * Method to get caret position in a textfield * @param oField */ private getCaretPos(oField): void { let node = oField._elementRef.nativeElement.children[0]; if (node.selectionStart || node.selectionStart == '0') { this.caret = node.selectionStart; } } /** * Method to open author profile page * @param {String} author: author of the post */ private openProfile(author: string): void { if (this.steemConnect.user_object !== undefined) { if ((this.steemConnect.user_object as any).user == author) { this.app.getRootNav().push('ProfilePage', { author: (this.steemConnect.user_object as any).user }); } else { this.app.getRootNav().push('AuthorProfilePage', { author: author }); } } else { this.app.getRootNav().push('AuthorProfilePage', { author: author }); } } /** * Method to open the voting-slider popover */ private presentPopover(myEvent) { let popover = this.popoverCtrl.create('VotingSliderPage'); popover.present({ ev: myEvent }); popover.onDidDismiss(data => { if (data) { this.castVote(this.post.author, this.post.url, data.weight); } }); } /** * Method to cast a vote or unvote * @param i * @param author * @param permlink * @param weight */ private castVote(author: string, permlink: string, weight: number = 1000): void { // Set the is voting value of the post to true this.is_voting = true; this.steemActions.dispatch_vote('posts', author, permlink, weight).then((data: any) => { this.is_voting = false; // remove the spinner // Catch if the user is not logged in and display an alert if (data.msg == 'not-logged') return; if (data.msg === 'correct') { if (data.type === 'vote') { this.post.vote = true; } else if (data.type === 'unvote') { this.post.vote = false; } this.refreshPost(); } }); } /** * Method to cast a flag * @param i * @param author * @param permlink * @param weight */ private castFlag(author: string, permlink: string, weight: number = -10000): void { let loading = this.loadingCtrl.create({ content: this.translate.instant('pages.post_single.flag_loading') }); loading.present(); this.steemActions.dispatch_vote('posts', author, permlink, weight).then(data => { loading.dismiss(); // Catch if the user is not logged in and display an alert if (data == 'not-logged') { return; } else if (data === 'Correct') { this.toastCtrl.create({ message: this.translate.instant('pages.post_single.flag_correctly') }); } else if (data === 'flag-error') { setTimeout(() => { this.alerts.display_alert('FLAG_ERROR'); }, 200); } }); } /** * Method to refresh the current data of the post */ private refreshPost(): void { this.steemia.dispatch_post_single({ author: this.post.author, permlink: this.post.url }).then(data => { this.post.net_likes = (data as any).net_likes; this.post.net_votes = (data as any).net_votes; this.post.top_likers_avatars = (data as any).top_likers_avatars; this.post.total_payout_reward = (data as any).total_payout_reward; this.post.children = (data as any).children; }); } /** * Method to reblog the post */ private reblog(): void { let loading = this.loadingCtrl.create({ content: this.translate.instant('pages.post_single.reblog_action') }); loading.present(); this.steemActions.dispatch_reblog(this.post.author, this.post.url).then(data => { // Catch if the user is not logged in and display an alert if (data === 'not-logged') { this.show_prompt(loading, 'NOT_LOGGED_IN'); return; } if (data === 'Correct') { this.show_prompt(loading, 'REBLOGGED_CORRECTLY'); } if (data === 'ALREADY_REBLOGGED') { this.show_prompt(loading, 'ALREADY_REBLOGGED'); } }); } /** * Method to display a delayed alert to prevent two alerts * oppening at the same time * @param loader * @param msg */ private show_prompt(loader, msg) { loader.dismiss(); setTimeout(() => { this.alerts.display_alert(msg); }, 500); } /** * Method to socially share the post */ private share() { this.steemActions.dispatch_share(this.post.url).then(res => { }) } /** * Dispatch a comment to the current post */ private comment() { if (this.chatBox.length === 0) { this.alerts.display_alert('EMPTY_TEXT'); return; } let loading = this.loadingCtrl.create({ content: this.translate.instant('generic_messages.please_wait') }); loading.present(); this.steemActions.dispatch_comment(this.post.author, this.post.url, this.chatBox).then(res => { if (res === 'not-logged') { this.show_prompt(loading, 'NOT_LOGGED_IN'); return; } else if (res === 'Correct') { this.chatBox = ''; this.zone.runOutsideAngular(() => { this.load_comments('refresh'); }); loading.dismiss(); } else if (res === 'COMMENT_INTERVAL') { this.show_prompt(loading, 'COMMENT_INTERVAL'); } }); } /** * Method to open page to edit the current post */ private editPost() { this.navCtrl.push("EditPostPage", { post: this.post }); } /** * Method to add a post to the bookmarks */ private addBookmark() { if ((this.steemConnect.user_temp as any).user) { this.storage.get('bookmarks').then(data => { if (data) { this.bookmarks = data; this.bookmarks.push({ author: this.post.author, permlink: this.post.root_permlink, url: this.post.url, title: this.post.title, body: this.post.body }); this.storage.set('bookmarks', this.bookmarks).then(data => { this.is_bookmarked = true; this.displayToast('saved'); }); } else { this.bookmarks = [{ author: this.post.author, permlink: this.post.root_permlink, url: this.post.url, title: this.post.title, body: this.post.body }]; this.storage.set('bookmarks', this.bookmarks).then(data => { this.is_bookmarked = true; this.displayToast('saved'); }); } }); } else { this.alerts.display_alert('NOT_LOGGED_IN'); } } /** * Method to remove post from bookmarks */ private removeBookmark(): void { if ((this.steemConnect.user_temp as any).user) { this.storage.get('bookmarks').then(data => { this.bookmarks = data; for (let object of data) { if (object.author === this.post.author && object.url === this.post.url) { let index = this.bookmarks.indexOf(object); this.bookmarks.splice(index, 1); this.storage.set('bookmarks', this.bookmarks).then(data => { this.is_bookmarked = false; this.displayToast('removed'); }); } } }); } else { this.alerts.display_alert('NOT_LOGGED_IN'); } } /** * Toast helper for bookmark state * @param msg */ private displayToast(msg) { let toast = this.toastCtrl.create({ message: this.translate.instant('bookmark_action', { action: msg }), duration: 1500, position: 'bottom' }); toast.present(); } /** * Method to check if the post is currently bookmarked * @param array */ private containsObject(array) { for (let object of array) { if (object.author === this.post.author && object.url === this.post.url) { this.is_bookmarked = true; } } } /** * Method to adjust textarea based on the user input so input does * not get hidden * @param event */ protected adjustTextarea(event?: any): void { this.myInput['_elementRef'].nativeElement.getElementsByClassName("text-input")[0].style.height = 'auto'; this.myInput['_elementRef'] .nativeElement .getElementsByClassName("text-input")[0] .style .height = this.myInput['_elementRef'] .nativeElement .getElementsByClassName("text-input")[0] .scrollHeight + 'px'; } /** * Method to insert text at current pointer * @param {String} text: Text to insert */ private insertText(text: string): void { const current = this.chatBox; let final = current.substr(0, this.caret) + text + current.substr(this.caret); this.chatBox = final; this.adjustTextarea(); } /** * Method to present actionsheet with options */ private presentActionSheet(): void { if ((this.steemConnect.user_temp as any).user) { let actionSheet = this.actionSheetCtrl.create({ title: this.translate.instant('general.camera_options.title'), buttons: [ { text: this.translate.instant('general.camera_options.camera'), icon: 'camera', handler: () => { this.camera.choose_image(this.camera.FROM_CAMERA, false, 'comment').then((image: any) => { this.insertText(image); }); } }, { text: this.translate.instant('general.camera_options.gallery'), icon: 'albums', handler: () => { this.camera.choose_image(this.camera.FROM_GALLERY, true, 'comment').then((image: any) => { this.insertText(image); }); } }, { text: this.translate.instant('general.camera_options.custom_url'), icon: 'md-globe', handler: () => { this.presentInsertURL() } }, { text: this.translate.instant('generic_messages.cancel'), icon: 'close', role: 'cancel', handler: () => { } } ] }); actionSheet.present(); } else { this.alerts.display_alert('NOT_LOGGED_IN'); } } /** * Method to show insert URL actionsheet */ private presentInsertURL(): void { let alert = this.alertCtrl.create({ title: this.translate.instant('general.insert_image.title'), inputs: [ { name: 'URL', placeholder: this.translate.instant('general.insert_image.url'), } ], buttons: [ { text: this.translate.instant('general.insert_image.cancel'), role: 'cancel', handler: data => { console.log('Cancel clicked'); } }, { text: 'OK', handler: data => { this.insertText('![image](' + data.URL + ')'); } } ] }); alert.present(); } /** * Method to open the pending payout popover */ private presentPayoutPopover(myEvent): void { let payout = { payout: this.post.total_payout_reward, created: this.post.created, beneficiaries: this.post.beneficiaries } let popover = this.popoverCtrl.create('PendingPayoutPage', payout); popover.present({ ev: myEvent }); } /** * Method to open a modal with the votes of the post * @param post */ private openVotes(url: string, author: string): void { let votesModal = this.modalCtrl.create("VotesPage", { votes: this.post.votes }, { cssClass: "full-modal" }); votesModal.present(); } /** * Method to show reblog alert with a detailed message of this action * @private */ private reblogAlert(): void { let confirm = this.alertCtrl.create({ title: this.translate.instant('reblog.title'), message: this.translate.instant('reblog.message'), buttons: [ { text: this.translate.instant('generic_messages.cancel'), handler: () => { //console.log('Disagree clicked'); } }, { text: this.translate.instant('reblog.reblog_action'), handler: () => { this.reblog(); } } ] }); confirm.present(); } /** * Method to pop to root when a tag is tapped * @param {String} tag: Tag to set in the app * @private */ private assign_tag(tag: string): void { // Publish event to dismiss all modals behind this page. this.events.publish('dismiss-modals'); // Set the next tag to the global service. this.service.current_tag.next(tag); // Closure to capitalize first letter in the string const capitalize = (string) => { return string.charAt(0).toUpperCase() + string.slice(1); } // Display message to confirm that the tag was set correctly. let toast = this.toastCtrl.create({ message: capitalize(tag) + " tag was set correctly!", duration: 1000 }); toast.present(); try { // Remove all the pages in the navigation stack until it is root. this.navCtrl.popToRoot().then(() => { // Success }).catch(() => { // Free to ignore it }); } catch (e) { } } /** * Method to text-to-speech the post * @private */ private listenPost(): void { this.zone.run(() => { this.is_listening = true; let toast = this.toastCtrl.create({ message: "Now you can listen to this post", duration: 1000 }); toast.present(); // Reading Post this.tts.speak({ text: this.post.only_text, rate: 0.90 }).then(() => { // Dictation is done, set is_listening to false this.is_listening = false; }); }); } /** * Method to text-to-speech the post * @private */ private stopListening(): void { this.zone.run(() => { this.is_listening = false; let toast = this.toastCtrl.create({ message: "Dictation stoped", duration: 1000 }); toast.present(); this.tts.speak(''); }); } }
the_stack
import 'reflect-metadata'; import test from 'ava'; import { Container, injectable, BindingScopeEnum } from 'inversify'; import { createCoreModule } from '../src/di/core.module'; import { createDefaultModule } from '../src/di/default.module'; import { Runner } from '../src/runner'; import * as path from 'path'; import { NodeFileSystem } from '../src/services/default/file-system'; import { FileSystem, MessageHandler, DirectoryService, FileSummary, StatePersistence } from '@fimbul/ymir'; import { unixifyPath } from '../src/utils'; import { Linter } from '../src/linter'; import * as yaml from 'js-yaml'; import { DefaultStatePersistence } from '../src/services/default/state-persistence'; import * as ts from 'typescript'; import { CachedFileSystem } from '../src/services/cached-file-system'; const directories: DirectoryService = { getCurrentDirectory() { return path.resolve('packages/wotan'); }, }; test('throws error on non-existing file', (t) => { const container = new Container({defaultScope: BindingScopeEnum.Singleton}); container.bind(DirectoryService).toConstantValue(directories); container.load(createCoreModule({}), createDefaultModule()); const runner = container.get(Runner); t.throws( () => Array.from(runner.lintCollection({ cache: false, config: undefined, files: [ 'test/fixtures/invalid.js', // exists 'non-existent.js', // does not exist, but is excluded 'non-existent/*.ts', // does not match, but has magic 'non-existent.ts', // does not exist ], exclude: ['*.js'], project: [], references: false, fix: false, extensions: undefined, reportUselessDirectives: false, })), { message: `'${unixifyPath(path.resolve('packages/wotan/non-existent.ts'))}' does not exist.` }, ); }); test('throws error on file not included in project', (t) => { const container = new Container({defaultScope: BindingScopeEnum.Singleton}); container.bind(DirectoryService).toConstantValue(directories); container.load(createCoreModule({}), createDefaultModule()); const runner = container.get(Runner); t.throws( () => Array.from(runner.lintCollection({ cache: false, config: undefined, files: [ 'non-existent.js', // does not exist, but is excluded 'non-existent/*.ts', // does not match, but has magic 'non-existent.ts', // does not exist ], exclude: ['*.js'], project: ['test/project/setup'], references: false, fix: false, extensions: undefined, reportUselessDirectives: false, })), { message: `'${unixifyPath(path.resolve('packages/wotan/non-existent.ts'))}' is not included in any of the projects: '${ unixifyPath(path.resolve('packages/wotan/test/project/setup/tsconfig.json')) }'.` }, ); }); test('handles absolute paths with file system specific path separator', (t) => { const container = new Container({defaultScope: BindingScopeEnum.Singleton}); container.bind(DirectoryService).toConstantValue(directories); container.load(createCoreModule({}), createDefaultModule()); const runner = container.get(Runner); const result = Array.from(runner.lintCollection({ cache: false, config: undefined, files: [ path.resolve('packages/wotan/test/project/setup/test.ts'), ], exclude: [], project: ['test/project/setup'], references: false, fix: false, extensions: undefined, reportUselessDirectives: false, })); t.is(result.length, 1); t.is(result[0][0], unixifyPath(path.resolve('packages/wotan/test/project/setup/test.ts'))); }); test('throws if no tsconfig.json can be found', (t) => { const container = new Container({defaultScope: BindingScopeEnum.Singleton}); @injectable() class MockFileSystem extends NodeFileSystem { constructor(logger: MessageHandler) { super(logger); } public stat(file: string) { const stat = super.stat(file); return { isFile() { return false; }, isDirectory() { return stat.isDirectory(); }, }; } } container.bind(FileSystem).to(MockFileSystem); container.load(createCoreModule({}), createDefaultModule()); const runner = container.get(Runner); const {root} = path.parse(process.cwd()); t.throws( () => Array.from(runner.lintCollection({ cache: false, config: undefined, files: [], exclude: [], project: [root], references: false, fix: false, extensions: undefined, reportUselessDirectives: false, })), { message: `Cannot find a tsconfig.json file at the specified directory: '${unixifyPath(root)}'` }, ); const dir = path.join(__dirname, 'non-existent'); t.throws( () => Array.from(runner.lintCollection({ cache: false, config: undefined, files: [], exclude: [], project: [dir], references: false, fix: false, extensions: undefined, reportUselessDirectives: false, })), { message: `The specified path does not exist: '${unixifyPath(dir)}'` }, ); t.throws( () => Array.from(runner.lintCollection({ cache: false, config: undefined, files: [], exclude: [], project: [], references: false, fix: false, extensions: undefined, reportUselessDirectives: false, })), { message: `Cannot find tsconfig.json for directory '${unixifyPath(process.cwd())}'.` }, ); }); test('reports warnings while parsing tsconfig.json', (t) => { const container = new Container({defaultScope: BindingScopeEnum.Singleton}); const files: {[name: string]: string | undefined} = { 'invalid-config.json': '{', 'invalid-base.json': '{"extends": "./invalid-config.json"}', 'invalid-files.json': '{"files": []}', 'no-match.json': '{"include": ["non-existent"], "compilerOptions": {"noLib": true}}', }; @injectable() class MockFileSystem extends NodeFileSystem { constructor(logger: MessageHandler) { super(logger); } public stat(file: string) { if (isLibraryFile(file)) return super.stat(file); return { isFile() { return files[path.basename(file)] !== undefined; }, isDirectory() { return false; }, }; } public readFile(file: string) { if (isLibraryFile(file)) return super.readFile(file); const basename = path.basename(file); const content = files[basename]; if (content !== undefined) return content; throw new Error('ENOENT'); } public readDirectory(): string[] { throw new Error('ENOENT'); } } container.bind(FileSystem).to(MockFileSystem); let warning = ''; container.bind(MessageHandler).toConstantValue({ log() {}, warn(message) { warning = message; }, error() { throw new Error('should not be called'); }, }); container.load(createCoreModule({}), createDefaultModule()); const runner = container.get(Runner); Array.from(runner.lintCollection({ cache: false, config: undefined, files: [], exclude: [], project: ['invalid-config.json'], references: false, fix: false, extensions: undefined, reportUselessDirectives: false, })); t.regex(warning, /invalid-config.json/); warning = ''; Array.from(runner.lintCollection({ cache: false, config: undefined, files: [], exclude: [], project: ['invalid-base.json'], references: false, fix: false, extensions: undefined, reportUselessDirectives: false, })); t.regex(warning, /invalid-config.json/); warning = ''; Array.from(runner.lintCollection({ cache: false, config: undefined, files: [], exclude: [], project: ['invalid-files.json'], references: false, fix: false, extensions: undefined, reportUselessDirectives: false, })); t.is(warning, `invalid-files.json(1,11): error TS18002: The 'files' list in config file '${ unixifyPath(path.resolve('invalid-files.json')) }' is empty.\n`); warning = ''; Array.from(runner.lintCollection({ cache: false, config: undefined, files: [], exclude: [], project: ['no-match.json'], references: false, fix: false, extensions: undefined, reportUselessDirectives: false, })); t.regex(warning, /^error TS18003:/); }); // TODO https://github.com/fimbullinter/wotan/issues/387 https://github.com/Microsoft/TypeScript/issues/26684 test.failing('excludes symlinked typeRoots', (t) => { const container = new Container({defaultScope: BindingScopeEnum.Singleton}); container.bind(DirectoryService).toConstantValue(directories); interface FileMeta { content?: string; symlink?: string; entries?: Record<string, FileMeta | undefined>; } const files: FileMeta = { entries: { 'tsconfig.json': {content: '{"files": ["a.ts"]}'}, 'a.ts': {content: 'foo;'}, node_modules: { entries: { '@types': { entries: { foo: {symlink: 'foo'}, }, }, }, }, foo: { entries: { 'index.d.ts': {content: 'export {};'}, }, }, '.wotanrc.yaml': {content: 'rules: {trailing-newline: error}'}, }, }; @injectable() class MockFileSystem extends NodeFileSystem { constructor(private dirs: DirectoryService, logger: MessageHandler) { super(logger); } public stat(file: string) { if (isLibraryFile(file)) return super.stat(file); const f = this.resolvePath(file); if (f === undefined) throw new Error('ENOENT'); return { isFile() { return f.resolved.content !== undefined; }, isDirectory() { return f.resolved.content === undefined; }, }; } public readFile(file: string) { if (isLibraryFile(file)) return super.readFile(file); const f = this.resolvePath(file); if (f === undefined) throw new Error('ENOENT'); if (f.resolved.content === undefined) throw new Error('EISDIR'); return f.resolved.content; } public readDirectory(dir: string): string[] { const f = this.resolvePath(dir); if (f === undefined) throw new Error('ENOENT'); if (f.resolved.content !== undefined) throw new Error('ENOTDIR'); return Object.keys(f.resolved.entries || {}); } public realpath(file: string): string { if (isLibraryFile(file)) return super.realpath(file); const f = this.resolvePath(file); if (f === undefined) throw new Error('ENOENT'); return path.resolve(this.dirs.getCurrentDirectory(), f.realpath); } private resolvePath(p: string) { const parts = path.relative(this.normalizePath(this.dirs.getCurrentDirectory()), this.normalizePath(p)).split(/\//g); let current: FileMeta | undefined = files; let part = parts.shift(); let realPath = []; while (part !== undefined) { if (part) { realPath.push(part); current = current.entries && current.entries[part]; if (current === undefined) return; if (current.symlink !== undefined) { parts.unshift(...current.symlink.split(/\//g)); realPath = []; current = files; } } part = parts.shift(); } return {resolved: current, realpath: realPath.join('/')}; } } container.bind(FileSystem).to(MockFileSystem); container.load(createCoreModule({}), createDefaultModule()); const runner = container.get(Runner); const result = Array.from(runner.lintCollection({ cache: false, config: undefined, files: [], exclude: [], project: ['tsconfig.json'], references: false, fix: false, extensions: undefined, reportUselessDirectives: false, })); t.is(result.length, 1); t.is(result[0][0], unixifyPath(path.resolve('packages/wotan/a.ts'))); }); function isLibraryFile(name: string) { return /[\\/]typescript[\\/]lib[\\/]lib(\.es\d+(\.\w+)*)?\.d\.ts$/.test(name); } test('works with absolute and relative paths', (t) => { const container = new Container(); container.bind(DirectoryService).toConstantValue(directories); container.load(createCoreModule({}), createDefaultModule()); const runner = container.get(Runner); testRunner(true); testRunner(false); function testRunner(project: boolean) { const result = Array.from(runner.lintCollection({ cache: false, config: undefined, files: [ unixifyPath(path.resolve('packages/wotan/test/fixtures/paths/a.ts')), unixifyPath(path.resolve('packages/wotan/test/fixtures/paths/b.ts')), 'test/fixtures/paths/c.ts', './test/fixtures/paths/d.ts', ], exclude: [ './test/fixtures/paths/b.ts', unixifyPath(path.resolve('packages/wotan/test/fixtures/paths/c.ts')), 'test/fixtures/paths/d.ts', ], project: project ? ['test/fixtures/paths/tsconfig.json'] : [], references: false, fix: false, extensions: undefined, reportUselessDirectives: false, })); t.is(result.length, 1); t.is(result[0][0], unixifyPath(path.resolve('packages/wotan/test/fixtures/paths/a.ts'))); } }); test('normalizes globs', (t) => { const container = new Container(); container.bind(DirectoryService).toConstantValue({ getCurrentDirectory() { return path.resolve('packages/wotan/test/fixtures/configuration'); }, }); container.load(createCoreModule({}), createDefaultModule()); const runner = container.get(Runner); testRunner(true); testRunner(false); function testRunner(project: boolean) { const result = Array.from(runner.lintCollection({ cache: false, config: undefined, files: [ '../paths/a.ts', '../paths/b.ts', ], exclude: [ '../**/b.ts', ], project: project ? ['../paths/tsconfig.json'] : [], references: false, fix: false, extensions: undefined, reportUselessDirectives: false, })); t.is(result.length, 1); t.is(result[0][0], unixifyPath(path.resolve('packages/wotan/test/fixtures/paths/a.ts'))); } }); test('supports linting multiple (overlapping) projects in one run', (t) => { const container = new Container(); container.bind(DirectoryService).toConstantValue(directories); container.load(createCoreModule({}), createDefaultModule()); const runner = container.get(Runner); const result = Array.from( runner.lintCollection({ cache: false, config: undefined, files: [], exclude: [], project: ['test/fixtures/multi-project/src', 'test/fixtures/multi-project/test'], references: false, fix: true, extensions: undefined, reportUselessDirectives: false, }), (entry): [string, FileSummary] => [unixifyPath(path.relative('packages/wotan/test/fixtures/multi-project', entry[0])), entry[1]], ); t.snapshot(result, {id: 'multi-project'}); }); @injectable() class TsVersionAgnosticStatePersistence extends DefaultStatePersistence { constructor(fs: CachedFileSystem) { super(fs); } public loadState(project: string) { const result = super.loadState(project); return result && {...result, ts: ts.version}; } public saveState() {} } test('uses results from cache', (t) => { const container = new Container({defaultScope: BindingScopeEnum.Singleton}); container.bind(DirectoryService).toConstantValue(directories); container.bind(StatePersistence).to(TsVersionAgnosticStatePersistence); container.load(createCoreModule({}), createDefaultModule()); container.get(Linter).getFindings = () => { throw new Error('should not be called'); }; container.get(StatePersistence).saveState = () => { throw new Error('should not be called'); }; const runner = container.get(Runner); const result = Array.from( runner.lintCollection({ cache: true, config: undefined, files: [], exclude: [], project: ['test/fixtures/cache'], references: false, fix: false, extensions: undefined, reportUselessDirectives: true, }), (entry): [string, FileSummary] => [unixifyPath(path.relative('packages/wotan/test/fixtures/cache', entry[0])), entry[1]], ); t.snapshot(result, {id: 'cache'}); }); test('ignore cache if option is not enabled', (t) => { const container = new Container({defaultScope: BindingScopeEnum.Singleton}); container.bind(DirectoryService).toConstantValue(directories); container.bind(StatePersistence).toConstantValue({ loadState () { throw new Error('should not be called'); }, saveState () { throw new Error('should not be called'); }, }); container.load(createCoreModule({}), createDefaultModule()); const runner = container.get(Runner); const result = Array.from( runner.lintCollection({ cache: false, config: undefined, files: [], exclude: [], project: ['test/fixtures/cache'], references: false, fix: false, extensions: undefined, reportUselessDirectives: true, }), (entry): [string, FileSummary] => [unixifyPath(path.relative('packages/wotan/test/fixtures/cache', entry[0])), entry[1]], ); t.snapshot(result, {id: 'cache'}); }); test('discards cache if config changes', (t) => { const container = new Container({defaultScope: BindingScopeEnum.Singleton}); container.bind(DirectoryService).toConstantValue(directories); container.bind(StatePersistence).to(TsVersionAgnosticStatePersistence); container.load(createCoreModule({}), createDefaultModule()); const linter = container.get(Linter); const getFindings = linter.getFindings; const lintedFiles: string[] = []; linter.getFindings = (...args) => { lintedFiles.push(path.basename(args[0].fileName)); return getFindings.apply(linter, args); }; const runner = container.get(Runner); const result = Array.from( runner.lintCollection({ cache: true, config: undefined, files: [], exclude: [], project: ['test/fixtures/cache'], references: false, fix: false, extensions: undefined, reportUselessDirectives: false, }), (entry): [string, FileSummary] => [unixifyPath(path.relative('packages/wotan/test/fixtures/cache', entry[0])), entry[1]], ); t.deepEqual(lintedFiles, ['a.ts', 'b.ts']); t.snapshot(result, {id: 'cache-outdated'}); }); test('cache and fix', (t) => { const container = new Container({defaultScope: BindingScopeEnum.Singleton}); container.bind(DirectoryService).toConstantValue(directories); container.bind(StatePersistence).to(TsVersionAgnosticStatePersistence); container.load(createCoreModule({}), createDefaultModule()); container.get(StatePersistence).saveState = (_, {ts: _ts, cs: _cs, ...rest}) => t.snapshot(yaml.dump(rest, {sortKeys: true}), {id: 'updated-state'}); const linter = container.get(Linter); const getFindings = linter.getFindings; const lintedFiles: string[] = []; linter.getFindings = (...args) => { lintedFiles.push(path.basename(args[0].fileName)); return getFindings.apply(linter, args); }; const runner = container.get(Runner); const result = Array.from( runner.lintCollection({ cache: true, config: undefined, files: [], exclude: [], project: ['test/fixtures/cache'], references: false, fix: true, extensions: undefined, reportUselessDirectives: true, }), (entry): [string, FileSummary] => [unixifyPath(path.relative('packages/wotan/test/fixtures/cache', entry[0])), entry[1]], ); t.deepEqual(lintedFiles, ['b.ts']); t.snapshot(result, {id: 'cache-fix'}); });
the_stack
import { expect, use } from 'chai'; import * as fs from 'fs-extra'; import { convertStat, FileSystem, FileSystemUtils, RawFileSystem } from '../../../client/common/platform/fileSystem'; import { FileSystemPaths, FileSystemPathUtils } from '../../../client/common/platform/fs-paths'; import { FileType } from '../../../client/common/platform/types'; import { createDeferred, sleep } from '../../../client/common/utils/async'; import { noop } from '../../../client/common/utils/misc'; import { assertDoesNotExist, assertFileText, DOES_NOT_EXIST, fixPath, FSFixture, SUPPORTS_SOCKETS, SUPPORTS_SYMLINKS, WINDOWS, } from './utils'; const assertArrays = require('chai-arrays'); use(require('chai-as-promised')); use(assertArrays); suite('FileSystem - raw', () => { let fileSystem: RawFileSystem; let fix: FSFixture; setup(async () => { fileSystem = RawFileSystem.withDefaults(); fix = new FSFixture(); await assertDoesNotExist(DOES_NOT_EXIST); }); teardown(async () => { await fix.cleanUp(); await fix.ensureDeleted(DOES_NOT_EXIST); }); suite('lstat', () => { test('for symlinks, gives the link info', async function () { if (!SUPPORTS_SYMLINKS) { this.skip(); } const filename = await fix.createFile('x/y/z/spam.py', '...'); const symlink = await fix.createSymlink('x/y/z/eggs.py', filename); const rawStat = await fs.lstat(symlink); const expected = convertStat(rawStat, FileType.SymbolicLink); const stat = await fileSystem.lstat(symlink); expect(stat).to.deep.equal(expected); }); test('for normal files, gives the file info', async () => { const filename = await fix.createFile('x/y/z/spam.py', '...'); // Ideally we would compare to the result of // fileSystem.stat(). However, we do not have access // to the VS Code API here. const rawStat = await fs.lstat(filename); const expected = convertStat(rawStat, FileType.File); const stat = await fileSystem.lstat(filename); expect(stat).to.deep.equal(expected); }); test('fails if the file does not exist', async () => { const promise = fileSystem.lstat(DOES_NOT_EXIST); await expect(promise).to.eventually.be.rejected; }); }); suite('chmod (non-Windows)', () => { suiteSetup(function () { // On Windows, chmod won't have any effect on the file itself. if (WINDOWS) { this.skip(); } }); async function checkMode(filename: string, expected: number) { const stat = await fs.stat(filename); expect(stat.mode & 0o777).to.equal(expected); } test('the file mode gets updated (string)', async () => { const filename = await fix.createFile('spam.py', '...'); await fs.chmod(filename, 0o644); await fileSystem.chmod(filename, '755'); await checkMode(filename, 0o755); }); test('the file mode gets updated (number)', async () => { const filename = await fix.createFile('spam.py', '...'); await fs.chmod(filename, 0o644); await fileSystem.chmod(filename, 0o755); await checkMode(filename, 0o755); }); test('the file mode gets updated for a directory', async () => { const dirname = await fix.createDirectory('spam'); await fs.chmod(dirname, 0o755); await fileSystem.chmod(dirname, 0o700); await checkMode(dirname, 0o700); }); test('nothing happens if the file mode already matches', async () => { const filename = await fix.createFile('spam.py', '...'); await fs.chmod(filename, 0o644); await fileSystem.chmod(filename, 0o644); await checkMode(filename, 0o644); }); test('fails if the file does not exist', async () => { const promise = fileSystem.chmod(DOES_NOT_EXIST, 0o755); await expect(promise).to.eventually.be.rejected; }); }); suite('appendText', () => { test('existing file', async () => { const orig = 'spamspamspam\n\n'; const dataToAppend = `Some Data\n${new Date().toString()}\nAnd another line`; const filename = await fix.createFile('spam.txt', orig); const expected = `${orig}${dataToAppend}`; await fileSystem.appendText(filename, dataToAppend); const actual = await fs.readFile(filename, 'utf8'); expect(actual).to.be.equal(expected); }); test('existing empty file', async () => { const filename = await fix.createFile('spam.txt'); const dataToAppend = `Some Data\n${new Date().toString()}\nAnd another line`; const expected = dataToAppend; await fileSystem.appendText(filename, dataToAppend); const actual = await fs.readFile(filename, 'utf8'); expect(actual).to.be.equal(expected); }); test('creates the file if it does not already exist', async () => { await fileSystem.appendText(DOES_NOT_EXIST, 'spam'); const actual = await fs.readFile(DOES_NOT_EXIST, 'utf8'); expect(actual).to.be.equal('spam'); }); test('fails if not a file', async () => { const dirname = await fix.createDirectory('spam'); const promise = fileSystem.appendText(dirname, 'spam'); await expect(promise).to.eventually.be.rejected; }); }); // non-async suite('statSync', () => { test('for normal files, gives the file info', async () => { const filename = await fix.createFile('x/y/z/spam.py', '...'); // Ideally we would compare to the result of // fileSystem.stat(). However, we do not have access // to the VS Code API here. const rawStat = await fs.stat(filename); const expected = convertStat(rawStat, FileType.File); const stat = fileSystem.statSync(filename); expect(stat).to.deep.equal(expected); }); test('for symlinks, gives the linked info', async function () { if (!SUPPORTS_SYMLINKS) { this.skip(); } const filename = await fix.createFile('x/y/z/spam.py', '...'); const symlink = await fix.createSymlink('x/y/z/eggs.py', filename); const rawStat = await fs.stat(filename); const expected = convertStat(rawStat, FileType.SymbolicLink | FileType.File); const stat = fileSystem.statSync(symlink); expect(stat).to.deep.equal(expected); }); test('fails if the file does not exist', async () => { expect(() => { fileSystem.statSync(DOES_NOT_EXIST); }).to.throw(); }); }); suite('readTextSync', () => { test('returns contents of a file', async () => { const expected = '<some text>'; const filename = await fix.createFile('x/y/z/spam.py', expected); const text = fileSystem.readTextSync(filename); expect(text).to.be.equal(expected); }); test('always UTF-8', async () => { const expected = '... 😁 ...'; const filename = await fix.createFile('x/y/z/spam.py', expected); const text = fileSystem.readTextSync(filename); expect(text).to.equal(expected); }); test('throws an exception if file does not exist', () => { expect(() => { fileSystem.readTextSync(DOES_NOT_EXIST); }).to.throw(Error); }); }); suite('createReadStream', () => { setup(function () { // TODO: This appears to be producing // false negative test results, so we're skipping // it for now. // See https://github.com/microsoft/vscode-python/issues/10031. this.skip(); }); test('returns the correct ReadStream', async () => { const filename = await fix.createFile('x/y/z/spam.py', '...'); const expected = fs.createReadStream(filename); expected.destroy(); const stream = fileSystem.createReadStream(filename); stream.destroy(); expect(stream.path).to.deep.equal(expected.path); }); // Missing tests: // * creation fails if the file does not exist // * .read() works as expected // * .pipe() works as expected }); suite('createWriteStream', () => { setup(function () { // TODO This appears to be producing // false negative test results, so we're skipping // it for now. // See https://github.com/microsoft/vscode-python/issues/10031. this.skip(); }); async function writeToStream(filename: string, write: (str: fs.WriteStream) => void) { const closeDeferred = createDeferred(); const stream = fileSystem.createWriteStream(filename); stream.on('close', () => closeDeferred.resolve()); write(stream); stream.end(); stream.close(); stream.destroy(); await closeDeferred.promise; return stream; } test('returns the correct WriteStream', async () => { const filename = await fix.resolve('x/y/z/spam.py'); const expected = fs.createWriteStream(filename); expected.destroy(); const stream = await writeToStream(filename, noop); expect(stream.path).to.deep.equal(expected.path); }); test('creates the file if missing', async () => { const filename = await fix.resolve('x/y/z/spam.py'); await assertDoesNotExist(filename); const data = 'line1\nline2\n'; await writeToStream(filename, (s) => s.write(data)); await assertFileText(filename, data); }); test('always UTF-8', async () => { const filename = await fix.resolve('x/y/z/spam.py'); const data = '... 😁 ...'; await writeToStream(filename, (s) => s.write(data)); await assertFileText(filename, data); }); test('overwrites existing file', async () => { const filename = await fix.createFile('x/y/z/spam.py', '...'); const data = 'line1\nline2\n'; await writeToStream(filename, (s) => s.write(data)); await assertFileText(filename, data); }); }); }); suite('FileSystem - utils', () => { let utils: FileSystemUtils; let fix: FSFixture; setup(async () => { utils = FileSystemUtils.withDefaults(); fix = new FSFixture(); await assertDoesNotExist(DOES_NOT_EXIST); }); teardown(async () => { await fix.cleanUp(); await fix.ensureDeleted(DOES_NOT_EXIST); }); suite('getFileHash', () => { // Since getFileHash() relies on timestamps, we have to take // into account filesystem timestamp resolution. For instance // on FAT and HFS it is 1 second. // See: https://nodejs.org/api/fs.html#fs_stat_time_values test('Getting hash for a file should return non-empty string', async () => { const filename = await fix.createFile('x/y/z/spam.py'); const hash = await utils.getFileHash(filename); expect(hash).to.not.equal(''); }); test('the returned hash is stable', async () => { const filename = await fix.createFile('x/y/z/spam.py'); const hash1 = await utils.getFileHash(filename); const hash2 = await utils.getFileHash(filename); await sleep(2_000); // just in case const hash3 = await utils.getFileHash(filename); expect(hash1).to.equal(hash2); expect(hash1).to.equal(hash3); expect(hash2).to.equal(hash3); }); test('the returned hash changes with modification', async () => { const filename = await fix.createFile('x/y/z/spam.py', 'original text'); const hash1 = await utils.getFileHash(filename); await sleep(2_000); // for filesystems with 1s resolution await fs.writeFile(filename, 'new text'); const hash2 = await utils.getFileHash(filename); expect(hash1).to.not.equal(hash2); }); test('the returned hash is unique', async () => { const file1 = await fix.createFile('spam.py'); await sleep(2_000); // for filesystems with 1s resolution const file2 = await fix.createFile('x/y/z/spam.py'); await sleep(2_000); // for filesystems with 1s resolution const file3 = await fix.createFile('eggs.py'); const hash1 = await utils.getFileHash(file1); const hash2 = await utils.getFileHash(file2); const hash3 = await utils.getFileHash(file3); expect(hash1).to.not.equal(hash2); expect(hash1).to.not.equal(hash3); expect(hash2).to.not.equal(hash3); }); test('Getting hash for non existent file should throw error', async () => { const promise = utils.getFileHash(DOES_NOT_EXIST); await expect(promise).to.eventually.be.rejected; }); }); suite('search', () => { test('found matches', async () => { const pattern = await fix.resolve(`x/y/z/spam.*`); const expected: string[] = [ await fix.createFile('x/y/z/spam.py'), await fix.createFile('x/y/z/spam.pyc'), await fix.createFile('x/y/z/spam.so'), await fix.createDirectory('x/y/z/spam.data'), ]; // non-matches await fix.createFile('x/spam.py'); await fix.createFile('x/y/z/eggs.py'); await fix.createFile('x/y/z/spam-all.py'); await fix.createFile('x/y/z/spam'); await fix.createFile('x/spam.py'); let files = await utils.search(pattern); // For whatever reason, on Windows "search()" is // returning filenames with forward slasshes... files = files.map(fixPath); expect(files.sort()).to.deep.equal(expected.sort()); }); test('no matches', async () => { const pattern = await fix.resolve(`x/y/z/spam.*`); const files = await utils.search(pattern); expect(files).to.deep.equal([]); }); }); suite('fileExistsSync', () => { test('want file, got file', async () => { const filename = await fix.createFile('x/y/z/spam.py'); const exists = utils.fileExistsSync(filename); expect(exists).to.equal(true); }); test('want file, not file', async () => { const filename = await fix.createDirectory('x/y/z/spam.py'); const exists = utils.fileExistsSync(filename); // Note that currently the "file" can be *anything*. It // doesn't have to be just a regular file. This is the // way it already worked, so we're keeping it that way // for now. expect(exists).to.equal(true); }); test('symlink', async function () { if (!SUPPORTS_SYMLINKS) { this.skip(); } const filename = await fix.createFile('x/y/z/spam.py', '...'); const symlink = await fix.createSymlink('x/y/z/eggs.py', filename); const exists = utils.fileExistsSync(symlink); // Note that currently the "file" can be *anything*. It // doesn't have to be just a regular file. This is the // way it already worked, so we're keeping it that way // for now. expect(exists).to.equal(true); }); test('unknown', async function () { if (!SUPPORTS_SOCKETS) { this.skip(); } const sockFile = await fix.createSocket('x/y/z/ipc.sock'); const exists = utils.fileExistsSync(sockFile); // Note that currently the "file" can be *anything*. It // doesn't have to be just a regular file. This is the // way it already worked, so we're keeping it that way // for now. expect(exists).to.equal(true); }); }); }); suite('FileSystem', () => { let fileSystem: FileSystem; let fix: FSFixture; setup(async () => { fileSystem = new FileSystem(); fix = new FSFixture(); await assertDoesNotExist(DOES_NOT_EXIST); }); teardown(async () => { await fix.cleanUp(); await fix.ensureDeleted(DOES_NOT_EXIST); }); suite('path-related', () => { const paths = FileSystemPaths.withDefaults(); const pathUtils = FileSystemPathUtils.withDefaults(paths); suite('directorySeparatorChar', () => { // tested fully in the FileSystemPaths tests. test('matches wrapped object', () => { const expected = paths.sep; const sep = fileSystem.directorySeparatorChar; expect(sep).to.equal(expected); }); }); suite('arePathsSame', () => { // tested fully in the FileSystemPathUtils tests. test('matches wrapped object', () => { const file1 = fixPath('a/b/c/spam.py'); const file2 = fixPath('a/b/c/Spam.py'); const expected = pathUtils.arePathsSame(file1, file2); const areSame = fileSystem.arePathsSame(file1, file2); expect(areSame).to.equal(expected); }); }); }); suite('raw', () => { suite('appendFile', () => { test('wraps the low-level impl', async () => { const filename = await fix.createFile('spam.txt'); const dataToAppend = `Some Data\n${new Date().toString()}\nAnd another line`; const expected = dataToAppend; await fileSystem.appendFile(filename, dataToAppend); const actual = await fs.readFile(filename, 'utf8'); expect(actual).to.be.equal(expected); }); }); suite('chmod (non-Windows)', () => { suiteSetup(function () { // On Windows, chmod won't have any effect on the file itself. if (WINDOWS) { this.skip(); } }); test('wraps the low-level impl', async () => { const filename = await fix.createFile('spam.py', '...'); await fs.chmod(filename, 0o644); await fileSystem.chmod(filename, '755'); const stat = await fs.stat(filename); expect(stat.mode & 0o777).to.equal(0o755); }); }); //============================= // sync methods suite('readFileSync', () => { test('wraps the low-level impl', async () => { const expected = '<some text>'; const filename = await fix.createFile('x/y/z/spam.py', expected); const text = fileSystem.readFileSync(filename); expect(text).to.be.equal(expected); }); }); suite('createReadStream', () => { test('wraps the low-level impl', async function () { // This test seems to randomly fail. this.skip(); const filename = await fix.createFile('x/y/z/spam.py', '...'); const expected = fs.createReadStream(filename); expected.destroy(); const stream = fileSystem.createReadStream(filename); stream.destroy(); expect(stream.path).to.deep.equal(expected.path); }); }); suite('createWriteStream', () => { test('wraps the low-level impl', async function () { // This test seems to randomly fail. this.skip(); const filename = await fix.resolve('x/y/z/spam.py'); const expected = fs.createWriteStream(filename); expected.destroy(); const stream = fileSystem.createWriteStream(filename); stream.destroy(); expect(stream.path).to.deep.equal(expected.path); }); }); }); suite('utils', () => { suite('getFileHash', () => { // Since getFileHash() relies on timestamps, we have to take // into account filesystem timestamp resolution. For instance // on FAT and HFS it is 1 second. // See: https://nodejs.org/api/fs.html#fs_stat_time_values test('Getting hash for a file should return non-empty string', async () => { const filename = await fix.createFile('x/y/z/spam.py'); const hash = await fileSystem.getFileHash(filename); expect(hash).to.not.equal(''); }); test('the returned hash is stable', async () => { const filename = await fix.createFile('x/y/z/spam.py'); const hash1 = await fileSystem.getFileHash(filename); const hash2 = await fileSystem.getFileHash(filename); await sleep(2_000); // just in case const hash3 = await fileSystem.getFileHash(filename); expect(hash1).to.equal(hash2); expect(hash1).to.equal(hash3); expect(hash2).to.equal(hash3); }); test('the returned hash changes with modification', async () => { const filename = await fix.createFile('x/y/z/spam.py', 'original text'); const hash1 = await fileSystem.getFileHash(filename); await sleep(2_000); // for filesystems with 1s resolution await fs.writeFile(filename, 'new text'); const hash2 = await fileSystem.getFileHash(filename); expect(hash1).to.not.equal(hash2); }); test('the returned hash is unique', async () => { const file1 = await fix.createFile('spam.py'); await sleep(2_000); // for filesystems with 1s resolution const file2 = await fix.createFile('x/y/z/spam.py'); await sleep(2_000); // for filesystems with 1s resolution const file3 = await fix.createFile('eggs.py'); const hash1 = await fileSystem.getFileHash(file1); const hash2 = await fileSystem.getFileHash(file2); const hash3 = await fileSystem.getFileHash(file3); expect(hash1).to.not.equal(hash2); expect(hash1).to.not.equal(hash3); expect(hash2).to.not.equal(hash3); }); test('Getting hash for non existent file should throw error', async () => { const promise = fileSystem.getFileHash(DOES_NOT_EXIST); await expect(promise).to.eventually.be.rejected; }); }); suite('search', () => { test('found matches', async () => { const pattern = await fix.resolve(`x/y/z/spam.*`); const expected: string[] = [ await fix.createFile('x/y/z/spam.py'), await fix.createFile('x/y/z/spam.pyc'), await fix.createFile('x/y/z/spam.so'), await fix.createDirectory('x/y/z/spam.data'), ]; // non-matches await fix.createFile('x/spam.py'); await fix.createFile('x/y/z/eggs.py'); await fix.createFile('x/y/z/spam-all.py'); await fix.createFile('x/y/z/spam'); await fix.createFile('x/spam.py'); await fix.createFile('x/y/z/.net.py'); let files = await fileSystem.search(pattern); // For whatever reason, on Windows "search()" is // returning filenames with forward slasshes... files = files.map(fixPath); expect(files.sort()).to.deep.equal(expected.sort()); }); test('found dot matches', async () => { const dir = await fix.resolve(`x/y/z`); const expected: string[] = [ await fix.createFile('x/y/z/spam.py'), await fix.createFile('x/y/z/.net.py'), ]; // non-matches await fix.createFile('x/spam.py'); await fix.createFile('x/y/z/spam'); await fix.createFile('x/spam.py'); let files = await fileSystem.search(`${dir}/**/*.py`, undefined, true); // For whatever reason, on Windows "search()" is // returning filenames with forward slasshes... files = files.map(fixPath); expect(files.sort()).to.deep.equal(expected.sort()); }); test('no matches', async () => { const pattern = await fix.resolve(`x/y/z/spam.*`); const files = await fileSystem.search(pattern); expect(files).to.deep.equal([]); }); }); //============================= // sync methods suite('fileExistsSync', () => { test('want file, got file', async () => { const filename = await fix.createFile('x/y/z/spam.py'); const exists = fileSystem.fileExistsSync(filename); expect(exists).to.equal(true); }); test('want file, not file', async () => { const filename = await fix.createDirectory('x/y/z/spam.py'); const exists = fileSystem.fileExistsSync(filename); // Note that currently the "file" can be *anything*. It // doesn't have to be just a regular file. This is the // way it already worked, so we're keeping it that way // for now. expect(exists).to.equal(true); }); test('symlink', async function () { if (!SUPPORTS_SYMLINKS) { this.skip(); } const filename = await fix.createFile('x/y/z/spam.py', '...'); const symlink = await fix.createSymlink('x/y/z/eggs.py', filename); const exists = fileSystem.fileExistsSync(symlink); // Note that currently the "file" can be *anything*. It // doesn't have to be just a regular file. This is the // way it already worked, so we're keeping it that way // for now. expect(exists).to.equal(true); }); test('unknown', async function () { if (!SUPPORTS_SOCKETS) { this.skip(); } const sockFile = await fix.createSocket('x/y/z/ipc.sock'); const exists = fileSystem.fileExistsSync(sockFile); // Note that currently the "file" can be *anything*. It // doesn't have to be just a regular file. This is the // way it already worked, so we're keeping it that way // for now. expect(exists).to.equal(true); }); }); }); });
the_stack
import { createRouter, createWebHistory, RouteRecordRaw } from "vue-router"; import { DefineComponent } from 'vue'; // console.log(router) import layOut from "@/layout/index.vue"; import much from "@/layout/components/router-view.vue"; import { NextLoading } from '@/utils/loading' // progress bar // meta 参数 /** * @param {string} title 标题 * @param {string} locale i18n 配置的属性,在language文件夹 * @param {string} icon 图标 * @param {string} url 外链 * @param {string} iframeUrl 内嵌网页 * @param {string} iframeData 内嵌网页attr * @param {boolean} breadcrumb 是否不展示在 “面包屑”组件上展示 * @param {number} sort 动态添加排序 */ export interface Routers { path: string, component: DefineComponent | Function, name?: string, redirect?: string, meta?: { title: string, icon: string, locale?: string, breadcrumb?: boolean, url?: string, iframeUrl?: string, iframeData?: any, }, children?: Routers[], hidden?: boolean, // 动态添加 sort?: number } const routes: Routers[] = [ { path: "/", component: layOut, redirect: "/home", meta: { title: "首页", locale: 'home', icon: "viteshouye", // breadcrumb: true }, children: [ { path: "home", name: "home", component: () => import("@/views/home/index.vue"), meta: { title: "首页", locale: 'home', icon: "viteshouye", }, }, ], }, { path: "/redirect", name: "redirect", hidden: true, component: () => import("@/views/redirect.vue"), }, { path: "/login", name: "login", meta: { title: "登录", icon: "about", }, hidden: true, // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import("@/views/login/index.vue"), }, ]; export const addRouter: Routers[] = [ { path: "/modules", component: layOut, redirect: "/modules/table", name: "modules", meta: { title: "组件列表", locale: 'component.list', icon: "vitezujian", }, children: [ { path: "table", name: "table", component: () => import("@/views/modules/table/index.vue"), meta: { title: "表格", locale: 'table', icon: "viteZJ-biaoge" }, }, { path: "export", name: "export", component: () => import("@/views/modules/export/index.vue"), meta: { title: "导出表格", locale: 'export', icon: "vitequanping", }, }, { path: "antv-x6", name: "antv-x6", component: () => import("@/views/modules/antv-x6/index.vue"), meta: { title: "antv-x6", locale: 'antv-x6', icon: "viteantv", }, }, { path: "upload", name: "upload", component: () => import("@/views/modules/upload/index.vue"), meta: { title: "上传文件", locale: 'upload.file', icon: "viteZJ-shangchaun", }, }, { path: "form", name: "form", component: () => import("@/views/modules/form/index.vue"), meta: { title: "表单", locale: 'form', icon: "viteZJ-shangchaun", }, }, { path: "icon", name: "icon", component: () => import("@/views/modules/icons/index.vue"), meta: { title: "图标", locale: 'icon', icon: "vitei", }, }, { path: "richText", name: "richText", component: () => import("@/views/modules/rich-text/index.vue"), meta: { title: "富文本", locale: 'rich.text', icon: "viteZJ-fuwenben", }, }, { path: "map", name: "map", component: () => import("@/views/modules/map/index.vue"), meta: { title: "地图", locale: 'map', icon: "viteviteZJ-ditu", }, }, { path: "sign", name: "sign", component: () => import("@/views/modules/sign/sign.vue"), meta: { title: "签名", locale: 'sign', icon: "viteviteZJ-sign", }, }, ], }, { path: "/much-router", component: layOut, redirect: "/much-router/much-menu-one", name: "much-router", meta: { title: "嵌套路由", locale: 'nesting.router', icon: "viteroute", }, children: [ { path: "much-menu-one", name: "much-menu-one", component: () => import("@/views/modules/antv-x6/index.vue"), meta: { title: "二级菜单(一)", locale: 'nesting.router.menu.two.1', icon: "vitecaidanliebiao", }, }, { path: "much-menu-two", name: "much-menu-two", component: much, meta: { title: "二级菜单(二)", locale: 'nesting.router.menu.two.2', icon: "viteantv", }, children: [ { path: "much-menu-two-one", name: "much-menu-two-one", component: () => import("@/views/modules/rich-text/index.vue"), meta: { title: "富文本", locale: 'rich.text', icon: "viteZJ-fuwenben", }, }, { path: "much-menu-two-two", name: "much-menu-two-two", component: much, meta: { title: "三级菜单", locale: 'nesting.router.menu.three', icon: "vitecaidanliebiao", }, children: [ { path: "much-menu-three-one", name: "much-menu-three-one", component: () => import("@/views/modules/map/index.vue"), meta: { title: "地图", locale: 'map', icon: "viteviteZJ-map", }, }, { path: "much-menu-three-two", name: "much-menu-three-two", component: () => import("@/views/modules/icons/index.vue"), meta: { title: "图标", locale: 'icon', icon: "viteviteZJ-icon", }, }, ], }, ], } ], }, { path: "/markDown", name: "markDown", component: layOut, redirect: "/markDown/markDownEditor", meta: { title: "markdown", icon: "vitemarkdown", locale: 'markdown', }, children: [ { path: "markDownEditor", name: "markDownEditor", component: () => import("@/views/markdown/index.vue"), meta: { title: "markdown编辑器", locale: 'markdown.editor', icon: "vitemarkdown", }, }, { path: "markDownPreview", name: "markDownPreview", component: () => import("@/views/markdown/preview.vue"), meta: { title: "markdown预览", locale: 'markdown.preview', icon: "viteyanjing", }, }] }, { path: "/eCharts", component: layOut, redirect: "/eCharts/eChartLine", name: "eCharts", meta: { title: "图表", locale: 'chart', icon: "vitetubiao", }, children: [ { path: "eChartLine", name: "eChartLine", component: () => import("@/views/eCharts/line.vue"), meta: { title: "折线图", locale: 'line.chart', icon: "vitezhexiantu", }, }, { path: "eChartPillar", name: "eChartPillar", component: () => import("@/views/eCharts/pillar.vue"), meta: { title: "柱状图", locale: 'pillar.chart', icon: "vitezhuzhuangtu", }, }, { path: "eChartCake", name: "eChartCake", component: () => import("@/views/eCharts/cake.vue"), meta: { title: "饼状图", locale: 'cake.chart', icon: "vitebingzhuangtu", }, }, ], }, { path: "/log", component: layOut, redirect: "/log/add-log", name: "log", meta: { title: "日志", locale: 'log', icon: "vitebullseye", }, children: [ { path: "error-log", name: "error-log", component: () => import("@/views/log/error-log.vue"), meta: { title: "错误日志", locale: 'bug.log', icon: "vitebug", }, }, { path: "ajax-log", name: "ajax-log", component: () => import("@/views/log/ajax-log.vue"), meta: { title: "ajax 错误", locale: 'ajax.log', icon: "viteAPI", }, }, { path: "add-log", name: "add-log", component: () => import("@/views/log/add-log.vue"), meta: { title: "添加日志", locale: 'add.log', icon: "viteyumaobi", }, }, ], }, { path: "/directives", component: layOut, redirect: "/directives/add-log", name: "directives", meta: { title: "指令", locale: 'directive', icon: "vitedirective", }, children: [ { path: "number-directive", name: "number-directive", component: () => import("@/views/directives/number.vue"), meta: { title: "数字指令", locale: 'number.directive', icon: "vitenumber", }, }, { path: "press-key-directive", name: "press-key-directive", component: () => import("@/views/directives/press-key.vue"), meta: { title: "按键指令", locale: 'press.key.directive', icon: "vitepress-key", }, }, { path: "debounce-throttle", name: "debounce-throttle", component: () => import("@/views/directives/debounce-throttle.vue"), meta: { title: "防抖&节流指令", locale: 'debounce.throttle.directive', icon: "vitethrottle", }, }, { path: "copy-directive", name: "copy-directive", component: () => import("@/views/directives/copy.vue"), meta: { title: "复制文本指令", icon: "vitecopy", locale: "copy.directive", }, }, { path: "demo-directive", name: "demo-directive", component: () => import("@/views/authority/demo/demo.vue"), meta: { title: "权限指令", icon: "vitecaidanliebiao", locale: "demo.directive", }, }, ], }, { path: "/authority", component: layOut, redirect: "/authority/menu", name: "authority", meta: { title: "权限", icon: "vitequanxianguanli-02", locale: 'authority', }, children: [ { path: "admin", name: "admin", component: () => import("@/views/authority/admin/index.vue"), meta: { title: "用户列表", icon: "viteyonghuliebiao", locale: "user.list", }, }, { path: "menu", name: "menu", component: () => import("@/views/authority/menu/index.vue"), meta: { title: "菜单列表", icon: "vitecaidanliebiao", locale: "menu.list", }, }, { path: "demo", name: "demo", component: () => import("@/views/authority/demo/demo.vue"), meta: { title: "权限演示", icon: "vitecaidanliebiao", locale: "authority.demo", }, }, ], }, { path: "/iframe", component: layOut, redirect: "/iframe/iframe-", name: "iframe", meta: { title: "iframe", locale: 'iframe', icon: "viteiframe", }, children: [ { path: "iframe-", name: "iframe-", component: () => import("@/views/iframe/index.vue"), meta: { title: "iframe", iframeUrl: 'https://cn.vitejs.dev/', iframeData: { width: '100%', height: '650px' }, icon: "viteiframe", }, }, ], }, { path: "/interlink", component: layOut, redirect: "/interlink/link", name: "interlink", meta: { title: "interlink", locale: 'interlink', icon: "vitelianjie", }, children: [ { path: "link", name: "link", component: () => import("@/views/link/index.vue"), meta: { title: "外链", url: 'https://cn.vitejs.dev/', icon: "vitelianjie", }, }, ], }, { path: "/:pathMatch(.*)", name: "404", component: () => import("../views/404.vue"), hidden: true, }, ]; const _router = createRouter({ history: createWebHistory(), routes: routes as RouteRecordRaw[], }); NextLoading.start() export default _router;
the_stack
import 'rxjs/add/operator/map'; import 'rxjs/add/operator/scan'; import 'rxjs/add/operator/mergeMap'; import 'rxjs/add/operator/concat'; import 'rxjs/add/operator/concatMap'; import 'rxjs/add/operator/every'; import 'rxjs/add/operator/mergeAll'; import 'rxjs/add/observable/from'; import {Location} from '@angular/common'; import {ComponentResolver, Injector, ReflectiveInjector, Type} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import {Subject} from 'rxjs/Subject'; import {Subscription} from 'rxjs/Subscription'; import {of } from 'rxjs/observable/of'; import {applyRedirects} from './apply_redirects'; import {RouterConfig, validateConfig} from './config'; import {createRouterState} from './create_router_state'; import {createUrlTree} from './create_url_tree'; import {RouterOutlet} from './directives/router_outlet'; import {recognize} from './recognize'; import {resolve} from './resolve'; import {RouterOutletMap} from './router_outlet_map'; import {ActivatedRoute, ActivatedRouteSnapshot, RouterState, RouterStateSnapshot, advanceActivatedRoute, createEmptyState} from './router_state'; import {PRIMARY_OUTLET, Params} from './shared'; import {UrlSerializer} from './url_serializer'; import {UrlTree, createEmptyUrlTree} from './url_tree'; import {forEach, shallowEqual} from './utils/collection'; import {TreeNode} from './utils/tree'; export interface NavigationExtras { relativeTo?: ActivatedRoute; queryParams?: Params; fragment?: string; } /** * An event triggered when a navigation starts */ export class NavigationStart { constructor(public id: number, public url: string) {} toString(): string { return `NavigationStart(id: ${this.id}, url: '${this.url}')`; } } /** * An event triggered when a navigation ends successfully */ export class NavigationEnd { constructor(public id: number, public url: string, public urlAfterRedirects: string) {} toString(): string { return `NavigationEnd(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}')`; } } /** * An event triggered when a navigation is canceled */ export class NavigationCancel { constructor(public id: number, public url: string) {} toString(): string { return `NavigationCancel(id: ${this.id}, url: '${this.url}')`; } } /** * An event triggered when a navigation fails due to unexpected error */ export class NavigationError { constructor(public id: number, public url: string, public error: any) {} toString(): string { return `NavigationError(id: ${this.id}, url: '${this.url}', error: ${this.error})`; } } /** * An event triggered when routes are recognized */ export class RoutesRecognized { constructor( public id: number, public url: string, public urlAfterRedirects: string, public state: RouterStateSnapshot) {} toString(): string { return `RoutesRecognized(id: ${this.id}, url: '${this.url}', urlAfterRedirects: '${this.urlAfterRedirects}', state: ${this.state})`; } } export type Event = NavigationStart | NavigationEnd | NavigationCancel | NavigationError; /** * The `Router` is responsible for mapping URLs to components. */ export class Router { private currentUrlTree: UrlTree; private currentRouterState: RouterState; private locationSubscription: Subscription; private routerEvents: Subject<Event>; private navigationId: number = 0; private config: RouterConfig; /** * @internal */ constructor( private rootComponentType: Type, private resolver: ComponentResolver, private urlSerializer: UrlSerializer, private outletMap: RouterOutletMap, private location: Location, private injector: Injector, config: RouterConfig) { this.resetConfig(config); this.routerEvents = new Subject<Event>(); this.currentUrlTree = createEmptyUrlTree(); this.currentRouterState = createEmptyState(this.currentUrlTree, this.rootComponentType); } /** * @internal */ initialNavigation(): void { this.setUpLocationChangeListener(); this.navigateByUrl(this.location.path()); } /** * Returns the current route state. */ get routerState(): RouterState { return this.currentRouterState; } /** * Returns the current url. */ get url(): string { return this.serializeUrl(this.currentUrlTree); } /** * Returns an observable of route events */ get events(): Observable<Event> { return this.routerEvents; } /** * Resets the configuration used for navigation and generating links. * * ### Usage * * ``` * router.resetConfig([ * { path: 'team/:id', component: TeamCmp, children: [ * { path: 'simple', component: SimpleCmp }, * { path: 'user/:name', component: UserCmp } * ] } * ]); * ``` */ resetConfig(config: RouterConfig): void { validateConfig(config); this.config = config; } /** * @internal */ dispose(): void { this.locationSubscription.unsubscribe(); } /** * Applies an array of commands to the current url tree and creates * a new url tree. * * When given an activate route, applies the given commands starting from the route. * When not given a route, applies the given command starting from the root. * * ### Usage * * ``` * // create /team/33/user/11 * router.createUrlTree(['/team', 33, 'user', 11]); * * // create /team/33;expand=true/user/11 * router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]); * * // you can collapse static fragments like this * router.createUrlTree(['/team/33/user', userId]); * * // assuming the current url is `/team/33/user/11` and the route points to `user/11` * * // navigate to /team/33/user/11/details * router.createUrlTree(['details'], {relativeTo: route}); * * // navigate to /team/33/user/22 * router.createUrlTree(['../22'], {relativeTo: route}); * * // navigate to /team/44/user/22 * router.createUrlTree(['../../team/44/user/22'], {relativeTo: route}); * ``` */ createUrlTree(commands: any[], {relativeTo, queryParams, fragment}: NavigationExtras = {}): UrlTree { const a = relativeTo ? relativeTo : this.routerState.root; return createUrlTree(a, this.currentUrlTree, commands, queryParams, fragment); } /** * Navigate based on the provided url. This navigation is always absolute. * * Returns a promise that: * - is resolved with 'true' when navigation succeeds * - is resolved with 'false' when navigation fails * - is rejected when an error happens * * ### Usage * * ``` * router.navigateByUrl("/team/33/user/11"); * ``` */ navigateByUrl(url: string|UrlTree): Promise<boolean> { if (url instanceof UrlTree) { return this.scheduleNavigation(url, false); } else { const urlTree = this.urlSerializer.parse(url); return this.scheduleNavigation(urlTree, false); } } /** * Navigate based on the provided array of commands and a starting point. * If no starting route is provided, the navigation is absolute. * * Returns a promise that: * - is resolved with 'true' when navigation succeeds * - is resolved with 'false' when navigation fails * - is rejected when an error happens * * ### Usage * * ``` * router.navigate(['team', 33, 'team', '11], {relativeTo: route}); * ``` */ navigate(commands: any[], extras: NavigationExtras = {}): Promise<boolean> { return this.scheduleNavigation(this.createUrlTree(commands, extras), false); } /** * Serializes a {@link UrlTree} into a string. */ serializeUrl(url: UrlTree): string { return this.urlSerializer.serialize(url); } /** * Parse a string into a {@link UrlTree}. */ parseUrl(url: string): UrlTree { return this.urlSerializer.parse(url); } private scheduleNavigation(url: UrlTree, preventPushState: boolean): Promise<boolean> { const id = ++this.navigationId; this.routerEvents.next(new NavigationStart(id, this.serializeUrl(url))); return Promise.resolve().then((_) => this.runNavigate(url, preventPushState, id)); } private setUpLocationChangeListener(): void { this.locationSubscription = <any>this.location.subscribe((change) => { return this.scheduleNavigation(this.urlSerializer.parse(change['url']), change['pop']); }); } private runNavigate(url: UrlTree, preventPushState: boolean, id: number): Promise<boolean> { if (id !== this.navigationId) { this.location.go(this.urlSerializer.serialize(this.currentUrlTree)); this.routerEvents.next(new NavigationCancel(id, this.serializeUrl(url))); return Promise.resolve(false); } return new Promise((resolvePromise, rejectPromise) => { let updatedUrl: UrlTree; let state: RouterState; applyRedirects(url, this.config) .mergeMap(u => { updatedUrl = u; return recognize( this.rootComponentType, this.config, updatedUrl, this.serializeUrl(updatedUrl)); }) .mergeMap((newRouterStateSnapshot) => { this.routerEvents.next(new RoutesRecognized( id, this.serializeUrl(url), this.serializeUrl(updatedUrl), newRouterStateSnapshot)); return resolve(this.resolver, newRouterStateSnapshot); }) .map((routerStateSnapshot) => { return createRouterState(routerStateSnapshot, this.currentRouterState); }) .map((newState: RouterState) => { state = newState; }) .mergeMap(_ => { return new GuardChecks(state.snapshot, this.currentRouterState.snapshot, this.injector) .check(this.outletMap); }) .forEach((shouldActivate: boolean) => { if (!shouldActivate || id !== this.navigationId) { this.routerEvents.next(new NavigationCancel(id, this.serializeUrl(url))); return Promise.resolve(false); } new ActivateRoutes(state, this.currentRouterState).activate(this.outletMap); this.currentUrlTree = updatedUrl; this.currentRouterState = state; if (!preventPushState) { let path = this.urlSerializer.serialize(updatedUrl); if (this.location.isCurrentPathEqualTo(path)) { this.location.replaceState(path); } else { this.location.go(path); } } return Promise.resolve(true); }) .then( () => { this.routerEvents.next( new NavigationEnd(id, this.serializeUrl(url), this.serializeUrl(updatedUrl))); resolvePromise(true); }, e => { this.routerEvents.next(new NavigationError(id, this.serializeUrl(url), e)); rejectPromise(e); }); }); } } class CanActivate { constructor(public route: ActivatedRouteSnapshot) {} } class CanDeactivate { constructor(public component: Object, public route: ActivatedRouteSnapshot) {} } class GuardChecks { private checks: Array<CanActivate|CanDeactivate> = []; constructor( private future: RouterStateSnapshot, private curr: RouterStateSnapshot, private injector: Injector) {} check(parentOutletMap: RouterOutletMap): Observable<boolean> { const futureRoot = this.future._root; const currRoot = this.curr ? this.curr._root : null; this.traverseChildRoutes(futureRoot, currRoot, parentOutletMap); if (this.checks.length === 0) return of (true); return Observable.from(this.checks) .map(s => { if (s instanceof CanActivate) { return this.runCanActivate(s.route); } else if (s instanceof CanDeactivate) { return this.runCanDeactivate(s.component, s.route); } else { throw new Error('Cannot be reached'); } }) .mergeAll() .every(result => result === true); } private traverseChildRoutes( futureNode: TreeNode<ActivatedRouteSnapshot>, currNode: TreeNode<ActivatedRouteSnapshot>, outletMap: RouterOutletMap): void { const prevChildren: {[key: string]: any} = nodeChildrenAsMap(currNode); futureNode.children.forEach(c => { this.traverseRoutes(c, prevChildren[c.value.outlet], outletMap); delete prevChildren[c.value.outlet]; }); forEach( prevChildren, (v: any, k: string) => this.deactivateOutletAndItChildren(v, outletMap._outlets[k])); } traverseRoutes( futureNode: TreeNode<ActivatedRouteSnapshot>, currNode: TreeNode<ActivatedRouteSnapshot>, parentOutletMap: RouterOutletMap): void { const future = futureNode.value; const curr = currNode ? currNode.value : null; const outlet = parentOutletMap ? parentOutletMap._outlets[futureNode.value.outlet] : null; // reusing the node if (curr && future._routeConfig === curr._routeConfig) { if (!shallowEqual(future.params, curr.params)) { this.checks.push(new CanDeactivate(outlet.component, curr), new CanActivate(future)); } // If we have a component, we need to go through an outlet. // Otherwise, this route is not represented in the component tree. if (future.component) { this.traverseChildRoutes(futureNode, currNode, outlet ? outlet.outletMap : null); } else { this.traverseChildRoutes(futureNode, currNode, parentOutletMap); } } else { // if we had a componentless route, we need to deactivate everything! if (curr) { if (curr.component) { this.deactivateOutletAndItChildren(curr, outlet); } else { this.deactivateOutletMap(parentOutletMap); } } // if we have a component, we need to deactivate its outlet, run canActivate, // and then traverse its children with the outlet map from that outlet. // Otherwise, this route is not represented in the component tree, // so we reuse the parent map. this.checks.push(new CanActivate(future)); if (future.component) { this.traverseChildRoutes(futureNode, null, outlet ? outlet.outletMap : null); } else { this.traverseChildRoutes(futureNode, null, parentOutletMap); } } } private deactivateOutletAndItChildren(route: ActivatedRouteSnapshot, outlet: RouterOutlet): void { if (outlet && outlet.isActivated) { this.deactivateOutletMap(outlet.outletMap); this.checks.push(new CanDeactivate(outlet.component, route)); } } private deactivateOutletMap(outletMap: RouterOutletMap): void { forEach(outletMap._outlets, (v: RouterOutlet) => { if (v.isActivated) { this.deactivateOutletAndItChildren(v.activatedRoute.snapshot, v); } }); } private runCanActivate(future: ActivatedRouteSnapshot): Observable<boolean> { const canActivate = future._routeConfig ? future._routeConfig.canActivate : null; if (!canActivate || canActivate.length === 0) return of (true); return Observable.from(canActivate) .map(c => { const guard = this.injector.get(c); if (guard.canActivate) { return wrapIntoObservable(guard.canActivate(future, this.future)); } else { return wrapIntoObservable(guard(future, this.future)); } }) .mergeAll() .every(result => result === true); } private runCanDeactivate(component: Object, curr: ActivatedRouteSnapshot): Observable<boolean> { const canDeactivate = curr._routeConfig ? curr._routeConfig.canDeactivate : null; if (!canDeactivate || canDeactivate.length === 0) return of (true); return Observable.from(canDeactivate) .map(c => { const guard = this.injector.get(c); if (guard.canDeactivate) { return wrapIntoObservable(guard.canDeactivate(component, curr, this.curr)); } else { return wrapIntoObservable(guard(component, curr, this.curr)); } }) .mergeAll() .every(result => result === true); } } function wrapIntoObservable<T>(value: T | Observable<T>): Observable<T> { if (value instanceof Observable) { return value; } else { return of (value); } } class ActivateRoutes { constructor(private futureState: RouterState, private currState: RouterState) {} activate(parentOutletMap: RouterOutletMap): void { const futureRoot = this.futureState._root; const currRoot = this.currState ? this.currState._root : null; pushQueryParamsAndFragment(this.futureState); this.activateChildRoutes(futureRoot, currRoot, parentOutletMap); } private activateChildRoutes( futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute>, outletMap: RouterOutletMap): void { const prevChildren: {[key: string]: any} = nodeChildrenAsMap(currNode); futureNode.children.forEach(c => { this.activateRoutes(c, prevChildren[c.value.outlet], outletMap); delete prevChildren[c.value.outlet]; }); forEach( prevChildren, (v: any, k: string) => this.deactivateOutletAndItChildren(outletMap._outlets[k])); } activateRoutes( futureNode: TreeNode<ActivatedRoute>, currNode: TreeNode<ActivatedRoute>, parentOutletMap: RouterOutletMap): void { const future = futureNode.value; const curr = currNode ? currNode.value : null; // reusing the node if (future === curr) { // advance the route to push the parameters advanceActivatedRoute(future); // If we have a component, we need to go through an outlet. // Otherwise, this route is not represented in the component tree. if (future.component) { const outlet = getOutlet(parentOutletMap, futureNode.value); this.activateChildRoutes(futureNode, currNode, outlet.outletMap); } else { this.activateChildRoutes(futureNode, currNode, parentOutletMap); } } else { // if we had a componentless route, we need to deactivate everything! if (curr) { if (curr.component) { const outlet = getOutlet(parentOutletMap, futureNode.value); this.deactivateOutletAndItChildren(outlet); } else { this.deactivateOutletMap(parentOutletMap); } } // if we have a component, we need to advance the route // and place the component into the outlet. // Otherwise, this route is not represented in the component tree. if (future.component) { // this.deactivateOutletAndItChildren(outlet); advanceActivatedRoute(future); const outlet = getOutlet(parentOutletMap, futureNode.value); const outletMap = new RouterOutletMap(); this.placeComponentIntoOutlet(outletMap, future, outlet); this.activateChildRoutes(futureNode, null, outletMap); } else { advanceActivatedRoute(future); this.activateChildRoutes(futureNode, null, parentOutletMap); } } } private placeComponentIntoOutlet( outletMap: RouterOutletMap, future: ActivatedRoute, outlet: RouterOutlet): void { const resolved = ReflectiveInjector.resolve([ {provide: ActivatedRoute, useValue: future}, {provide: RouterOutletMap, useValue: outletMap} ]); outlet.activate(future._futureSnapshot._resolvedComponentFactory, future, resolved, outletMap); } private deactivateOutletAndItChildren(outlet: RouterOutlet): void { if (outlet && outlet.isActivated) { this.deactivateOutletMap(outlet.outletMap); outlet.deactivate(); } } private deactivateOutletMap(outletMap: RouterOutletMap): void { forEach(outletMap._outlets, (v: RouterOutlet) => this.deactivateOutletAndItChildren(v)); } } function pushQueryParamsAndFragment(state: RouterState): void { if (!shallowEqual(state.snapshot.queryParams, (<any>state.queryParams).value)) { (<any>state.queryParams).next(state.snapshot.queryParams); } if (state.snapshot.fragment !== (<any>state.fragment).value) { (<any>state.fragment).next(state.snapshot.fragment); } } function nodeChildrenAsMap(node: TreeNode<any>) { return node ? node.children.reduce((m: any, c: TreeNode<any>) => { m[c.value.outlet] = c; return m; }, {}) : {}; } function getOutlet(outletMap: RouterOutletMap, route: ActivatedRoute): RouterOutlet { let outlet = outletMap._outlets[route.outlet]; if (!outlet) { const componentName = (<any>route.component).name; if (route.outlet === PRIMARY_OUTLET) { throw new Error(`Cannot find primary outlet to load '${componentName}'`); } else { throw new Error(`Cannot find the outlet ${route.outlet} to load '${componentName}'`); } } return outlet; }
the_stack
* @module iModelHubClient */ import { AccessToken, GuidString, Logger } from "@itwin/core-bentley"; import { request, RequestOptions, Response } from "@bentley/itwin-client"; import { ECJsonTypeMap, WsgInstance } from "../wsg/ECJsonTypeMap"; import { IModelHubClientLoggerCategory } from "../IModelHubClientLoggerCategories"; import { IModelBaseHandler } from "./BaseHandler"; import { ArgumentCheck } from "./Errors"; import { BaseEventSAS, EventBaseHandler, EventListener, GetEventOperationToRequestType, IModelHubBaseEvent, ListenerSubscription, } from "./EventsBase"; const loggerCategory: string = IModelHubClientLoggerCategory.IModelHub; /** Type of [[IModelHubGlobalEvent]]. Global Event type is used to define which events you wish to receive from your [[GlobalEventSubscription]]. See [[GlobalEventSubscriptionHandler.create]] and [[GlobalEventSubscriptionHandler.update]]. * @internal */ export type GlobalEventType = /** Sent when an iModel is put into the archive. See [[SoftiModelDeleteEvent]]. * @internal Rename to SoftIModelDeleteEvent */ "SoftiModelDeleteEvent" | /** Sent when an archived iModel is completely deleted from the storage. See [[HardiModelDeleteEvent]]. * @internal Rename to HardIModelDeleteEvent */ "HardiModelDeleteEvent" | /** Sent when an iModel is created. See [[IModelCreatedEvent]]. * @internal Rename to IModelCreatedEvent */ "iModelCreatedEvent" | /** Sent when a [[ChangeSet]] is pushed. See [[ChangeSetCreatedEvent]]. */ "ChangeSetCreatedEvent" | /** Sent when a named [[Version]] is created. See [[NamedVersionCreatedEvent]]. */ "NamedVersionCreatedEvent" | /** Sent when a new [[Checkpoint]] is generated. See [[GlobalCheckpointCreatedEvent]]. */ "CheckpointCreatedEvent" | /** Sent when a new [[CheckpointV2]] is generated. See [[GlobalCheckpointV2CreatedEvent]]. */ "CheckpointV2CreatedEvent"; /** Base type for all iModelHub global events. * @internal */ export abstract class IModelHubGlobalEvent extends IModelHubBaseEvent { /** Id of the iModel that caused this event. */ public iModelId?: GuidString; /** Id of the [[Project]] that this iModel belongs to. */ public projectId?: string; /** Id of the iTwin that this iModel belongs to. */ public iTwinId?: string; /** Construct this global event from object instance. * @param obj Object instance. * @internal */ public override fromJson(obj: any) { super.fromJson(obj); this.iModelId = obj.iModelId; this.projectId = obj.ProjectId; this.iTwinId = obj.iTwinId; } } /** Sent when an iModel is put into the archive. See [[IModelHandler.delete]]. * @internal Rename to SoftIModelDeleteEvent */ export class SoftiModelDeleteEvent extends IModelHubGlobalEvent { } /** Sent when an archived iModel is completely deleted from the storage. Sent after some time passes after [[IModelHandler.delete]] and iModel is no longer kept in the archive. iModel is kept at least 30 days in the archive. * @internal Rename to HardIModelDeleteEvent */ export class HardiModelDeleteEvent extends IModelHubGlobalEvent { } /** Sent when an iModel is created. See [[IModelHandler.create]]. * @internal */ export class IModelCreatedEvent extends IModelHubGlobalEvent { } /** Sent when a [[ChangeSet]] is pushed. See [[ChangeSetHandler.create]]. Sent together with [[ChangeSetPostPushEvent]]. * @internal */ export class ChangeSetCreatedEvent extends IModelHubGlobalEvent { public changeSetId?: string; public changeSetIndex?: string; public briefcaseId?: number; /** Construct this event from object instance. * @param obj Object instance. */ public override fromJson(obj: any) { super.fromJson(obj); this.changeSetId = obj.ChangeSetId; this.changeSetIndex = obj.ChangeSetIndex; this.briefcaseId = obj.BriefcaseId; } } /** Sent when a named [[Version]] is created. See [[VersionHandler.create]]. * @internal */ export class NamedVersionCreatedEvent extends IModelHubGlobalEvent { public versionId?: GuidString; public versionName?: string; public changeSetId?: string; /** Construct this event from object instance. * @param obj Object instance. */ public override fromJson(obj: any) { super.fromJson(obj); this.versionId = obj.VersionId; this.versionName = obj.VersionName; this.changeSetId = obj.ChangeSetId; } } /** Sent when a new [[Checkpoint]] is generated. [[Checkpoint]]s can be generated daily when there are new [[ChangeSet]]s pushed or when a new [[Version]] is created. * @internal */ export class GlobalCheckpointCreatedEvent extends IModelHubGlobalEvent { public changeSetIndex?: string; public changeSetId?: string; public versionId?: GuidString; /** Construct this event from object instance. * @param obj Object instance. */ public override fromJson(obj: any) { super.fromJson(obj); this.changeSetIndex = obj.ChangeSetIndex; this.changeSetId = obj.ChangeSetId; this.versionId = obj.VersionId; } } /** Sent when a new [[CheckpointV2]] is generated. [[CheckpointV2]] might be created for every [[ChangeSet]]. * @internal */ export class GlobalCheckpointV2CreatedEvent extends IModelHubGlobalEvent { public changeSetIndex?: string; public changeSetId?: string; public versionId?: GuidString; /** Construct this event from object instance. * @param obj Object instance. */ public override fromJson(obj: any) { super.fromJson(obj); this.changeSetIndex = obj.ChangeSetIndex; this.changeSetId = obj.ChangeSetId; this.versionId = obj.VersionId; } } type GlobalEventConstructor = (new (handler?: IModelBaseHandler, sasToken?: string) => IModelHubGlobalEvent); /** Get constructor from GlobalEventType name. */ function constructorFromEventType(type: GlobalEventType): GlobalEventConstructor { switch (type) { case "SoftiModelDeleteEvent": return SoftiModelDeleteEvent; case "HardiModelDeleteEvent": return HardiModelDeleteEvent; case "iModelCreatedEvent": return IModelCreatedEvent; case "ChangeSetCreatedEvent": return ChangeSetCreatedEvent; case "NamedVersionCreatedEvent": return NamedVersionCreatedEvent; case "CheckpointCreatedEvent": return GlobalCheckpointCreatedEvent; case "CheckpointV2CreatedEvent": return GlobalCheckpointV2CreatedEvent; } } /** Parse [[IModelHubGlobalEvent]] from response object. * @param response Response object to parse. * @returns Appropriate global event object. * @internal */ // eslint-disable-next-line @typescript-eslint/naming-convention export function ParseGlobalEvent(response: Response, handler?: IModelBaseHandler, sasToken?: string): IModelHubGlobalEvent { const constructor: GlobalEventConstructor = constructorFromEventType(response.header["content-type"]); const globalEvent = new constructor(handler, sasToken); globalEvent.fromJson({ ...response.header, ...response.body }); return globalEvent; } /** Subscription to receive [[IModelHubGlobalEvent]]s. Each subscription has a separate queue for events that it hasn't read yet. Global event subscriptions do not expire and must be deleted by the user. Use wsgId of this instance for the methods that require subscriptionId. See [[GlobalEventSubscriptionHandler]]. * @internal */ @ECJsonTypeMap.classToJson("wsg", "GlobalScope.GlobalEventSubscription", { schemaPropertyName: "schemaName", classPropertyName: "className" }) export class GlobalEventSubscription extends WsgInstance { @ECJsonTypeMap.propertyToJson("wsg", "properties.EventTypes") public eventTypes?: GlobalEventType[]; @ECJsonTypeMap.propertyToJson("wsg", "properties.SubscriptionId") public subscriptionId?: string; } /** Shared access signature token for getting [[IModelHubGlobalEvent]]s. It's used to authenticate for [[GlobalEventHandler.getEvent]]. To receive an instance call [[GlobalEventHandler.getSASToken]]. * @internal */ @ECJsonTypeMap.classToJson("wsg", "GlobalScope.GlobalEventSAS", { schemaPropertyName: "schemaName", classPropertyName: "className" }) export class GlobalEventSAS extends BaseEventSAS { } /** Handler for managing [[GlobalEventSubscription]]s. * Use [[GlobalEventHandler.Subscriptions]] to get an instance of this class. * @internal */ export class GlobalEventSubscriptionHandler { private _handler: IModelBaseHandler; /** Constructor for GlobalEventSubscriptionHandler. * @param handler Handler for WSG requests. * @internal */ constructor(handler: IModelBaseHandler) { this._handler = handler; } /** Get relative url for GlobalEventSubscription requests. * @param instanceId Id of the subscription. */ private getRelativeUrl(instanceId?: string) { return `/Repositories/Global--Global/GlobalScope/GlobalEventSubscription/${instanceId || ""}`; } /** Create a [[GlobalEventSubscription]]. You can use this to get or update the existing subscription instance, if you only have the original subscriptionId. * @param subscriptionId Guid to be used by global event subscription. It will be a part of the resulting subscription id. * @param globalEvents Array of GlobalEventTypes to subscribe to. * @return Created GlobalEventSubscription instance. * @throws [[IModelHubError]] with [IModelHubStatus.EventSubscriptionAlreadyExists]($bentley) if [[GlobalEventSubscription]] already exists with the specified subscriptionId. * @throws [Common iModelHub errors]($docs/learning/iModelHub/CommonErrors) */ public async create(accessToken: AccessToken, subscriptionId: GuidString, globalEvents: GlobalEventType[]) { Logger.logInfo(loggerCategory, "Creating global event subscription", () => ({ subscriptionId })); ArgumentCheck.validGuid("subscriptionId", subscriptionId); let subscription = new GlobalEventSubscription(); subscription.eventTypes = globalEvents; subscription.subscriptionId = subscriptionId; subscription = await this._handler.postInstance<GlobalEventSubscription>(accessToken, GlobalEventSubscription, this.getRelativeUrl(), subscription); Logger.logTrace(loggerCategory, "Created global event subscription", () => ({ subscriptionId })); return subscription; } /** Update a [[GlobalEventSubscription]]. Can change the [[GlobalEventType]]s specified in the subscription. Must be a valid subscription that was previously created with [[GlobalEventSubscriptionHandler.create]]. * @param subscription Updated GlobalEventSubscription. * @return GlobalEventSubscription instance from iModelHub after update. * @throws [[IModelHubError]] with [IModelHubStatus.EventSubscriptionDoesNotExist]($bentley) if [[GlobalEventSubscription]] does not exist with the specified subscription.wsgId. * @throws [Common iModelHub errors]($docs/learning/iModelHub/CommonErrors) */ public async update(accessToken: AccessToken, subscription: GlobalEventSubscription): Promise<GlobalEventSubscription> { Logger.logInfo(loggerCategory, `Updating global event subscription with instance id: ${subscription.wsgId}`, () => ({ subscriptionId: subscription.subscriptionId })); ArgumentCheck.defined("subscription", subscription); ArgumentCheck.validGuid("subscription.wsgId", subscription.wsgId); const updatedSubscription = await this._handler.postInstance<GlobalEventSubscription>(accessToken, GlobalEventSubscription, this.getRelativeUrl(subscription.wsgId), subscription); Logger.logTrace(loggerCategory, `Updated global event subscription with instance id: ${subscription.wsgId}`, () => ({ subscriptionId: subscription.subscriptionId })); return updatedSubscription; } /** Delete a [[GlobalEventSubscription]]. * @param subscriptionId WSG Id of the GlobalEventSubscription. * @returns Resolves if the GlobalEventSubscription has been successfully deleted. * @throws [[IModelHubError]] with [IModelHubStatus.EventSubscriptionDoesNotExist]($bentley) if GlobalEventSubscription does not exist with the specified subscription.wsgId. * @throws [Common iModelHub errors]($docs/learning/iModelHub/CommonErrors) */ public async delete(accessToken: AccessToken, subscriptionId: string): Promise<void> { Logger.logInfo(loggerCategory, "Deleting global event subscription", () => ({ subscriptionId })); ArgumentCheck.validGuid("subscriptionInstanceId", subscriptionId); await this._handler.delete(accessToken, this.getRelativeUrl(subscriptionId)); Logger.logTrace(loggerCategory, "Deleted global event subscription", () => ({ subscriptionId })); } } /** Type of [[GlobalEventHandler.getEvent]] operations. * @internal */ export enum GetEventOperationType { /** Event will be immediately removed from queue. */ Destructive = 0, /** Event will be locked instead of removed. It has to be later removed via [[IModelHubBaseEvent.delete]]. */ Peek, } /** Handler for receiving [[IModelHubGlobalEvent]]s. * Use [[IModelClient.GlobalEvents]] to get an instance of this class. * @internal */ export class GlobalEventHandler extends EventBaseHandler { private _subscriptionHandler: GlobalEventSubscriptionHandler | undefined; /** Constructor for GlobalEventHandler. * @param handler Handler for WSG requests. * @internal */ constructor(handler: IModelBaseHandler) { super(); this._handler = handler; } /** Get a handler for managing [[GlobalEventSubscription]]s. */ public get subscriptions(): GlobalEventSubscriptionHandler { if (!this._subscriptionHandler) { this._subscriptionHandler = new GlobalEventSubscriptionHandler(this._handler); } return this._subscriptionHandler; } /** Get relative url for GlobalEventSAS requests. */ private getGlobalEventSASRelativeUrl(): string { return `/Repositories/Global--Global/GlobalScope/GlobalEventSAS/`; } /** Get global event SAS Token. Used to authenticate for [[GlobalEventHandler.getEvent]]. * @throws [Common iModelHub errors]($docs/learning/iModelHub/CommonErrors) */ public async getSASToken(accessToken: AccessToken): Promise<GlobalEventSAS> { Logger.logInfo(loggerCategory, "Getting global event SAS token"); const globalEventSAS = await this._handler.postInstance<GlobalEventSAS>(accessToken, GlobalEventSAS, this.getGlobalEventSASRelativeUrl(), new GlobalEventSAS()); Logger.logTrace(loggerCategory, "Got global event SAS token"); return globalEventSAS; } /** Get absolute url for global event requests. * @param baseAddress Base address for the serviceBus. * @param subscriptionId Id of the subscription instance. * @param timeout Optional timeout for long polling. */ private getGlobalEventUrl(baseAddress: string, subscriptionId: string, timeout?: number): string { let url: string = `${baseAddress}/Subscriptions/${subscriptionId}/messages/head`; if (timeout) { url = `${url}?timeout=${timeout}`; } return url; } /** Get an [[IModelHubGlobalEvent]] from the [[GlobalEventSubscription]]. You can use long polling timeout, to have requests return when events are available (or request times out), rather than returning immediately when no events are found. * @param sasToken SAS Token used to authenticate. See [[GlobalEventSAS.sasToken]]. * @param baseAddress Address for the events. See [[GlobalEventSAS.baseAddress]]. * @param subscriptionId Id of the subscription to the topic. See [[GlobalEventSubscription]]. * @param timeout Optional timeout duration in seconds for request, when using long polling. * @return IModelHubGlobalEvent if it exists, undefined otherwise. * @throws [[IModelHubClientError]] with [IModelHubStatus.UndefinedArgumentError]($bentley) or [IModelHubStatus.InvalidArgumentError]($bentley) if one of the arguments is undefined or has an invalid value. * @throws [[ResponseError]] if request has failed. */ public async getEvent(sasToken: string, baseAddress: string, subscriptionId: string, timeout?: number, getOperation: GetEventOperationType = GetEventOperationType.Destructive): Promise<IModelHubGlobalEvent | undefined> { Logger.logInfo(loggerCategory, "Getting global event from subscription", () => ({ subscriptionId })); ArgumentCheck.defined("sasToken", sasToken); ArgumentCheck.defined("baseAddress", baseAddress); ArgumentCheck.defined("subscriptionInstanceId", subscriptionId); let options: RequestOptions; if (getOperation === GetEventOperationType.Destructive) options = await this.getEventRequestOptions(GetEventOperationToRequestType.GetDestructive, sasToken, timeout); else if (getOperation === GetEventOperationType.Peek) options = await this.getEventRequestOptions(GetEventOperationToRequestType.GetPeek, sasToken, timeout); else // Unknown operation type. return undefined; const result = await request(this.getGlobalEventUrl(baseAddress, subscriptionId, timeout), options); if (result.status === 204) { Logger.logTrace(loggerCategory, "No events found on subscription", () => ({ subscriptionId })); return undefined; } const event = ParseGlobalEvent(result, this._handler, sasToken); Logger.logTrace(loggerCategory, "Got Global Event from subscription", () => ({ subscriptionId })); return event; } /** Create a listener for long polling events from a [[GlobalEventSubscription]]. When event is received from the subscription, every registered listener callback is called. This continuously waits for events until all created listeners for that subscriptionInstanceId are deleted. [[GlobalEventSAS]] token expirations are handled automatically, [[AccessToken]] expiration is handled by calling authenticationCallback to get a new token. * @param authenticationCallback Callback used to get AccessToken. Only the first registered authenticationCallback for this subscriptionId will be used. * @param subscriptionInstanceId Id of GlobalEventSubscription. * @param listener Callback that is called when an [[IModelHubGlobalEvent]] is received. * @returns Function that deletes the created listener. * @throws [[IModelHubClientError]] with [IModelHubStatus.UndefinedArgumentError]($bentley) or [IModelHubStatus.InvalidArgumentError]($bentley) if one of the arguments is undefined or has an invalid value. */ public createListener(authenticationCallback: () => Promise<AccessToken | undefined>, subscriptionInstanceId: string, listener: (event: IModelHubGlobalEvent) => void): () => void { ArgumentCheck.defined("subscriptionInstanceId", subscriptionInstanceId); const subscription = new ListenerSubscription(); subscription.authenticationCallback = authenticationCallback; subscription.getEvent = async (sasToken: string, baseAddress: string, id: string, timeout?: number) => this.getEvent(sasToken, baseAddress, id, timeout); subscription.getSASToken = async (token: AccessToken) => this.getSASToken(token); subscription.id = subscriptionInstanceId; return EventListener.create(subscription, listener); } }
the_stack
import { TypeAssertion } from '../types'; import { validate, getType } from '../validator'; import { compile } from '../compiler'; import { serialize, deserialize } from '../serializer'; describe("compiler-1", function() { it("compiler-primitive", function() { const schema = compile(` type FooA = number; type FooB = bigint; type FooC = string; type FooD = boolean; type FooE = null; type FooF = undefined; type BarA = 3; type BarB = 7n; type BarC = 'XB'; type BarD = true; type BazA = integer; `); { expect(Array.from(schema.keys())).toEqual([ 'FooA', 'FooB', 'FooC', 'FooD', 'FooE', 'FooF', 'BarA', 'BarB', 'BarC', 'BarD', 'BazA', ]); } for (const ty of [getType(deserialize(serialize(schema)), 'FooA'), getType(schema, 'FooA')]) { const rhs: TypeAssertion = { name: 'FooA', typeName: 'FooA', kind: 'primitive', primitiveName: 'number', }; expect(ty).toEqual(rhs); expect(validate<number>(0, ty)).toEqual({value: 0}); expect(validate<number>(1, ty)).toEqual({value: 1}); expect(validate<number>(1.1, ty)).toEqual({value: 1.1}); expect(validate<number>(BigInt(0), ty)).toEqual(null); expect(validate<number>(BigInt(1), ty)).toEqual(null); expect(validate<number>('', ty)).toEqual(null); expect(validate<number>('1', ty)).toEqual(null); expect(validate<number>(false, ty)).toEqual(null); expect(validate<number>(true, ty)).toEqual(null); expect(validate<number>(null, ty)).toEqual(null); expect(validate<number>(void 0, ty)).toEqual(null); expect(validate<number>({}, ty)).toEqual(null); expect(validate<number>([], ty)).toEqual(null); expect(validate<number>(3, ty)).toEqual({value: 3}); expect(validate<number>(BigInt(7), ty)).toEqual(null); expect(validate<number>('XB', ty)).toEqual(null); expect(validate<number>(true, ty)).toEqual(null); } for (const ty of [getType(deserialize(serialize(schema)), 'FooB'), getType(schema, 'FooB')]) { const rhs: TypeAssertion = { name: 'FooB', typeName: 'FooB', kind: 'primitive', primitiveName: 'bigint', }; expect(ty).toEqual(rhs); expect(validate<BigInt>(0, ty)).toEqual(null); expect(validate<BigInt>(1, ty)).toEqual(null); expect(validate<BigInt>(1.1, ty)).toEqual(null); expect(validate<BigInt>(BigInt(0), ty)).toEqual({value: BigInt(0)}); expect(validate<BigInt>(BigInt(1), ty)).toEqual({value: BigInt(1)}); expect(validate<BigInt>('', ty)).toEqual(null); expect(validate<BigInt>('1', ty)).toEqual(null); expect(validate<BigInt>(false, ty)).toEqual(null); expect(validate<BigInt>(true, ty)).toEqual(null); expect(validate<BigInt>(null, ty)).toEqual(null); expect(validate<BigInt>(void 0, ty)).toEqual(null); expect(validate<BigInt>({}, ty)).toEqual(null); expect(validate<BigInt>([], ty)).toEqual(null); expect(validate<BigInt>(3, ty)).toEqual(null); expect(validate<BigInt>(BigInt(7), ty)).toEqual({value: BigInt(7)}); expect(validate<BigInt>('XB', ty)).toEqual(null); expect(validate<BigInt>(true, ty)).toEqual(null); } for (const ty of [getType(deserialize(serialize(schema)), 'FooC'), getType(schema, 'FooC')]) { const rhs: TypeAssertion = { name: 'FooC', typeName: 'FooC', kind: 'primitive', primitiveName: 'string', }; expect(ty).toEqual(rhs); expect(validate<string>(0, ty)).toEqual(null); expect(validate<string>(1, ty)).toEqual(null); expect(validate<string>(1.1, ty)).toEqual(null); expect(validate<string>(BigInt(0), ty)).toEqual(null); expect(validate<string>(BigInt(1), ty)).toEqual(null); expect(validate<string>('', ty)).toEqual({value: ''}); expect(validate<string>('1', ty)).toEqual({value: '1'}); expect(validate<string>(false, ty)).toEqual(null); expect(validate<string>(true, ty)).toEqual(null); expect(validate<string>(null, ty)).toEqual(null); expect(validate<string>(void 0, ty)).toEqual(null); expect(validate<string>({}, ty)).toEqual(null); expect(validate<string>([], ty)).toEqual(null); expect(validate<string>(3, ty)).toEqual(null); expect(validate<string>(BigInt(7), ty)).toEqual(null); expect(validate<string>('XB', ty)).toEqual({value: 'XB'}); expect(validate<string>(true, ty)).toEqual(null); } for (const ty of [getType(deserialize(serialize(schema)), 'FooD'), getType(schema, 'FooD')]) { const rhs: TypeAssertion = { name: 'FooD', typeName: 'FooD', kind: 'primitive', primitiveName: 'boolean', }; expect(ty).toEqual(rhs); expect(validate<boolean>(0, ty)).toEqual(null); expect(validate<boolean>(1, ty)).toEqual(null); expect(validate<boolean>(1.1, ty)).toEqual(null); expect(validate<boolean>(BigInt(0), ty)).toEqual(null); expect(validate<boolean>(BigInt(1), ty)).toEqual(null); expect(validate<boolean>('', ty)).toEqual(null); expect(validate<boolean>('1', ty)).toEqual(null); expect(validate<boolean>(false, ty)).toEqual({value: false}); expect(validate<boolean>(true, ty)).toEqual({value: true}); expect(validate<boolean>(null, ty)).toEqual(null); expect(validate<boolean>(void 0, ty)).toEqual(null); expect(validate<boolean>({}, ty)).toEqual(null); expect(validate<boolean>([], ty)).toEqual(null); expect(validate<boolean>(3, ty)).toEqual(null); expect(validate<boolean>(BigInt(7), ty)).toEqual(null); expect(validate<boolean>('XB', ty)).toEqual(null); expect(validate<boolean>(true, ty)).toEqual({value: true}); } for (const ty of [getType(deserialize(serialize(schema)), 'FooE'), getType(schema, 'FooE')]) { const rhs: TypeAssertion = { name: 'FooE', typeName: 'FooE', kind: 'primitive', primitiveName: 'null', }; expect(ty).toEqual(rhs); expect(validate<null>(0, ty)).toEqual(null); expect(validate<null>(1, ty)).toEqual(null); expect(validate<null>(1.1, ty)).toEqual(null); expect(validate<null>(BigInt(0), ty)).toEqual(null); expect(validate<null>(BigInt(1), ty)).toEqual(null); expect(validate<null>('', ty)).toEqual(null); expect(validate<null>('1', ty)).toEqual(null); expect(validate<null>(false, ty)).toEqual(null); expect(validate<null>(true, ty)).toEqual(null); expect(validate<null>(null, ty)).toEqual({value: null}); expect(validate<null>(void 0, ty)).toEqual(null); expect(validate<null>({}, ty)).toEqual(null); expect(validate<null>([], ty)).toEqual(null); expect(validate<null>(3, ty)).toEqual(null); expect(validate<null>(BigInt(7), ty)).toEqual(null); expect(validate<null>('XB', ty)).toEqual(null); expect(validate<null>(true, ty)).toEqual(null); } for (const ty of [getType(deserialize(serialize(schema)), 'FooF'), getType(schema, 'FooF')]) { const rhs: TypeAssertion = { name: 'FooF', typeName: 'FooF', kind: 'primitive', primitiveName: 'undefined', }; expect(ty).toEqual(rhs); expect(validate<undefined>(0, ty)).toEqual(null); expect(validate<undefined>(1, ty)).toEqual(null); expect(validate<undefined>(1.1, ty)).toEqual(null); expect(validate<undefined>(BigInt(0), ty)).toEqual(null); expect(validate<undefined>(BigInt(1), ty)).toEqual(null); expect(validate<undefined>('', ty)).toEqual(null); expect(validate<undefined>('1', ty)).toEqual(null); expect(validate<undefined>(false, ty)).toEqual(null); expect(validate<undefined>(true, ty)).toEqual(null); expect(validate<undefined>(null, ty)).toEqual(null); expect(validate<undefined>(void 0, ty)).toEqual({value: void 0}); expect(validate<undefined>({}, ty)).toEqual(null); expect(validate<undefined>([], ty)).toEqual(null); expect(validate<undefined>(3, ty)).toEqual(null); expect(validate<undefined>(BigInt(7), ty)).toEqual(null); expect(validate<undefined>('XB', ty)).toEqual(null); expect(validate<undefined>(true, ty)).toEqual(null); } { const rhs: TypeAssertion = { name: 'BarA', typeName: 'BarA', kind: 'primitive-value', value: 3, }; // const ty = getType(schema, 'BarA'); for (const ty of [getType(deserialize(serialize(schema)), 'BarA'), getType(schema, 'BarA')]) { expect(ty).toEqual(rhs); expect(validate<number>(0, ty)).toEqual(null); expect(validate<number>(1, ty)).toEqual(null); expect(validate<number>(1.1, ty)).toEqual(null); expect(validate<number>(BigInt(0), ty)).toEqual(null); expect(validate<number>(BigInt(1), ty)).toEqual(null); expect(validate<number>('', ty)).toEqual(null); expect(validate<number>('1', ty)).toEqual(null); expect(validate<number>(false, ty)).toEqual(null); expect(validate<number>(true, ty)).toEqual(null); expect(validate<number>(null, ty)).toEqual(null); expect(validate<number>(void 0, ty)).toEqual(null); expect(validate<number>({}, ty)).toEqual(null); expect(validate<number>([], ty)).toEqual(null); expect(validate<number>(3, ty)).toEqual({value: 3}); expect(validate<number>(BigInt(7), ty)).toEqual(null); expect(validate<number>('XB', ty)).toEqual(null); expect(validate<number>(true, ty)).toEqual(null); } } { const rhs: TypeAssertion = { name: 'BarB', typeName: 'BarB', kind: 'primitive-value', value: BigInt(7), }; // const ty = getType(schema, 'BarB'); for (const ty of [getType(deserialize(serialize(schema)), 'BarB'), getType(schema, 'BarB')]) { expect(ty).toEqual(rhs); expect(validate<BigInt>(0, ty)).toEqual(null); expect(validate<BigInt>(1, ty)).toEqual(null); expect(validate<BigInt>(1.1, ty)).toEqual(null); expect(validate<BigInt>(BigInt(0), ty)).toEqual(null); expect(validate<BigInt>(BigInt(1), ty)).toEqual(null); expect(validate<BigInt>('', ty)).toEqual(null); expect(validate<BigInt>('1', ty)).toEqual(null); expect(validate<BigInt>(false, ty)).toEqual(null); expect(validate<BigInt>(true, ty)).toEqual(null); expect(validate<BigInt>(null, ty)).toEqual(null); expect(validate<BigInt>(void 0, ty)).toEqual(null); expect(validate<BigInt>({}, ty)).toEqual(null); expect(validate<BigInt>([], ty)).toEqual(null); expect(validate<BigInt>(3, ty)).toEqual(null); expect(validate<BigInt>(BigInt(7), ty)).toEqual({value: BigInt(7)}); expect(validate<BigInt>('XB', ty)).toEqual(null); expect(validate<BigInt>(true, ty)).toEqual(null); } } { const rhs: TypeAssertion = { name: 'BarC', typeName: 'BarC', kind: 'primitive-value', value: 'XB', }; // const ty = getType(schema, 'BarC'); for (const ty of [getType(deserialize(serialize(schema)), 'BarC'), getType(schema, 'BarC')]) { expect(ty).toEqual(rhs); expect(validate<string>(0, ty)).toEqual(null); expect(validate<string>(1, ty)).toEqual(null); expect(validate<string>(1.1, ty)).toEqual(null); expect(validate<string>(BigInt(0), ty)).toEqual(null); expect(validate<string>(BigInt(1), ty)).toEqual(null); expect(validate<string>('', ty)).toEqual(null); expect(validate<string>('1', ty)).toEqual(null); expect(validate<string>(false, ty)).toEqual(null); expect(validate<string>(true, ty)).toEqual(null); expect(validate<string>(null, ty)).toEqual(null); expect(validate<string>(void 0, ty)).toEqual(null); expect(validate<string>({}, ty)).toEqual(null); expect(validate<string>([], ty)).toEqual(null); expect(validate<string>(3, ty)).toEqual(null); expect(validate<string>(BigInt(7), ty)).toEqual(null); expect(validate<string>('XB', ty)).toEqual({value: 'XB'}); expect(validate<string>(true, ty)).toEqual(null); } } { const rhs: TypeAssertion = { name: 'BarD', typeName: 'BarD', kind: 'primitive-value', value: true, }; // const ty = getType(schema, 'BarD'); for (const ty of [getType(deserialize(serialize(schema)), 'BarD'), getType(schema, 'BarD')]) { expect(ty).toEqual(rhs); expect(validate<boolean>(0, ty)).toEqual(null); expect(validate<boolean>(1, ty)).toEqual(null); expect(validate<boolean>(1.1, ty)).toEqual(null); expect(validate<boolean>(BigInt(0), ty)).toEqual(null); expect(validate<boolean>(BigInt(1), ty)).toEqual(null); expect(validate<boolean>('', ty)).toEqual(null); expect(validate<boolean>('1', ty)).toEqual(null); expect(validate<boolean>(false, ty)).toEqual(null); expect(validate<boolean>(true, ty)).toEqual({value: true}); expect(validate<boolean>(null, ty)).toEqual(null); expect(validate<boolean>(void 0, ty)).toEqual(null); expect(validate<boolean>({}, ty)).toEqual(null); expect(validate<boolean>([], ty)).toEqual(null); expect(validate<boolean>(3, ty)).toEqual(null); expect(validate<boolean>(BigInt(7), ty)).toEqual(null); expect(validate<boolean>('XB', ty)).toEqual(null); expect(validate<boolean>(true, ty)).toEqual({value: true}); } } for (const ty of [getType(deserialize(serialize(schema)), 'BazA'), getType(schema, 'BazA')]) { const rhs: TypeAssertion = { name: 'BazA', typeName: 'BazA', kind: 'primitive', primitiveName: 'integer', }; expect(ty).toEqual(rhs); expect(validate<number>(0, ty)).toEqual({value: 0}); expect(validate<number>(1, ty)).toEqual({value: 1}); expect(validate<number>(1.1, ty)).toEqual(null); expect(validate<number>(BigInt(0), ty)).toEqual(null); expect(validate<number>(BigInt(1), ty)).toEqual(null); expect(validate<number>('', ty)).toEqual(null); expect(validate<number>('1', ty)).toEqual(null); expect(validate<number>(false, ty)).toEqual(null); expect(validate<number>(true, ty)).toEqual(null); expect(validate<number>(null, ty)).toEqual(null); expect(validate<number>(void 0, ty)).toEqual(null); expect(validate<number>({}, ty)).toEqual(null); expect(validate<number>([], ty)).toEqual(null); expect(validate<number>(3, ty)).toEqual({value: 3}); expect(validate<number>(BigInt(7), ty)).toEqual(null); expect(validate<number>('XB', ty)).toEqual(null); expect(validate<number>(true, ty)).toEqual(null); } }); it("compiler-array-of-primitive", function() { const schemas = [compile(` type FooA = number[]; type FooB = bigint[]; type FooC = string[]; type FooD = boolean[]; type FooE = null[]; type FooF = undefined[]; type BarA = 3[]; type BarB = 7n[]; type BarC = 'XB'[]; type BarD = true[]; type BazA = integer[]; `), compile(` type FooA = Array<number>; type FooB = Array<bigint>; type FooC = Array<string>; type FooD = Array<boolean>; type FooE = Array<null>; type FooF = Array<undefined>; type BarA = Array<3>; type BarB = Array<7n>; type BarC = Array<'XB'>; type BarD = Array<true>; type BazA = Array<integer>; `)]; for (const schema of schemas) { { expect(Array.from(schema.keys())).toEqual([ 'FooA', 'FooB', 'FooC', 'FooD', 'FooE', 'FooF', 'BarA', 'BarB', 'BarC', 'BarD', 'BazA', ]); } { const rhs: TypeAssertion = { name: 'FooA', typeName: 'FooA', kind: 'repeated', min: null, max: null, repeated: { kind: 'primitive', primitiveName: 'number', }, }; // const ty = getType(schema, 'FooA'); for (const ty of [getType(deserialize(serialize(schema)), 'FooA'), getType(schema, 'FooA')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual(null); expect(validate<any>(1, ty)).toEqual(null); expect(validate<any>(BigInt(0), ty)).toEqual(null); expect(validate<any>(BigInt(1), ty)).toEqual(null); expect(validate<any>('', ty)).toEqual(null); expect(validate<any>('1', ty)).toEqual(null); expect(validate<any>(false, ty)).toEqual(null); expect(validate<any>(true, ty)).toEqual(null); expect(validate<any>(null, ty)).toEqual(null); expect(validate<any>(void 0, ty)).toEqual(null); expect(validate<any>({}, ty)).toEqual(null); expect(validate<any>([], ty)).toEqual({value: []}); expect(validate<any>([0], ty)).toEqual({value: [0]}); expect(validate<any>([1.1], ty)).toEqual({value: [1.1]}); expect(validate<any>([BigInt(0)], ty)).toEqual(null); expect(validate<any>([''], ty)).toEqual(null); expect(validate<any>([false], ty)).toEqual(null); expect(validate<any>([null], ty)).toEqual(null); expect(validate<any>([void 0], ty)).toEqual(null); expect(validate<any>([3], ty)).toEqual({value: [3]}); expect(validate<any>([BigInt(7)], ty)).toEqual(null); expect(validate<any>(['XB'], ty)).toEqual(null); expect(validate<any>([true], ty)).toEqual(null); } } { const rhs: TypeAssertion = { name: 'FooB', typeName: 'FooB', kind: 'repeated', min: null, max: null, repeated: { kind: 'primitive', primitiveName: 'bigint', }, }; // const ty = getType(schema, 'FooB'); for (const ty of [getType(deserialize(serialize(schema)), 'FooB'), getType(schema, 'FooB')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual(null); expect(validate<any>(1, ty)).toEqual(null); expect(validate<any>(BigInt(0), ty)).toEqual(null); expect(validate<any>(BigInt(1), ty)).toEqual(null); expect(validate<any>('', ty)).toEqual(null); expect(validate<any>('1', ty)).toEqual(null); expect(validate<any>(false, ty)).toEqual(null); expect(validate<any>(true, ty)).toEqual(null); expect(validate<any>(null, ty)).toEqual(null); expect(validate<any>(void 0, ty)).toEqual(null); expect(validate<any>({}, ty)).toEqual(null); expect(validate<any>([], ty)).toEqual({value: []}); expect(validate<any>([0], ty)).toEqual(null); expect(validate<any>([1.1], ty)).toEqual(null); expect(validate<any>([BigInt(0)], ty)).toEqual({value: [BigInt(0)]}); expect(validate<any>([''], ty)).toEqual(null); expect(validate<any>([false], ty)).toEqual(null); expect(validate<any>([null], ty)).toEqual(null); expect(validate<any>([void 0], ty)).toEqual(null); expect(validate<any>([3], ty)).toEqual(null); expect(validate<any>([BigInt(7)], ty)).toEqual({value: [BigInt(7)]}); expect(validate<any>(['XB'], ty)).toEqual(null); expect(validate<any>([true], ty)).toEqual(null); } } { const rhs: TypeAssertion = { name: 'FooC', typeName: 'FooC', kind: 'repeated', min: null, max: null, repeated: { kind: 'primitive', primitiveName: 'string', }, }; // const ty = getType(schema, 'FooC'); for (const ty of [getType(deserialize(serialize(schema)), 'FooC'), getType(schema, 'FooC')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual(null); expect(validate<any>(1, ty)).toEqual(null); expect(validate<any>(BigInt(0), ty)).toEqual(null); expect(validate<any>(BigInt(1), ty)).toEqual(null); expect(validate<any>('', ty)).toEqual(null); expect(validate<any>('1', ty)).toEqual(null); expect(validate<any>(false, ty)).toEqual(null); expect(validate<any>(true, ty)).toEqual(null); expect(validate<any>(null, ty)).toEqual(null); expect(validate<any>(void 0, ty)).toEqual(null); expect(validate<any>({}, ty)).toEqual(null); expect(validate<any>([], ty)).toEqual({value: []}); expect(validate<any>([0], ty)).toEqual(null); expect(validate<any>([1.1], ty)).toEqual(null); expect(validate<any>([BigInt(0)], ty)).toEqual(null); expect(validate<any>([''], ty)).toEqual({value: ['']}); expect(validate<any>([false], ty)).toEqual(null); expect(validate<any>([null], ty)).toEqual(null); expect(validate<any>([void 0], ty)).toEqual(null); expect(validate<any>([3], ty)).toEqual(null); expect(validate<any>([BigInt(7)], ty)).toEqual(null); expect(validate<any>(['XB'], ty)).toEqual({value: ['XB']}); expect(validate<any>([true], ty)).toEqual(null); } } { const rhs: TypeAssertion = { name: 'FooD', typeName: 'FooD', kind: 'repeated', min: null, max: null, repeated: { kind: 'primitive', primitiveName: 'boolean', }, }; // const ty = getType(schema, 'FooD'); for (const ty of [getType(deserialize(serialize(schema)), 'FooD'), getType(schema, 'FooD')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual(null); expect(validate<any>(1, ty)).toEqual(null); expect(validate<any>(BigInt(0), ty)).toEqual(null); expect(validate<any>(BigInt(1), ty)).toEqual(null); expect(validate<any>('', ty)).toEqual(null); expect(validate<any>('1', ty)).toEqual(null); expect(validate<any>(false, ty)).toEqual(null); expect(validate<any>(true, ty)).toEqual(null); expect(validate<any>(null, ty)).toEqual(null); expect(validate<any>(void 0, ty)).toEqual(null); expect(validate<any>({}, ty)).toEqual(null); expect(validate<any>([], ty)).toEqual({value: []}); expect(validate<any>([0], ty)).toEqual(null); expect(validate<any>([1.1], ty)).toEqual(null); expect(validate<any>([BigInt(0)], ty)).toEqual(null); expect(validate<any>([''], ty)).toEqual(null); expect(validate<any>([false], ty)).toEqual({value: [false]}); expect(validate<any>([null], ty)).toEqual(null); expect(validate<any>([void 0], ty)).toEqual(null); expect(validate<any>([3], ty)).toEqual(null); expect(validate<any>([BigInt(7)], ty)).toEqual(null); expect(validate<any>(['XB'], ty)).toEqual(null); expect(validate<any>([true], ty)).toEqual({value: [true]}); } } { const rhs: TypeAssertion = { name: 'FooE', typeName: 'FooE', kind: 'repeated', min: null, max: null, repeated: { kind: 'primitive', primitiveName: 'null', }, }; // const ty = getType(schema, 'FooE'); for (const ty of [getType(deserialize(serialize(schema)), 'FooE'), getType(schema, 'FooE')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual(null); expect(validate<any>(1, ty)).toEqual(null); expect(validate<any>(BigInt(0), ty)).toEqual(null); expect(validate<any>(BigInt(1), ty)).toEqual(null); expect(validate<any>('', ty)).toEqual(null); expect(validate<any>('1', ty)).toEqual(null); expect(validate<any>(false, ty)).toEqual(null); expect(validate<any>(true, ty)).toEqual(null); expect(validate<any>(null, ty)).toEqual(null); expect(validate<any>(void 0, ty)).toEqual(null); expect(validate<any>({}, ty)).toEqual(null); expect(validate<any>([], ty)).toEqual({value: []}); expect(validate<any>([0], ty)).toEqual(null); expect(validate<any>([1.1], ty)).toEqual(null); expect(validate<any>([BigInt(0)], ty)).toEqual(null); expect(validate<any>([''], ty)).toEqual(null); expect(validate<any>([false], ty)).toEqual(null); expect(validate<any>([null], ty)).toEqual({value: [null]}); expect(validate<any>([void 0], ty)).toEqual(null); expect(validate<any>([3], ty)).toEqual(null); expect(validate<any>([BigInt(7)], ty)).toEqual(null); expect(validate<any>(['XB'], ty)).toEqual(null); expect(validate<any>([true], ty)).toEqual(null); } } { const rhs: TypeAssertion = { name: 'FooF', typeName: 'FooF', kind: 'repeated', min: null, max: null, repeated: { kind: 'primitive', primitiveName: 'undefined', }, }; // const ty = getType(schema, 'FooF'); for (const ty of [getType(deserialize(serialize(schema)), 'FooF'), getType(schema, 'FooF')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual(null); expect(validate<any>(1, ty)).toEqual(null); expect(validate<any>(BigInt(0), ty)).toEqual(null); expect(validate<any>(BigInt(1), ty)).toEqual(null); expect(validate<any>('', ty)).toEqual(null); expect(validate<any>('1', ty)).toEqual(null); expect(validate<any>(false, ty)).toEqual(null); expect(validate<any>(true, ty)).toEqual(null); expect(validate<any>(null, ty)).toEqual(null); expect(validate<any>(void 0, ty)).toEqual(null); expect(validate<any>({}, ty)).toEqual(null); expect(validate<any>([], ty)).toEqual({value: []}); expect(validate<any>([0], ty)).toEqual(null); expect(validate<any>([1.1], ty)).toEqual(null); expect(validate<any>([BigInt(0)], ty)).toEqual(null); expect(validate<any>([''], ty)).toEqual(null); expect(validate<any>([false], ty)).toEqual(null); expect(validate<any>([null], ty)).toEqual(null); expect(validate<any>([void 0], ty)).toEqual({value: [void 0]}); expect(validate<any>([3], ty)).toEqual(null); expect(validate<any>([BigInt(7)], ty)).toEqual(null); expect(validate<any>(['XB'], ty)).toEqual(null); expect(validate<any>([true], ty)).toEqual(null); } } { const rhs: TypeAssertion = { name: 'BarA', typeName: 'BarA', kind: 'repeated', min: null, max: null, repeated: { kind: 'primitive-value', value: 3, }, }; // const ty = getType(schema, 'BarA'); for (const ty of [getType(deserialize(serialize(schema)), 'BarA'), getType(schema, 'BarA')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual(null); expect(validate<any>(1, ty)).toEqual(null); expect(validate<any>(BigInt(0), ty)).toEqual(null); expect(validate<any>(BigInt(1), ty)).toEqual(null); expect(validate<any>('', ty)).toEqual(null); expect(validate<any>('1', ty)).toEqual(null); expect(validate<any>(false, ty)).toEqual(null); expect(validate<any>(true, ty)).toEqual(null); expect(validate<any>(null, ty)).toEqual(null); expect(validate<any>(void 0, ty)).toEqual(null); expect(validate<any>({}, ty)).toEqual(null); expect(validate<any>([], ty)).toEqual({value: []}); expect(validate<any>([0], ty)).toEqual(null); expect(validate<any>([1.1], ty)).toEqual(null); expect(validate<any>([BigInt(0)], ty)).toEqual(null); expect(validate<any>([''], ty)).toEqual(null); expect(validate<any>([false], ty)).toEqual(null); expect(validate<any>([null], ty)).toEqual(null); expect(validate<any>([void 0], ty)).toEqual(null); expect(validate<any>([3], ty)).toEqual({value: [3]}); expect(validate<any>([BigInt(7)], ty)).toEqual(null); expect(validate<any>(['XB'], ty)).toEqual(null); expect(validate<any>([true], ty)).toEqual(null); } } { const rhs: TypeAssertion = { name: 'BarB', typeName: 'BarB', kind: 'repeated', min: null, max: null, repeated: { kind: 'primitive-value', value: BigInt(7), }, }; // const ty = getType(schema, 'BarB'); for (const ty of [getType(deserialize(serialize(schema)), 'BarB'), getType(schema, 'BarB')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual(null); expect(validate<any>(1, ty)).toEqual(null); expect(validate<any>(BigInt(0), ty)).toEqual(null); expect(validate<any>(BigInt(1), ty)).toEqual(null); expect(validate<any>('', ty)).toEqual(null); expect(validate<any>('1', ty)).toEqual(null); expect(validate<any>(false, ty)).toEqual(null); expect(validate<any>(true, ty)).toEqual(null); expect(validate<any>(null, ty)).toEqual(null); expect(validate<any>(void 0, ty)).toEqual(null); expect(validate<any>({}, ty)).toEqual(null); expect(validate<any>([], ty)).toEqual({value: []}); expect(validate<any>([0], ty)).toEqual(null); expect(validate<any>([1.1], ty)).toEqual(null); expect(validate<any>([BigInt(0)], ty)).toEqual(null); expect(validate<any>([''], ty)).toEqual(null); expect(validate<any>([false], ty)).toEqual(null); expect(validate<any>([null], ty)).toEqual(null); expect(validate<any>([void 0], ty)).toEqual(null); expect(validate<any>([3], ty)).toEqual(null); expect(validate<any>([BigInt(7)], ty)).toEqual({value: [BigInt(7)]}); expect(validate<any>(['XB'], ty)).toEqual(null); expect(validate<any>([true], ty)).toEqual(null); } } { const rhs: TypeAssertion = { name: 'BarC', typeName: 'BarC', kind: 'repeated', min: null, max: null, repeated: { kind: 'primitive-value', value: 'XB', }, }; // const ty = getType(schema, 'BarC'); for (const ty of [getType(deserialize(serialize(schema)), 'BarC'), getType(schema, 'BarC')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual(null); expect(validate<any>(1, ty)).toEqual(null); expect(validate<any>(BigInt(0), ty)).toEqual(null); expect(validate<any>(BigInt(1), ty)).toEqual(null); expect(validate<any>('', ty)).toEqual(null); expect(validate<any>('1', ty)).toEqual(null); expect(validate<any>(false, ty)).toEqual(null); expect(validate<any>(true, ty)).toEqual(null); expect(validate<any>(null, ty)).toEqual(null); expect(validate<any>(void 0, ty)).toEqual(null); expect(validate<any>({}, ty)).toEqual(null); expect(validate<any>([], ty)).toEqual({value: []}); expect(validate<any>([0], ty)).toEqual(null); expect(validate<any>([1.1], ty)).toEqual(null); expect(validate<any>([BigInt(0)], ty)).toEqual(null); expect(validate<any>([''], ty)).toEqual(null); expect(validate<any>([false], ty)).toEqual(null); expect(validate<any>([null], ty)).toEqual(null); expect(validate<any>([void 0], ty)).toEqual(null); expect(validate<any>([3], ty)).toEqual(null); expect(validate<any>([BigInt(7)], ty)).toEqual(null); expect(validate<any>(['XB'], ty)).toEqual({value: ['XB']}); expect(validate<any>([true], ty)).toEqual(null); } } { const rhs: TypeAssertion = { name: 'BarD', typeName: 'BarD', kind: 'repeated', min: null, max: null, repeated: { kind: 'primitive-value', value: true, }, }; // const ty = getType(schema, 'BarD'); for (const ty of [getType(deserialize(serialize(schema)), 'BarD'), getType(schema, 'BarD')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual(null); expect(validate<any>(1, ty)).toEqual(null); expect(validate<any>(BigInt(0), ty)).toEqual(null); expect(validate<any>(BigInt(1), ty)).toEqual(null); expect(validate<any>('', ty)).toEqual(null); expect(validate<any>('1', ty)).toEqual(null); expect(validate<any>(false, ty)).toEqual(null); expect(validate<any>(true, ty)).toEqual(null); expect(validate<any>(null, ty)).toEqual(null); expect(validate<any>(void 0, ty)).toEqual(null); expect(validate<any>({}, ty)).toEqual(null); expect(validate<any>([], ty)).toEqual({value: []}); expect(validate<any>([0], ty)).toEqual(null); expect(validate<any>([1.1], ty)).toEqual(null); expect(validate<any>([BigInt(0)], ty)).toEqual(null); expect(validate<any>([''], ty)).toEqual(null); expect(validate<any>([false], ty)).toEqual(null); expect(validate<any>([null], ty)).toEqual(null); expect(validate<any>([void 0], ty)).toEqual(null); expect(validate<any>([3], ty)).toEqual(null); expect(validate<any>([BigInt(7)], ty)).toEqual(null); expect(validate<any>(['XB'], ty)).toEqual(null); expect(validate<any>([true], ty)).toEqual({value: [true]}); } } { const rhs: TypeAssertion = { name: 'BazA', typeName: 'BazA', kind: 'repeated', min: null, max: null, repeated: { kind: 'primitive', primitiveName: 'integer', }, }; // const ty = getType(schema, 'BazA'); for (const ty of [getType(deserialize(serialize(schema)), 'BazA'), getType(schema, 'BazA')]) { expect(ty).toEqual(rhs); expect(validate<any>(0, ty)).toEqual(null); expect(validate<any>(1, ty)).toEqual(null); expect(validate<any>(1.1, ty)).toEqual(null); expect(validate<any>(BigInt(0), ty)).toEqual(null); expect(validate<any>(BigInt(1), ty)).toEqual(null); expect(validate<any>('', ty)).toEqual(null); expect(validate<any>('1', ty)).toEqual(null); expect(validate<any>(false, ty)).toEqual(null); expect(validate<any>(true, ty)).toEqual(null); expect(validate<any>(null, ty)).toEqual(null); expect(validate<any>(void 0, ty)).toEqual(null); expect(validate<any>({}, ty)).toEqual(null); expect(validate<any>([], ty)).toEqual({value: []}); expect(validate<any>([0], ty)).toEqual({value: [0]}); expect(validate<any>([1.1], ty)).toEqual(null); expect(validate<any>([BigInt(0)], ty)).toEqual(null); expect(validate<any>([''], ty)).toEqual(null); expect(validate<any>([false], ty)).toEqual(null); expect(validate<any>([null], ty)).toEqual(null); expect(validate<any>([void 0], ty)).toEqual(null); expect(validate<any>([3], ty)).toEqual({value: [3]}); expect(validate<any>([BigInt(7)], ty)).toEqual(null); expect(validate<any>(['XB'], ty)).toEqual(null); expect(validate<any>([true], ty)).toEqual(null); } } } }); });
the_stack
import BigNumber from 'bignumber.js'; import { getSolo } from '../helpers/Solo'; import { TestSolo } from '../modules/TestSolo'; import { fastForward, mineAvgBlock, resetEVM, snapshot } from '../helpers/EVM'; import { setupMarkets } from '../helpers/SoloHelpers'; import { toBytes } from '../../src/lib/BytesHelper'; import { INTEGERS } from '../../src/lib/Constants'; import { expectThrow } from '../../src/lib/Expect'; import { address, AmountDenomination, AmountReference, Trade, } from '../../src/types'; let solo: TestSolo; let accounts: address[]; let snapshotId: string; let admin: address; let owner1: address; let owner2: address; const accountNumber1 = INTEGERS.ZERO; const accountNumber2 = INTEGERS.ONE; const heldMarket = INTEGERS.ZERO; const owedMarket = INTEGERS.ONE; const collateralMarket = new BigNumber(2); const par = new BigNumber(10000); const zero = new BigNumber(0); const premium = new BigNumber('1.05'); const defaultPrice = new BigNumber('1e40'); let defaultGlob: Trade; let heldGlob: Trade; describe('FinalSettlement', () => { beforeAll(async () => { const r = await getSolo(); solo = r.solo; accounts = r.accounts; admin = accounts[0]; owner1 = accounts[2]; owner2 = accounts[3]; defaultGlob = { primaryAccountOwner: owner1, primaryAccountId: accountNumber1, otherAccountOwner: owner2, otherAccountId: accountNumber2, inputMarketId: owedMarket, outputMarketId: heldMarket, autoTrader: solo.contracts.finalSettlement.options.address, amount: { value: zero, denomination: AmountDenomination.Principal, reference: AmountReference.Target, }, data: toBytes(owedMarket), }; heldGlob = { primaryAccountOwner: owner1, primaryAccountId: accountNumber1, otherAccountOwner: owner2, otherAccountId: accountNumber2, inputMarketId: heldMarket, outputMarketId: owedMarket, autoTrader: solo.contracts.finalSettlement.options.address, amount: { value: zero, denomination: AmountDenomination.Principal, reference: AmountReference.Target, }, data: toBytes(owedMarket), }; await resetEVM(); await setupMarkets(solo, accounts); await Promise.all([ solo.testing.setAccountBalance(owner2, accountNumber2, owedMarket, par.times(-1)), solo.testing.setAccountBalance(owner2, accountNumber2, heldMarket, par.times(2)), solo.testing.setAccountBalance(owner1, accountNumber1, owedMarket, par), solo.testing.setAccountBalance(owner2, accountNumber2, collateralMarket, par.times(4)), ]); snapshotId = await snapshot(); }); beforeEach(async () => { await resetEVM(snapshotId); }); describe('#getRampTime', () => { it('Succeeds', async () => { expect(await solo.finalSettlement.getRampTime()).toEqual(new BigNumber(60 * 60 * 24 * 28)); }); }); describe('#initialize', () => { it('Succeeds', async () => { await solo.finalSettlement.initialize(); const startTime: BigNumber = await solo.finalSettlement.getStartTime(); // Expect the start time to equal the block timestamp. const { timestamp } = await solo.web3.eth.getBlock(await solo.web3.eth.getBlockNumber()); expect(startTime).toEqual(new BigNumber(timestamp)); }); it('Fails if already initialized', async () => { await solo.finalSettlement.initialize(); await expectThrow( solo.finalSettlement.initialize(), 'FinalSettlement: Already initialized', ); }); it('Fails if not a global operator', async () => { await solo.admin.setGlobalOperator( solo.contracts.finalSettlement.options.address, false, { from: admin }, ); await expectThrow( solo.finalSettlement.initialize(), 'FinalSettlement: Not a global operator', ); }); }); describe('settle account (heldAmount)', () => { beforeEach(async () => { await solo.finalSettlement.initialize(); await solo.testing.setAccountBalance(owner2, accountNumber2, heldMarket, par); await fastForward(60 * 60 * 24 * 28); }); it('Succeeds in settling', async () => { const txResult = await expectSettlementOkay(heldGlob); const [ held1, owed1, held2, owed2, ] = await Promise.all([ solo.getters.getAccountPar(owner1, accountNumber1, heldMarket), solo.getters.getAccountPar(owner1, accountNumber1, owedMarket), solo.getters.getAccountPar(owner2, accountNumber2, heldMarket), solo.getters.getAccountPar(owner2, accountNumber2, owedMarket), ]); expect(owed1).toEqual(par.minus(par.div(premium)).integerValue(BigNumber.ROUND_DOWN)); expect(owed2).toEqual(owed1.times(-1)); expect(held1).toEqual(par); expect(held2).toEqual(zero); const logs = solo.logs.parseLogs(txResult, { skipOperationLogs: true }); expect(logs.length).toEqual(1); const settleLog = logs[0]; expect(settleLog.name).toEqual('Settlement'); expect(settleLog.args.makerAddress).toEqual(owner2); expect(settleLog.args.takerAddress).toEqual(owner1); expect(settleLog.args.heldMarketId).toEqual(heldMarket); expect(settleLog.args.owedMarketId).toEqual(owedMarket); expect(settleLog.args.heldWei).toEqual(par); expect(settleLog.args.owedWei).toEqual(par.div(premium).integerValue(BigNumber.ROUND_UP)); console.log(`\tFinalSettlement (held) gas used: ${txResult.gasUsed}`); }); it('Succeeds in settling part of a position', async () => { await expectSettlementOkay({ ...heldGlob, amount: { value: par.div(2), denomination: AmountDenomination.Actual, reference: AmountReference.Target, }, }); const [ held1, owed1, held2, owed2, ] = await Promise.all([ solo.getters.getAccountPar(owner1, accountNumber1, heldMarket), solo.getters.getAccountPar(owner1, accountNumber1, owedMarket), solo.getters.getAccountPar(owner2, accountNumber2, heldMarket), solo.getters.getAccountPar(owner2, accountNumber2, owedMarket), ]); expect(owed1).toEqual(par.minus(par.div(premium).div(2)).integerValue(BigNumber.ROUND_DOWN)); expect(owed2).toEqual(owed1.times(-1)); expect(held1).toEqual(par.div(2)); expect(held2).toEqual(par.minus(held1)); }); it('Succeeds in settling including premiums', async () => { const owedPremium = new BigNumber('0.5'); const heldPremium = new BigNumber('1.0'); const adjustedPremium = premium.minus(1).times( owedPremium.plus(1), ).times( heldPremium.plus(1), ).plus(1); await Promise.all([ solo.admin.setSpreadPremium(owedMarket, owedPremium, { from: admin }), solo.admin.setSpreadPremium(heldMarket, heldPremium, { from: admin }), ]); await expectSettlementOkay(heldGlob); const [ held1, owed1, held2, owed2, ] = await Promise.all([ solo.getters.getAccountPar(owner1, accountNumber1, heldMarket), solo.getters.getAccountPar(owner1, accountNumber1, owedMarket), solo.getters.getAccountPar(owner2, accountNumber2, heldMarket), solo.getters.getAccountPar(owner2, accountNumber2, owedMarket), ]); expect(owed1).toEqual(par.minus(par.div(adjustedPremium)).integerValue(BigNumber.ROUND_DOWN)); expect(owed2).toEqual(owed1.times(-1)); expect(held1).toEqual(par); expect(held2).toEqual(zero); }); it('Succeeds for zero inputMarket', async () => { const getAllBalances = [ solo.getters.getAccountPar(owner1, accountNumber1, heldMarket), solo.getters.getAccountPar(owner1, accountNumber1, owedMarket), solo.getters.getAccountPar(owner2, accountNumber2, heldMarket), solo.getters.getAccountPar(owner2, accountNumber2, owedMarket), ]; const start = await Promise.all(getAllBalances); await solo.testing.setAccountBalance(owner2, accountNumber2, heldMarket, zero); await expectSettlementOkay(heldGlob, {}, false); const end = await Promise.all(getAllBalances); expect(start).toEqual(end); }); it('Fails for negative inputMarket', async () => { await solo.testing.setAccountBalance(owner2, accountNumber2, heldMarket, par.times(-1)); await expectSettlementRevert( heldGlob, 'FinalSettlement: inputMarket mismatch', ); }); it('Fails for overusing collateral', async () => { await expectSettlementRevert( { ...heldGlob, amount: { value: par.times(-1), denomination: AmountDenomination.Actual, reference: AmountReference.Target, }, }, 'FinalSettlement: Collateral cannot be overused', ); }); it('Fails for increasing the heldAmount', async () => { await expectSettlementRevert( { ...heldGlob, amount: { value: par.times(4), denomination: AmountDenomination.Actual, reference: AmountReference.Target, }, }, 'FinalSettlement: inputMarket mismatch', ); }); it('Fails if not initialized', async () => { await resetEVM(snapshotId); await expectSettlementRevert( heldGlob, 'FinalSettlement: Contract must be initialized', ); }); it('Fails for invalid trade data', async () => { await expectSettlementRevert( { ...heldGlob, data: [], }, // No message, abi.decode reverts. ); }); it('Fails for zero owedMarket', async () => { await solo.testing.setAccountBalance(owner2, accountNumber2, owedMarket, zero); await expectSettlementRevert( heldGlob, 'FinalSettlement: Borrows must be negative', ); }); it('Fails for positive owedMarket', async () => { await solo.testing.setAccountBalance(owner2, accountNumber2, owedMarket, par); await expectSettlementRevert( heldGlob, 'FinalSettlement: Borrows must be negative', ); }); it('Fails for over-repaying the borrow', async () => { await solo.testing.setAccountBalance(owner2, accountNumber2, heldMarket, par.times(2)); await expectSettlementRevert( heldGlob, 'FinalSettlement: outputMarket too small', ); }); }); describe('settle account (owedAmount)', () => { beforeEach(async () => { await solo.finalSettlement.initialize(); await fastForward(60 * 60 * 24 * 28); }); it('Succeeds in settling', async () => { const txResult = await expectSettlementOkay({}); const [ held1, owed1, held2, owed2, ] = await Promise.all([ solo.getters.getAccountPar(owner1, accountNumber1, heldMarket), solo.getters.getAccountPar(owner1, accountNumber1, owedMarket), solo.getters.getAccountPar(owner2, accountNumber2, heldMarket), solo.getters.getAccountPar(owner2, accountNumber2, owedMarket), ]); expect(owed1).toEqual(zero); expect(owed2).toEqual(zero); expect(held1).toEqual(par.times(premium)); expect(held2).toEqual(par.times(2).minus(held1)); const logs = solo.logs.parseLogs(txResult, { skipOperationLogs: true }); expect(logs.length).toEqual(1); const settleLog = logs[0]; expect(settleLog.name).toEqual('Settlement'); expect(settleLog.args.makerAddress).toEqual(owner2); expect(settleLog.args.takerAddress).toEqual(owner1); expect(settleLog.args.heldMarketId).toEqual(heldMarket); expect(settleLog.args.owedMarketId).toEqual(owedMarket); expect(settleLog.args.heldWei).toEqual(par.times(premium)); expect(settleLog.args.owedWei).toEqual(par); console.log(`\tFinalSettlement (owed) gas used: ${txResult.gasUsed}`); }); it('Succeeds in settling part of a position', async () => { await expectSettlementOkay({ amount: { value: par.div(-2), denomination: AmountDenomination.Actual, reference: AmountReference.Target, }, }); const [ held1, owed1, held2, owed2, ] = await Promise.all([ solo.getters.getAccountPar(owner1, accountNumber1, heldMarket), solo.getters.getAccountPar(owner1, accountNumber1, owedMarket), solo.getters.getAccountPar(owner2, accountNumber2, heldMarket), solo.getters.getAccountPar(owner2, accountNumber2, owedMarket), ]); expect(owed1).toEqual(par.div(2)); expect(owed2).toEqual(par.div(-2)); expect(held1).toEqual(par.times(premium).div(2)); expect(held2).toEqual(par.times(2).minus(held1)); }); it('Succeeds in settling including premiums', async () => { const owedPremium = new BigNumber('0.5'); const heldPremium = new BigNumber('1.0'); const adjustedPremium = premium.minus(1).times( owedPremium.plus(1), ).times( heldPremium.plus(1), ).plus(1); await Promise.all([ solo.admin.setSpreadPremium(owedMarket, owedPremium, { from: admin }), solo.admin.setSpreadPremium(heldMarket, heldPremium, { from: admin }), ]); await expectSettlementOkay({}); const [ held1, owed1, held2, owed2, ] = await Promise.all([ solo.getters.getAccountPar(owner1, accountNumber1, heldMarket), solo.getters.getAccountPar(owner1, accountNumber1, owedMarket), solo.getters.getAccountPar(owner2, accountNumber2, heldMarket), solo.getters.getAccountPar(owner2, accountNumber2, owedMarket), ]); expect(owed1).toEqual(zero); expect(owed2).toEqual(zero); expect(held1).toEqual(par.times(adjustedPremium)); expect(held2).toEqual(par.times(2).minus(held1)); }); it('Succeeds for zero inputMarket', async () => { const getAllBalances = [ solo.getters.getAccountPar(owner1, accountNumber1, heldMarket), solo.getters.getAccountPar(owner1, accountNumber1, owedMarket), solo.getters.getAccountPar(owner2, accountNumber2, heldMarket), solo.getters.getAccountPar(owner2, accountNumber2, owedMarket), ]; const start = await Promise.all(getAllBalances); await solo.testing.setAccountBalance(owner2, accountNumber2, owedMarket, zero); await expectSettlementOkay({}, {}, false); const end = await Promise.all(getAllBalances); expect(start).toEqual(end); }); it('Fails for positive inputMarket', async () => { await solo.testing.setAccountBalance(owner2, accountNumber2, owedMarket, par); await expectSettlementRevert( {}, 'FinalSettlement: outputMarket mismatch', ); }); it('Fails for overpaying a borrow', async () => { await expectSettlementRevert( { amount: { value: par, denomination: AmountDenomination.Actual, reference: AmountReference.Target, }, }, 'FinalSettlement: Borrows cannot be overpaid', ); }); it('Fails for increasing a borrow', async () => { await expectSettlementRevert( { amount: { value: par.times(-2), denomination: AmountDenomination.Actual, reference: AmountReference.Target, }, }, 'FinalSettlement: outputMarket mismatch', ); }); it('Fails if not initialized', async () => { await resetEVM(snapshotId); await expectSettlementRevert( {}, 'FinalSettlement: Contract must be initialized', ); }); it('Fails for invalid trade data', async () => { await expectSettlementRevert( { data: [] }, // No message, abi.decode reverts. ); }); it('Fails for zero collateral', async () => { await solo.testing.setAccountBalance(owner2, accountNumber2, heldMarket, zero); await expectSettlementRevert( {}, 'FinalSettlement: Collateral must be positive', ); }); it('Fails for negative collateral', async () => { await solo.testing.setAccountBalance(owner2, accountNumber2, heldMarket, par.times(-1)); await expectSettlementRevert( {}, 'FinalSettlement: Collateral must be positive', ); }); it('Fails for overtaking collateral', async () => { await solo.testing.setAccountBalance(owner2, accountNumber2, heldMarket, par.div(2)); await expectSettlementRevert( {}, 'FinalSettlement: outputMarket too small', ); }); }); describe('#getSpreadAdjustedPrices', () => { it('Succeeds at initialization', async () => { await solo.finalSettlement.initialize(); const { timestamp } = await solo.web3.eth.getBlock(await solo.web3.eth.getBlockNumber()); const prices = await solo.finalSettlement.getPrices( heldMarket, owedMarket, new BigNumber(timestamp), ); expect(prices.owedPrice.eq(defaultPrice)).toEqual(true); expect(prices.heldPrice).toEqual(defaultPrice); }); it('Succeeds when recently initialized', async () => { await solo.finalSettlement.initialize(); const { timestamp } = await solo.web3.eth.getBlock(await solo.web3.eth.getBlockNumber()); await mineAvgBlock(); const prices = await solo.finalSettlement.getPrices( heldMarket, owedMarket, new BigNumber(timestamp + 60 * 60), // 1 hour later ); expect(prices.owedPrice.lt(defaultPrice.times(premium))).toEqual(true); expect(prices.owedPrice.gt(defaultPrice)).toEqual(true); expect(prices.heldPrice).toEqual(defaultPrice); }); it('Succeeds when initialized a long time ago', async () => { await solo.finalSettlement.initialize(); const { timestamp } = await solo.web3.eth.getBlock(await solo.web3.eth.getBlockNumber()); await mineAvgBlock(); // Expect maximum spread after 28 days. const prices1 = await solo.finalSettlement.getPrices( heldMarket, owedMarket, new BigNumber(timestamp + 60 * 60 * 24 * 28), ); expect(prices1.owedPrice).toEqual(defaultPrice.times(premium)); expect(prices1.heldPrice).toEqual(defaultPrice); // Expect maximum spread after a year. const prices2 = await solo.finalSettlement.getPrices( heldMarket, owedMarket, new BigNumber(timestamp + 60 * 60 * 24 * 365), ); expect(prices2).toEqual(prices1); }); it('Fails when not yet initialized', async () => { await expectThrow( solo.finalSettlement.getPrices( heldMarket, owedMarket, new BigNumber(10), ), 'FinalSettlement: Not initialized', ); }); }); describe('accountOperation#finalSettlement', () => { beforeEach(async () => { await solo.finalSettlement.initialize(); await fastForward(60 * 60 * 24 * 28); }); it('Succeeds', async () => { await solo.operation.initiate().finalSettlement({ liquidMarketId: owedMarket, payoutMarketId: heldMarket, primaryAccountOwner: owner1, primaryAccountId: accountNumber1, liquidAccountOwner: owner2, liquidAccountId: accountNumber2, amount: { value: INTEGERS.ZERO, denomination: AmountDenomination.Principal, reference: AmountReference.Target, }, }).commit({ from: owner1 }); const [ held1, owed1, held2, owed2, ] = await Promise.all([ solo.getters.getAccountPar(owner1, accountNumber1, heldMarket), solo.getters.getAccountPar(owner1, accountNumber1, owedMarket), solo.getters.getAccountPar(owner2, accountNumber2, heldMarket), solo.getters.getAccountPar(owner2, accountNumber2, owedMarket), ]); expect(owed1).toEqual(zero); expect(owed2).toEqual(zero); expect(held1).toEqual(par.times(premium)); expect(held2).toEqual(par.times(2).minus(held1)); }); }); }); // ============ Helper Functions ============ async function expectSettlementOkay( glob: Object, options?: Object, expectLogs: boolean = true, ) { const combinedGlob = { ...defaultGlob, ...glob }; const txResult = await solo.operation .initiate() .trade(combinedGlob) .commit({ ...options, from: owner1 }); if (expectLogs) { const logs = solo.logs.parseLogs(txResult, { skipOperationLogs: true }); expect(logs.length).toEqual(1); expect(logs[0].name).toEqual('Settlement'); } return txResult; } async function expectSettlementRevert( glob: Object, reason?: string, options?: Object, ) { await expectThrow(expectSettlementOkay(glob, options), reason); }
the_stack
import { BaseResource, CloudError, AzureServiceClientOptions } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export { BaseResource, CloudError }; /** * The object that represents the operation. */ export interface OperationDisplay { /** * Service provider: Microsoft.connectedClusters */ provider?: string; /** * Connected Cluster Resource on which the operation is performed */ resource?: string; /** * Operation type: Read, write, delete, etc. */ operation?: string; /** * Description of the operation. */ description?: string; } /** * The Connected cluster API operation */ export interface Operation { /** * Operation name: {Microsoft.Kubernetes}/{resource}/{operation} * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The object that represents the operation. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly display?: OperationDisplay; } /** * Identity for the connected cluster. */ export interface ConnectedClusterIdentity { /** * The principal id of connected cluster identity. This property will only be provided for a * system assigned identity. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly principalId?: string; /** * The tenant id associated with the connected cluster. This property will only be provided for a * system assigned identity. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly tenantId?: string; /** * The type of identity used for the connected cluster. The type 'SystemAssigned, includes a * system created identity. The type 'None' means no identity is assigned to the connected * cluster. Possible values include: 'None', 'SystemAssigned'. Default value: 'SystemAssigned'. */ type: ResourceIdentityType; } /** * Metadata pertaining to creation and last modification of the resource. */ export interface SystemData { /** * The identity that created the resource. */ createdBy?: string; /** * The type of identity that created the resource. Possible values include: 'User', * 'Application', 'ManagedIdentity', 'Key' */ createdByType?: CreatedByType; /** * The timestamp of resource creation (UTC). */ createdAt?: Date; /** * The identity that last modified the resource. */ lastModifiedBy?: string; /** * The type of identity that last modified the resource. Possible values include: 'User', * 'Application', 'ManagedIdentity', 'Key' */ lastModifiedByType?: LastModifiedByType; /** * The timestamp of resource modification (UTC). */ lastModifiedAt?: Date; } /** * Common fields that are returned in the response for all Azure Resource Manager resources * @summary Resource */ export interface Resource extends BaseResource { /** * Fully qualified resource ID for the resource. Ex - * /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly id?: string; /** * The name of the resource * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly name?: string; /** * The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or * "Microsoft.Storage/storageAccounts" * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; } /** * The resource model definition for an Azure Resource Manager tracked top level resource which has * 'tags' and a 'location' * @summary Tracked Resource */ export interface TrackedResource extends Resource { /** * Resource tags. */ tags?: { [propertyName: string]: string }; /** * The geo-location where the resource lives */ location: string; } /** * Represents a connected cluster. */ export interface ConnectedCluster extends TrackedResource { /** * The identity of the connected cluster. */ identity: ConnectedClusterIdentity; /** * Base64 encoded public certificate used by the agent to do the initial handshake to the backend * services in Azure. */ agentPublicKeyCertificate: string; /** * The Kubernetes version of the connected cluster resource * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly kubernetesVersion?: string; /** * Number of nodes present in the connected cluster resource * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly totalNodeCount?: number; /** * Number of CPU cores present in the connected cluster resource * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly totalCoreCount?: number; /** * Version of the agent running on the connected cluster resource * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly agentVersion?: string; /** * Provisioning state of the connected cluster resource. Possible values include: 'Succeeded', * 'Failed', 'Canceled', 'Provisioning', 'Updating', 'Deleting', 'Accepted' */ provisioningState?: ProvisioningState; /** * The Kubernetes distribution running on this connected cluster. */ distribution?: string; /** * The infrastructure on which the Kubernetes cluster represented by this connected cluster is * running on. */ infrastructure?: string; /** * Connected cluster offering * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly offering?: string; /** * Expiration time of the managed identity certificate * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly managedIdentityCertificateExpirationTime?: Date; /** * Time representing the last instance when heart beat was received from the cluster * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly lastConnectivityTime?: Date; /** * Represents the connectivity status of the connected cluster. Possible values include: * 'Connecting', 'Connected', 'Offline', 'Expired' * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly connectivityStatus?: ConnectivityStatus; /** * Metadata pertaining to creation and last modification of the resource * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly systemData?: SystemData; } /** * Object containing updates for patch operations. */ export interface ConnectedClusterPatch { /** * Resource tags. */ tags?: { [propertyName: string]: string }; /** * Describes the connected cluster resource properties that can be updated during PATCH * operation. */ properties?: any; } /** * The resource model definition for a Azure Resource Manager proxy resource. It will not have tags * and a location * @summary Proxy Resource */ export interface ProxyResource extends Resource { } /** * The resource model definition for an Azure Resource Manager resource with an etag. * @summary Entity Resource */ export interface AzureEntityResource extends Resource { /** * Resource Etag. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly etag?: string; } /** * The resource management error additional info. */ export interface ErrorAdditionalInfo { /** * The additional info type. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly type?: string; /** * The additional info. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly info?: any; } /** * The error detail. */ export interface ErrorDetail { /** * The error code. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly code?: string; /** * The error message. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly message?: string; /** * The error target. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly target?: string; /** * The error details. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly details?: ErrorDetail[]; /** * The error additional info. * **NOTE: This property will not be serialized. It can only be populated by the server.** */ readonly additionalInfo?: ErrorAdditionalInfo[]; } /** * Common error response for all Azure Resource Manager APIs to return error details for failed * operations. (This also follows the OData error response format.). * @summary Error response */ export interface ErrorResponse { /** * The error object. */ error?: ErrorDetail; } /** * An interface representing ConnectedKubernetesClientOptions. */ export interface ConnectedKubernetesClientOptions extends AzureServiceClientOptions { baseUri?: string; } /** * @interface * The paginated list of connected Clusters * @extends Array<ConnectedCluster> */ export interface ConnectedClusterList extends Array<ConnectedCluster> { /** * The link to fetch the next page of connected cluster */ nextLink?: string; } /** * @interface * The paginated list of connected cluster API operations. * @extends Array<Operation> */ export interface OperationList extends Array<Operation> { /** * The link to fetch the next page of connected cluster API operations. */ nextLink?: string; } /** * Defines values for ResourceIdentityType. * Possible values include: 'None', 'SystemAssigned' * @readonly * @enum {string} */ export type ResourceIdentityType = 'None' | 'SystemAssigned'; /** * Defines values for ProvisioningState. * Possible values include: 'Succeeded', 'Failed', 'Canceled', 'Provisioning', 'Updating', * 'Deleting', 'Accepted' * @readonly * @enum {string} */ export type ProvisioningState = 'Succeeded' | 'Failed' | 'Canceled' | 'Provisioning' | 'Updating' | 'Deleting' | 'Accepted'; /** * Defines values for ConnectivityStatus. * Possible values include: 'Connecting', 'Connected', 'Offline', 'Expired' * @readonly * @enum {string} */ export type ConnectivityStatus = 'Connecting' | 'Connected' | 'Offline' | 'Expired'; /** * Defines values for CreatedByType. * Possible values include: 'User', 'Application', 'ManagedIdentity', 'Key' * @readonly * @enum {string} */ export type CreatedByType = 'User' | 'Application' | 'ManagedIdentity' | 'Key'; /** * Defines values for LastModifiedByType. * Possible values include: 'User', 'Application', 'ManagedIdentity', 'Key' * @readonly * @enum {string} */ export type LastModifiedByType = 'User' | 'Application' | 'ManagedIdentity' | 'Key'; /** * Contains response data for the create operation. */ export type ConnectedClusterCreateResponse = ConnectedCluster & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ConnectedCluster; }; }; /** * Contains response data for the update operation. */ export type ConnectedClusterUpdateResponse = ConnectedCluster & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ConnectedCluster; }; }; /** * Contains response data for the get operation. */ export type ConnectedClusterGetResponse = ConnectedCluster & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ConnectedCluster; }; }; /** * Contains response data for the listByResourceGroup operation. */ export type ConnectedClusterListByResourceGroupResponse = ConnectedClusterList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ConnectedClusterList; }; }; /** * Contains response data for the listBySubscription operation. */ export type ConnectedClusterListBySubscriptionResponse = ConnectedClusterList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ConnectedClusterList; }; }; /** * Contains response data for the beginCreate operation. */ export type ConnectedClusterBeginCreateResponse = ConnectedCluster & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ConnectedCluster; }; }; /** * Contains response data for the listByResourceGroupNext operation. */ export type ConnectedClusterListByResourceGroupNextResponse = ConnectedClusterList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ConnectedClusterList; }; }; /** * Contains response data for the listBySubscriptionNext operation. */ export type ConnectedClusterListBySubscriptionNextResponse = ConnectedClusterList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: ConnectedClusterList; }; }; /** * Contains response data for the get operation. */ export type OperationsGetResponse = OperationList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationList; }; }; /** * Contains response data for the getNext operation. */ export type OperationsGetNextResponse = OperationList & { /** * The underlying HTTP response. */ _response: msRest.HttpResponse & { /** * The response body as text (string format) */ bodyAsText: string; /** * The response body as parsed JSON or XML */ parsedBody: OperationList; }; };
the_stack
import path from 'path' import { Argv } from 'yargs' import { Umzug, SequelizeStorage } from 'umzug' import { createLogger, SubgraphDeploymentID, connectDatabase, parseGRT, createMetrics, createMetricsServer, toAddress, connectContracts, } from '@graphprotocol/common-ts' import { defineIndexerManagementModels, createIndexerManagementServer, createIndexerManagementClient, indexerError, IndexerErrorCode, registerIndexerErrorMetrics, defineQueryFeeModels, NetworkSubgraph, IndexingStatusResolver, } from '@graphprotocol/indexer-common' import { startAgent } from '../agent' import { Network } from '../network' import { Indexer } from '../indexer' import { providers, Wallet } from 'ethers' import { startCostModelAutomation } from '../cost' import { bindAllocationExchangeContract, TransferReceiptCollector, } from '../query-fees' import { AllocationReceiptCollector } from '../query-fees/allocations' import { createSyncingServer } from '../syncing-server' export default { command: 'start', describe: 'Start the agent', builder: (yargs: Argv): Argv => { return yargs .option('ethereum', { description: 'Ethereum node or provider URL', type: 'string', required: true, group: 'Ethereum', }) .option('ethereum-network', { description: 'Ethereum network', type: 'string', required: false, default: 'mainnet', group: 'Ethereum', }) .option('ethereum-polling-interval', { description: 'Polling interval for the Ethereum provider (ms)', type: 'number', default: 4000, group: 'Ethereum', }) .option('gas-increase-timeout', { description: 'Time (in seconds) after which transactions will be resubmitted with a higher gas price', type: 'number', default: 240, group: 'Ethereum', coerce: arg => arg * 1000, }) .option('gas-increase-factor', { description: 'Factor by which gas prices are increased when resubmitting transactions', type: 'number', default: 1.2, group: 'Ethereum', }) .option('gas-price-max', { description: 'The maximum gas price (gwei) to use for transactions', type: 'number', default: 100, deprecated: true, group: 'Ethereum', coerce: arg => arg * 10 ** 9, }) .option('base-fee-per-gas-max', { description: 'The maximum base fee per gas (gwei) to use for transactions, for legacy transactions this will be treated as the max gas price', type: 'number', required: false, group: 'Ethereum', coerce: arg => arg * 10 ** 9, }) .option('transaction-attempts', { description: 'The maximum number of transaction attempts (Use 0 for unlimited)', type: 'number', default: 0, group: 'Ethereum', }) .option('mnemonic', { description: 'Mnemonic for the operator wallet', type: 'string', required: true, group: 'Ethereum', }) .option('indexer-address', { description: 'Ethereum address of the indexer', type: 'string', required: true, group: 'Ethereum', }) .option('graph-node-query-endpoint', { description: 'Graph Node endpoint for querying subgraphs', type: 'string', required: true, group: 'Indexer Infrastructure', }) .option('graph-node-status-endpoint', { description: 'Graph Node endpoint for indexing statuses etc.', type: 'string', required: true, group: 'Indexer Infrastructure', }) .option('graph-node-admin-endpoint', { description: 'Graph Node endpoint for applying and updating subgraph deployments', type: 'string', required: true, group: 'Indexer Infrastructure', }) .option('public-indexer-url', { description: 'Indexer endpoint for receiving requests from the network', type: 'string', required: true, group: 'Indexer Infrastructure', }) .options('indexer-geo-coordinates', { description: `Coordinates describing the Indexer's location using latitude and longitude`, type: 'string', array: true, default: ['31.780715', '-41.179504'], group: 'Indexer Infrastructure', coerce: arg => arg.reduce( (acc: string[], value: string) => [...acc, ...value.split(' ')], [], ), }) .option('network-subgraph-deployment', { description: 'Network subgraph deployment', type: 'string', group: 'Network Subgraph', }) .option('network-subgraph-endpoint', { description: 'Endpoint to query the network subgraph from', type: 'string', group: 'Network Subgraph', }) .option('index-node-ids', { description: 'Node IDs of Graph nodes to use for indexing (separated by commas)', type: 'string', array: true, required: true, coerce: arg => arg.reduce( (acc: string[], value: string) => [...acc, ...value.split(',')], [], ), group: 'Indexer Infrastructure', }) .option('default-allocation-amount', { description: 'Default amount of GRT to allocate to a subgraph deployment', type: 'string', default: '0.01', required: false, group: 'Protocol', }) .option('indexer-management-port', { description: 'Port to serve the indexer management API at', type: 'number', default: 8000, required: false, group: 'Indexer Infrastructure', }) .option('metrics-port', { description: 'Port to serve Prometheus metrics at', type: 'number', defaut: 7300, required: false, group: 'Indexer Infrastructure', }) .option('syncing-port', { description: 'Port to serve the network subgraph and other syncing data for indexer service at', type: 'number', default: 8002, required: false, group: 'Indexer Infrastructure', }) .option('restake-rewards', { description: `Restake claimed indexer rewards, if set to 'false' rewards will be returned to the wallet`, type: 'boolean', default: true, group: 'Indexer Infrastructure', }) .option('rebate-claim-threshold', { description: `Minimum value of rebate for a single allocation (in GRT) in order for it to be included in a batch rebate claim on-chain`, type: 'string', default: '200', // This value (the marginal gain of a claim in GRT), should always exceed the marginal cost of a claim (in ETH gas) group: 'Indexer Infrastructure', }) .option('rebate-claim-batch-threshold', { description: `Minimum total value of all rebates in an batch (in GRT) before the batch is claimed on-chain`, type: 'string', default: '2000', group: 'Indexer Infrastructure', }) .option('inject-dai', { description: 'Inject the GRT to DAI/USDC conversion rate into cost model variables', type: 'boolean', default: true, group: 'Cost Models', }) .option('dai-contract', { description: 'Address of the DAI or USDC contract to use for the --inject-dai conversion rate', type: 'string', // Default to USDC default: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', }) .option('postgres-host', { description: 'Postgres host', type: 'string', required: true, group: 'Postgres', }) .option('postgres-port', { description: 'Postgres port', type: 'number', default: 5432, group: 'Postgres', }) .option('postgres-username', { description: 'Postgres username', type: 'string', required: false, default: 'postgres', group: 'Postgres', }) .option('postgres-password', { description: 'Postgres password', type: 'string', default: '', required: false, group: 'Postgres', }) .option('postgres-database', { description: 'Postgres database name', type: 'string', required: true, group: 'Postgres', }) .option('log-level', { description: 'Log level', type: 'string', default: 'debug', group: 'Indexer Infrastructure', }) .option('register', { description: 'Whether to register the indexer on chain', type: 'boolean', default: true, group: 'Protocol', }) .option('offchain-subgraphs', { description: 'Subgraphs to index that are not on chain (comma-separated)', type: 'string', array: true, default: [], coerce: arg => arg .reduce( (acc: string[], value: string) => [...acc, ...value.split(',')], [], ) .map((id: string) => id.trim()) .filter((id: string) => id.length > 0), }) .option('poi-disputable-epochs', { description: 'The number of epochs in the past to look for potential PoI disputes', type: 'number', default: 1, group: 'Disputes', }) .option('poi-dispute-monitoring', { description: 'Monitor the network for potential PoI disputes', type: 'boolean', default: false, group: 'Disputes', }) .check(argv => { if ( !argv['network-subgraph-endpoint'] && !argv['network-subgraph-deployment'] ) { return `At least one of --network-subgraph-endpoint and --network-subgraph-deployment must be provided` } if (argv['indexer-geo-coordinates']) { const [geo1, geo2] = argv['indexer-geo-coordinates'] if (!+geo1 || !+geo2) { return 'Invalid --indexer-geo-coordinates provided. Must be of format e.g.: 31.780715 -41.179504' } } if (argv['gas-increase-timeout']) { if (argv['gas-increase-timeout'] < 30000) { return 'Invalid --gas-increase-timeout provided. Must be at least 30 seconds' } } if (argv['gas-increase-factor'] <= 1.0) { return 'Invalid --gas-increase-factor provided. Must be > 1.0' } return true }) .option('vector-node', { description: 'URL of a vector node', type: 'string', group: 'Query Fees', }) .option('vector-router', { description: 'Public identifier of the vector router', type: 'string', group: 'Query Fees', }) .option('vector-transfer-definition', { description: 'Address of the Graph transfer definition contract', type: 'string', default: 'auto', group: 'Query Fees', }) .option('vector-event-server', { description: 'External URL of the vector event server of the agent', type: 'string', group: 'Query Fees', }) .option('vector-event-server-port', { description: 'Port to serve the vector event server at', type: 'number', required: false, default: 8001, group: 'Query Fees', }) .option('use-vector', { description: 'Whether to use Vector for query fees', type: 'boolean', required: false, implies: [ 'vector-node', 'vector-router', 'vector-transfer-definition', 'vector-event-server', 'vector-event-server-port', ], group: 'Query Fees', }) .option('allocation-exchange-contract', { description: 'Address of the contract to submit query fee vouchers to', type: 'string', required: false, default: 'auto', conflicts: ['use-vector'], implies: ['collect-receipts-endpoint'], group: 'Query Fees', }) .option('collect-receipts-endpoint', { description: 'Client endpoint for collecting receipts', type: 'string', required: false, conflicts: ['use-vector'], implies: ['allocation-exchange-contract'], group: 'Query Fees', }) .option('voucher-expiration', { description: 'Time (in hours) after which a low query fee voucher expires and is deleted (default: 90 days)', type: 'number', default: 2160, required: false, conflicts: ['use-vector'], implies: ['allocation-exchange-contract'], group: 'Query Fees', }) }, handler: async ( // eslint-disable-next-line @typescript-eslint/no-explicit-any argv: { [key: string]: any } & Argv['argv'], ): Promise<void> => { const logger = createLogger({ name: 'IndexerAgent', async: false, level: argv.logLevel, }) if (argv.gasIncreaseTimeout < 90000) { logger.warn( 'Gas increase timeout is set to less than 90 seconds (~ 6 blocks). This may lead to high gas usage', { gasIncreaseTimeout: argv.gasIncreaseTimeout / 1000.0 }, ) } if (argv.gasIncreaseFactor > 1.5) { logger.warn( `Gas increase factor is set to > 1.5. This may lead to high gas usage`, { gasIncreaseFactor: argv.gasIncreaseFactor }, ) } if (argv.rebateClaimThreshold < argv.voucherRedeemMinSingleValue) { logger.warn( `Rebate single minimum claim value is less than voucher minimum redemption value, but claims depend on redemptions`, ) } if (argv.rebateClaimThreshold === 0) { logger.warn( `Minimum query fee rebate value is 0 GRT, which may lead to claiming unprofitable rebates`, ) } process.on('unhandledRejection', err => { logger.warn(`Unhandled promise rejection`, { err: indexerError(IndexerErrorCode.IE035, err), }) }) process.on('uncaughtException', err => { logger.warn(`Uncaught exception`, { err: indexerError(IndexerErrorCode.IE036, err), }) }) // Spin up a metrics server const metrics = createMetrics() createMetricsServer({ logger: logger.child({ component: 'MetricsServer' }), registry: metrics.registry, port: argv.metricsPort, }) // Register indexer error metrics so we can track any errors that happen // inside the agent registerIndexerErrorMetrics(metrics) logger.info('Connect to database', { host: argv.postgresHost, port: argv.postgresPort, database: argv.postgresDatabase, }) const sequelize = await connectDatabase({ logging: undefined, host: argv.postgresHost, port: argv.postgresPort, username: argv.postgresUsername, password: argv.postgresPassword, database: argv.postgresDatabase, }) logger.info('Successfully connected to database') // Automatic database migrations logger.info(`Run database migrations`) try { const umzug = new Umzug({ migrations: { glob: path.join(__dirname, '..', 'migrations', '*.js') }, context: { queryInterface: sequelize.getQueryInterface(), logger, }, storage: new SequelizeStorage({ sequelize }), logger, }) await umzug.up() } catch (err) { logger.fatal(`Failed to run database migrations`, { err: indexerError(IndexerErrorCode.IE001, err), }) process.exit(1) return } logger.info(`Successfully ran database migrations`) logger.info(`Sync database models`) const managementModels = defineIndexerManagementModels(sequelize) const queryFeeModels = defineQueryFeeModels(sequelize) await sequelize.sync() logger.info(`Successfully synced database models`) logger.info(`Connect to Ethereum`) let providerUrl try { providerUrl = new URL(argv.ethereum) } catch (err) { logger.fatal(`Invalid Ethereum URL`, { err: indexerError(IndexerErrorCode.IE002, err), url: argv.ethereum, }) process.exit(1) return } const ethProviderMetrics = { requests: new metrics.client.Counter({ name: 'eth_provider_requests', help: 'Ethereum provider requests', registers: [metrics.registry], labelNames: ['method'], }), } if (providerUrl.password && providerUrl.protocol == 'http:') { logger.warn( 'Ethereum endpoint does not use HTTPS, your authentication credentials may not be secure', ) } // Prevent passing empty basicAuth info let username let password if (providerUrl.username == '' && providerUrl.password == '') { username = undefined password = undefined } else { username = providerUrl.username password = providerUrl.password } const ethereum = new providers.StaticJsonRpcProvider( { url: providerUrl.toString(), user: username, password: password, allowInsecureAuthentication: true, }, argv.ethereumNetwork, ) ethereum.pollingInterval = argv.ethereumPollingInterval ethereum.on('debug', info => { if (info.action === 'response') { ethProviderMetrics.requests.inc({ method: info.request.method, }) logger.trace('Ethereum request', { method: info.request.method, params: info.request.params, response: info.response, }) } }) ethereum.on('network', (newNetwork, oldNetwork) => { logger.trace('Ethereum network change', { oldNetwork: oldNetwork, newNetwork: newNetwork, }) }) logger.info(`Connected to Ethereum`, { pollingInterval: ethereum.pollingInterval, network: await ethereum.detectNetwork(), }) logger.info(`Connect wallet`, { network: ethereum.network.name, chainId: ethereum.network.chainId, }) let wallet = Wallet.fromMnemonic(argv.mnemonic) wallet = wallet.connect(ethereum) logger.info(`Connected wallet`) logger.info(`Connecting to contracts`) let contracts = undefined try { contracts = await connectContracts(wallet, ethereum.network.chainId) } catch (err) { logger.error( `Failed to connect to contracts, please ensure you are using the intended Ethereum network`, { err, }, ) process.exit(1) } logger.info(`Successfully connected to contracts`, { curation: contracts.curation.address, disputeManager: contracts.disputeManager.address, epochManager: contracts.epochManager.address, gns: contracts.gns.address, rewardsManager: contracts.rewardsManager.address, serviceRegistry: contracts.serviceRegistry.address, staking: contracts.staking.address, token: contracts.token.address, }) const indexerAddress = toAddress(argv.indexerAddress) const indexingStatusResolver = new IndexingStatusResolver({ logger: logger, statusEndpoint: argv.graphNodeStatusEndpoint, }) const networkSubgraph = await NetworkSubgraph.create({ logger, endpoint: argv.networkSubgraphEndpoint, deployment: argv.networkSubgraphDeployment ? { indexingStatusResolver: indexingStatusResolver, deployment: new SubgraphDeploymentID( argv.networkSubgraphDeployment, ), graphNodeQueryEndpoint: argv.graphNodeQueryEndpoint, } : undefined, }) logger.info('Launch indexer management API server') const indexerManagementClient = await createIndexerManagementClient({ models: managementModels, address: indexerAddress, contracts, indexingStatusResolver, networkSubgraph, logger, defaults: { globalIndexingRule: { allocationAmount: parseGRT(argv.defaultAllocationAmount), parallelAllocations: 1, }, }, features: { injectDai: argv.injectDai, }, }) await createIndexerManagementServer({ logger, client: indexerManagementClient, port: argv.indexerManagementPort, }) logger.info(`Successfully launched indexer management API server`) logger.info('Connect to network') const indexer = new Indexer( logger, argv.graphNodeAdminEndpoint, indexingStatusResolver, indexerManagementClient, argv.indexNodeIds, parseGRT(argv.defaultAllocationAmount), indexerAddress, ) const networkSubgraphDeployment = argv.networkSubgraphDeployment ? new SubgraphDeploymentID(argv.networkSubgraphDeployment) : undefined if (networkSubgraphDeployment !== undefined) { // Make sure the network subgraph is being indexed await indexer.ensure( `${networkSubgraphDeployment.ipfsHash.slice( 0, 23, )}/${networkSubgraphDeployment.ipfsHash.slice(23)}`, networkSubgraphDeployment, ) } const maxGasFee = argv.baseFeeGasMax || argv.gasPriceMax const network = await Network.create( logger, ethereum, contracts, wallet, indexerAddress, argv.publicIndexerUrl, argv.indexerGeoCoordinates, networkSubgraph, argv.restakeRewards, parseGRT(argv.rebateClaimThreshold), parseGRT(argv.rebateClaimBatchThreshold), argv.poiDisputeMonitoring, argv.poiDisputableEpochs, argv.gasIncreaseTimeout, argv.gasIncreaseFactor, maxGasFee, argv.transactionAttempts, ) logger.info('Successfully connected to network', { restakeRewards: argv.restakeRewards, }) logger.info(`Launch syncing server`) await createSyncingServer({ logger, networkSubgraph, port: argv.syncingPort, }) logger.info(`Successfully launched syncing server`) startCostModelAutomation({ logger, ethereum, contracts: network.contracts, indexerManagement: indexerManagementClient, injectDai: argv.injectDai, daiContractAddress: toAddress(argv.daiContract), metrics, }) let receiptCollector if (argv.useVector) { // Identify the Graph transfer definition address // TODO: Pick it from the `contracts` const vectorTransferDefinition = toAddress( argv.vectorTransferDefinition === 'auto' ? ethereum.network.chainId === 1 ? '0x0000000000000000000000000000000000000000' : '0x87b1A09EfE2DA4022fc4a152D10dd2Df36c67544' : argv.vectorTransferDefinition, ) // Automatically sync the status of receipt transfers to the db receiptCollector = await TransferReceiptCollector.create({ logger, ethereum, metrics, wallet, contracts, vector: { nodeUrl: argv.vectorNode, routerIdentifier: argv.vectorRouter, transferDefinition: vectorTransferDefinition, eventServer: { url: argv.vectorEventServer, port: argv.vectorEventServerPort, }, }, models: queryFeeModels, }) await receiptCollector.queuePendingTransfersFromDatabase() } else { // Identify the allocation exchange contract address // TODO: Pick it from the `contracts` const allocationExchangeContract = toAddress( argv.allocationExchangeContract === 'auto' ? ethereum.network.chainId === 1 ? '0x4a53cf3b3EdA545dc61dee0cA21eA8996C94385f' // mainnet : '0x58Ce0A0f41449E349C1A91Dd9F3D9286Bf32c161' // rinkeby : argv.allocationExchangeContract, ) receiptCollector = new AllocationReceiptCollector({ logger, network, models: queryFeeModels, collectEndpoint: new URL(argv.collectReceiptsEndpoint), allocationExchange: bindAllocationExchangeContract( wallet, allocationExchangeContract, ), allocationClaimThreshold: parseGRT(argv.rebateClaimThreshold), voucherExpiration: argv.voucherExpiration, }) await receiptCollector.queuePendingReceiptsFromDatabase() } await startAgent({ logger, metrics, indexer, network, networkSubgraph, registerIndexer: argv.register, offchainSubgraphs: argv.offchainSubgraphs.map( (s: string) => new SubgraphDeploymentID(s), ), receiptCollector, }) }, }
the_stack
export default function makeDashboard(integrationId: string) { return { annotations: { list: [ { builtIn: 1, datasource: "-- Grafana --", enable: true, hide: true, iconColor: "rgba(0, 211, 255, 1)", name: "Annotations & Alerts", type: "dashboard" } ] }, editable: true, gnetId: null, graphTooltip: 0, iteration: 1623960497845, links: [], panels: [ { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 0 }, hiddenSeries: false, id: 2, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `sum(sum(ranges{integration_id="${integrationId}",instance=~"$node"})) by (instance)`, hide: false, interval: "", intervalFactor: 2, legendFormat: "Ranges", refId: "A" }, { expr: `sum(sum(replicas_leaders{integration_id="${integrationId}",instance=~"$node"}) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Leaders", refId: "B" }, { expr: `sum(sum(replicas_leaseholders{integration_id="${integrationId}",instance=~"$node"}) by (instance))`, interval: "", legendFormat: "Lease Holders", refId: "G" }, { exemplar: true, expr: `sum(sum(replicas_leaders_not_leaseholders{integration_id="${integrationId}",instance=~"$node"}) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Leaders w/o Lease", refId: "C" }, { expr: `sum(sum(ranges_unavailable{integration_id="${integrationId}",instance=~"$node"}) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Unavailable", refId: "D" }, { exemplar: true, expr: `sum(sum(ranges_underreplicated{integration_id="${integrationId}",instance=~"$node"}) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Under-replicated", refId: "E" }, { expr: `sum(sum(ranges_overreplicated{integration_id="${integrationId}",instance=~"$node"}) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Over-replicated", refId: "F" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Ranges", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:133", format: "short", label: "ranges", logBase: 1, max: null, min: null, show: true }, { $$hashKey: "object:134", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The number of replicas on each store.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 8 }, hiddenSeries: false, id: 4, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `sum(replicas{integration_id="${integrationId}",instance=~"$node"}) by (instance)`, interval: "", intervalFactor: 2, legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Replicas per Store", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:431", format: "short", label: "replicas", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:432", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "The number of leaseholder replicas on each store. A leaseholder replica is the one that receives and coordinates all read and write requests for its range.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 16 }, hiddenSeries: false, id: 6, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `sum(replicas_leaseholders{integration_id="${integrationId}",instance=~"$node"}) by (instance)`, interval: "", intervalFactor: 2, legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Leaseholders per Store", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:581", format: "short", label: "leaseholders", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:582", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "Exponentially weighted moving average of the number of KV batch requests processed by leaseholder replicas on each store per second. Tracks roughly the last 30 minutes of requests. Used for load-based rebalancing decisions.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 24 }, hiddenSeries: false, id: 14, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `rebalancing_queriespersecond{integration_id="${integrationId}",instance=~"$node"}`, interval: "", legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Average Queries per Store", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:731", format: "short", label: "queries", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:732", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "Number of logical bytes stored in [key-value pairs](https://www.cockroachlabs.com/docs/v21.1/architecture/distribution-layer.html#table-data) on each node.\n\nThis includes historical and deleted data.", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 32 }, hiddenSeries: false, id: 16, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { exemplar: true, expr: `totalbytes{integration_id="${integrationId}",instance=~"$node"}`, interval: "", legendFormat: "{{instance}}", refId: "A" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Logical Bytes per Store", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:807", format: "bytes", label: "logical store size", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:808", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", description: "", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 40 }, hiddenSeries: false, id: 8, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `sum(sum(replicas{integration_id="${integrationId}",instance=~"$node"}) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Replicas", refId: "A" }, { expr: `sum(sum(replicas_quiescent{integration_id="${integrationId}",instance=~"$node"}) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Quiescent", refId: "B" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Replica Quiescence", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:883", format: "short", label: "replicas", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:884", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 48 }, hiddenSeries: false, id: 10, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 1, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `sum(sum(rate(range_splits{integration_id="${integrationId}",instance=~"$node"}[5m])) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Splits", refId: "A" }, { expr: `sum(sum(rate(range_merges{integration_id="${integrationId}",instance=~"$node"}[5m])) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Merges", refId: "C" }, { expr: `sum(sum(rate(range_adds{integration_id="${integrationId}",instance=~"$node"}[5m])) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Adds", refId: "B" }, { expr: `sum(sum(rate(range_removes{integration_id="${integrationId}",instance=~"$node"}[5m])) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Removes", refId: "D" }, { exemplar: true, expr: `sum(sum(rate(leases_transfers_success{integration_id="${integrationId}",instance=~"$node"}[5m])) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Lease Transfers", refId: "E" }, { exemplar: true, expr: `sum(sum(rate(rebalancing_lease_transfers{integration_id="${integrationId}",instance=~"$node"}[5m])) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Load-based Lease Transfers", refId: "F" }, { exemplar: true, expr: `sum(sum(rate(rebalancing_range_rebalances{integration_id="${integrationId}",instance=~"$node"}[5m])) by (instance))`, interval: "", intervalFactor: 2, legendFormat: "Load-based Range Rebalances", refId: "G" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Range Operations", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:959", format: "short", label: "ranges", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:960", format: "short", label: null, logBase: 1, max: null, min: null, show: true } ], yaxis: { align: false, alignLevel: null } }, { aliasColors: {}, bars: false, dashLength: 10, dashes: false, datasource: "metrics", fieldConfig: { defaults: {}, overrides: [] }, fill: 1, fillGradient: 0, gridPos: { h: 8, w: 24, x: 0, y: 56 }, hiddenSeries: false, id: 12, legend: { avg: false, current: false, max: false, min: false, show: true, total: false, values: false }, lines: true, linewidth: 2, nullPointMode: "null as zero", options: { alertThreshold: true }, percentage: false, pluginVersion: "", pointradius: 2, points: false, renderer: "flot", seriesOverrides: [], spaceLength: 10, stack: false, steppedLine: false, targets: [ { expr: `sum(rate(range_snapshots_generated{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "Generated", refId: "A" }, { exemplar: true, expr: `sum(rate(range_snapshots_applied_voter{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "Applied (Voters)", refId: "B" }, { exemplar: true, expr: `sum(rate(range_snapshots_applied_initial{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "Applied (Initial Upreplication)", refId: "C" }, { exemplar: true, expr: `sum(rate(range_snapshots_applied_initial{integration_id="${integrationId}",instance=~"$node"}[5m]))`, hide: false, interval: "", intervalFactor: 2, legendFormat: "Applied (Non-Voters)", refId: "D" }, { expr: `sum(rate(replicas_reserved{integration_id="${integrationId}",instance=~"$node"}[5m]))`, interval: "", intervalFactor: 2, legendFormat: "Reserved Replicas", refId: "E" } ], thresholds: [], timeFrom: null, timeRegions: [], timeShift: null, title: "Snapshots", tooltip: { shared: true, sort: 0, value_type: "individual" }, type: "graph", xaxis: { buckets: null, mode: "time", name: null, show: true, values: [] }, yaxes: [ { $$hashKey: "object:1109", format: "short", label: "snapshots", logBase: 1, max: null, min: "0", show: true }, { $$hashKey: "object:1110", format: "short", label: "", logBase: 1, max: null, min: "0", show: false } ], yaxis: { align: false, alignLevel: null } } ], refresh: false, schemaVersion: 27, style: "dark", tags: [], templating: { list: [ { allValue: "", current: { selected: false, text: "All", value: "$__all" }, datasource: "metrics", definition: `label_values(sys_uptime{integration_id="${integrationId}"},instance)`, description: null, error: null, hide: 0, includeAll: true, label: "Node", multi: false, name: "node", options: [], query: { query: `label_values(sys_uptime{integration_id="${integrationId}"},instance)`, refId: "Prometheus-node-Variable-Query" }, refresh: 1, regex: "", skipUrlSync: false, sort: 1, tagValuesQuery: "", tags: [], tagsQuery: "", type: "query", useTags: false } ] }, time: { from: "now-1h", to: "now" }, timepicker: {}, timezone: "utc", title: "CRDB Console: Replication", uid: `rep-${integrationId}`, version: 3 }; } export type Dashboard = ReturnType<typeof makeDashboard>;
the_stack
import Transport from "@ledgerhq/hw-transport"; import { openTransportReplayer, RecordStore, } from "@ledgerhq/hw-transport-mocker"; import Btc from "../src/Btc"; import BtcNew from "../src/BtcNew"; import BtcOld, { AddressFormat } from "../src/BtcOld"; import { AppAndVersion, getAppAndVersion } from "../src/getAppAndVersion"; import { TestingClient } from "./newops/integrationtools"; test("btc.getWalletXpub", async () => { /* This is how I generate the xpub Mainnet: prv: 0x0488ade4 = 76066276 pub: 0x0488b21e = 76067358 Testnet: prv: 0x04358394 = 70615956 pub: 0x043587cf = 70617039 versionpriv=70615956 versionpub=70617039 seed=be388c569b4a6846c847e882e09f000000000000000000000000e255bcd17cb8 m=`bx hd-new -v $versionpriv $seed` m_44h=`bx hd-private -d --index 44 $m` m_44h_0h=`bx hd-private -d --index 0 $m_44h` M_44h_0h=`bx hd-to-public -v $versionpub $m_44h_0h` m_44h_0h_17h=`bx hd-private -d --index 17 $m_44h_0h` M_44h_0h_17h=`bx hd-to-public -v $versionpub $m_44h_0h_17h` echo "M_44h_0h_17h xpub: $M_44h_0h_17h" echo "M_44h_0h: `bx base58check-decode $M_44h_0h`" echo "M_44h_0h_17h: `bx base58check-decode $M_44h_0h_17h`" Output (note that version (4) should be prepended to payload): M_44h_0h_17h xpub: tpubDDn3XrB65rhCzRh4fsD8gogX9gFvGcEmP3jZtGbdxK7Mn25gipFB68vLFyqZ43i4e5Z7p6rki7THyb2PeH1D3NkLm5EUFzbUzyafp872GKa M_44h_0h: wrapper { checksum 2142374336 payload 3587cf026d874e2b800000008bd937d416de7020952cc8e2c99ce9ac7e01265e31ceb8e47bf9c3 7f46f8abbd035d4a72237572a91e13818fa38cedabe6174569cc9a319012f75150d5c0a0639d version 4 } M_44h_0h_17h: wrapper { checksum 4186623970 payload 3587cf03ee6e81fd80000011c071c6f2d05cbc9ea9a04951b238086ce1608cf00020c3cab85b36 aac5fdd59102250dfdfb84c1efd160ed0e10ebac845d0e4b04277174630ba56de96bbd3afb21 version 4 } The xpub bytes (from bip32) are 4 byte: version bytes (mainnet: 0x0488B21E public, 0x0488ADE4 private; testnet: 0x043587CF public, 0x04358394 private) 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 derived keys, .... 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) 4 bytes: child number. This is ser32(i) for i in xi = xpar/i, with xi the key being serialized. (0x00000000 if master key) 32 bytes: the chain code 33 bytes: the public key or private key data (serP(K) for public keys, 0x00 || ser256(k) for private keys) M_44h_0h_17h: 043587cf 03 ee6e81fd 80000011 c071c6f2d05cbc9ea9a04951b238086ce1608cf00020c3cab85b36aac5fdd591 02250dfdfb84c1efd160ed0e10ebac845d0e4b04277174630ba56de96bbd3afb21 M_44h_0h: 043587cf 02 6d874e2b 80000000 8bd937d416de7020952cc8e2c99ce9ac7e01265e31ceb8e47bf9c37f46f8abbd 035d4a72237572a91e13818fa38cedabe6174569cc9a319012f75150d5c0a0639d Uncompress (a bit covoluted, but works): prv=`bx hd-to-ec -p $versionpriv $m_44h_0h_17h` bx ec-to-public -u ${prv:2} 04250dfdfb84c1efd160ed0e10ebac845d0e4b04277174630ba56de96bbd3afb21fc6c04ce0d5a0cbd784fdabc99d16269c27cf3842fe8440f1f21b8af900f0eaa pubCompr=`bx ec-to-public ${prv:2}` bx ec-to-address $pubCompr 16Y97ByhyboePhTYMMmFj1tq5Cy1bDq8jT prv=`bx hd-to-ec -p $versionpriv $m_44h_0h` bx ec-to-public -u ${prv:2} 045d4a72237572a91e13818fa38cedabe6174569cc9a319012f75150d5c0a0639d54eafd13a68d079b7a67764800c6a981825ef52384f08c3925109188ab21bc09 pubCompr=`bx ec-to-public ${prv:2}` bx ec-to-address $pubCompr 1NjiCsVBuKDT62LmaUd7WZZZBK2gPAkisb These translates to pubkeylen(1) || pubkeyuncompressed(65) || addrLen(1) || address || chaincode(32) Expected response for m/44'/0'/17': 41 04250dfdfb84c1efd160ed0e10ebac845d0e4b04277174630ba56de96bbd3afb21fc6c04ce0d5a0cbd784fdabc99d16269c27cf3842fe8440f1f21b8af900f0eaa 22 ascii(16Y97ByhyboePhTYMMmFj1tq5Cy1bDq8jT) c071c6f2d05cbc9ea9a04951b238086ce1608cf00020c3cab85b36aac5fdd591 Expected response for m/44'/0': 41 045d4a72237572a91e13818fa38cedabe6174569cc9a319012f75150d5c0a0639d54eafd13a68d079b7a67764800c6a981825ef52384f08c3925109188ab21bc09 22 ascii(1NjiCsVBuKDT62LmaUd7WZZZBK2gPAkisb) 8bd937d416de7020952cc8e2c99ce9ac7e01265e31ceb8e47bf9c37f46f8abbd */ /*eslint-disable */ const pubkeyParent = "045d4a72237572a91e13818fa38cedabe6174569cc9a319012f75150d5c0a0639d54eafd13a68d079b7a67764800c6a981825ef52384f08c3925109188ab21bc09"; const addrParent = Buffer.from("1NjiCsVBuKDT62LmaUd7WZZZBK2gPAkisb", "ascii").toString("hex"); const ccParent = "8bd937d416de7020952cc8e2c99ce9ac7e01265e31ceb8e47bf9c37f46f8abbd"; const responseParent = `41${pubkeyParent}22${addrParent}${ccParent}`; const pubkeyAcc = "04250dfdfb84c1efd160ed0e10ebac845d0e4b04277174630ba56de96bbd3afb21fc6c04ce0d5a0cbd784fdabc99d16269c27cf3842fe8440f1f21b8af900f0eaa"; const addrAcc = Buffer.from("16Y97ByhyboePhTYMMmFj1tq5Cy1bDq8jT", "ascii").toString("hex"); const ccAcc = "c071c6f2d05cbc9ea9a04951b238086ce1608cf00020c3cab85b36aac5fdd591"; /*eslint-enable */ const responseAcc = `41${pubkeyAcc}22${addrAcc}${ccAcc}`; const transport = await openTransportReplayer( RecordStore.fromString(` => b001000000 <= 0107426974636f696e06312e332e323301029000 => e040000009028000002c80000000 <= ${responseParent}9000 => e04000000d038000002c8000000080000011 <= ${responseAcc}9000 `) ); const btc = new Btc(transport); const result = await btc.getWalletXpub({ path: "44'/0'/17'", xpubVersion: 0x043587cf, // mainnet }); const expectedXpub = "tpubDDn3XrB65rhCzRh4fsD8gogX9gFvGcEmP3jZtGbdxK7Mn25gipFB68vLFyqZ43i4e5Z7p6rki7THyb2PeH1D3NkLm5EUFzbUzyafp872GKa"; expect(result).toEqual(expectedXpub); }); test("btc.getWalletPublicKey", async () => { const transport = await openTransportReplayer( RecordStore.fromString(` => b001000000 <= 0107426974636f696e06312e332e323301029000 => e040000011048000002c800000008000000000000000 <= 410486b865b52b753d0a84d09bc20063fab5d8453ec33c215d4019a5801c9c6438b917770b2782e29a9ecc6edb67cd1f0fbf05ec4c1236884b6d686d6be3b1588abb2231334b453654666641724c683466564d36756f517a7673597135767765744a63564dbce80dd580792cd18af542790e56aa813178dc28644bb5f03dbd44c85f2d2e7a9000 `) ); const btc = new Btc(transport); const result = await btc.getWalletPublicKey("44'/0'/0'/0"); expect(result).toEqual({ bitcoinAddress: "13KE6TffArLh4fVM6uoQzvsYq5vwetJcVM", chainCode: "bce80dd580792cd18af542790e56aa813178dc28644bb5f03dbd44c85f2d2e7a", publicKey: "0486b865b52b753d0a84d09bc20063fab5d8453ec33c215d4019a5801c9c6438b917770b2782e29a9ecc6edb67cd1f0fbf05ec4c1236884b6d686d6be3b1588abb", }); }); test("btc 2", async () => { const transport = await openTransportReplayer( RecordStore.fromString(` => b001000000 <= 0107426974636f696e06312e332e323301029000 => b001000000 <= 0107426974636f696e06312e332e323301029000 => e042000009000000010100000001 <= 9000 => e0428000254ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a <= 9000 => e04280003247304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f <= 9000 => e04280003257c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7 <= 9000 => e04280002a325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff <= 9000 => e04280000102 <= 9000 => e04280002281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac <= 9000 => e042800022a0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac <= 9000 => e04280000400000000 <= 32005df4c773da236484dae8f0fdba3d7e0ba1d05070d1a34fc44943e638441262a04f1001000000a086010000000000b890da969aa6f3109000 => e04000000d03800000000000000000000000 <= 41046666422d00f1b308fc7527198749f06fedb028b979c09f60d0348ef79c985e4138b86996b354774c434488d61c7fb20a83293ef3195d422fde9354e6cf2a74ce223137383731457244716465764c544c57424836577a6a556331454b4744517a434d41612d17bc55b7aa153ae07fba348692c2976e6889b769783d475ba7488fb547709000 => e0440000050100000001 <= 9000 => e04480003b013832005df4c773da236484dae8f0fdba3d7e0ba1d05070d1a34fc44943e638441262a04f1001000000a086010000000000b890da969aa6f31019 <= 9000 => e04480001d76a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88acffffffff <= 9000 => e04a80002301905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac <= 00009000 => e04800001303800000000000000000000000000000000001 <= 3145022100ff492ad0b3a634aa7751761f7e063bf6ef4148cd44ef8930164580d5ba93a17802206fac94b32e296549e2e478ce806b58d61cfacbfed35ac4ceca26ac531f92b20a019000 `) ); const btc = new Btc(transport); const tx1 = btc.splitTransaction( "01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000" ); const result = await btc.createPaymentTransactionNew({ inputs: [[tx1, 1, undefined, undefined]], associatedKeysets: ["0'/0/0"], changePath: undefined, outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac", additionals: [], }); expect(result).toEqual( "0100000001c773da236484dae8f0fdba3d7e0ba1d05070d1a34fc44943e638441262a04f10010000006b483045022100ff492ad0b3a634aa7751761f7e063bf6ef4148cd44ef8930164580d5ba93a17802206fac94b32e296549e2e478ce806b58d61cfacbfed35ac4ceca26ac531f92b20a0121026666422d00f1b308fc7527198749f06fedb028b979c09f60d0348ef79c985e41ffffffff01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac00000000" ); }); test("btc 3", async () => { const transport = await openTransportReplayer( RecordStore.fromString(` => e042000009000000010100000001 <= 9000 => e0428000254ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a <= 9000 => e04280003247304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f <= 9000 => e04280003257c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7 <= 9000 => e04280002a325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff <= 9000 => e04280000102 <= 9000 => e04280002281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac <= 9000 => e042800022a0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac <= 9000 => e04280000400000000 <= 3200e4eac773da236484dae8f0fdba3d7e0ba1d05070d1a34fc44943e638441262a04f1001000000a086010000000000c79483cc9a6e96fe9000 => e0440000050100000001 <= 9000 => e04480002600c773da236484dae8f0fdba3d7e0ba1d05070d1a34fc44943e638441262a04f100100000069 <= 9000 => e04480003252210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04b <= 9000 => e044800032d40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc5 <= 9000 => e04480000900639853aeffffffff <= 9000 => e04a80002301905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac <= 00009000 => e04800001303800000000000000000000000000000000001 <= 3045022100b5b1813992282b9a1fdd957b9751d79dc21018abc6586336e272212cc89cfe84022053765a1da0bdb5a0631a9866f1fd4c583589d5188b11cfa302fc20cd2611a71e019000 `) ); const btc = new Btc(transport); const tx1 = btc.splitTransaction( "01000000014ea60aeac5252c14291d428915bd7ccd1bfc4af009f4d4dc57ae597ed0420b71010000008a47304402201f36a12c240dbf9e566bc04321050b1984cd6eaf6caee8f02bb0bfec08e3354b022012ee2aeadcbbfd1e92959f57c15c1c6debb757b798451b104665aa3010569b49014104090b15bde569386734abf2a2b99f9ca6a50656627e77de663ca7325702769986cf26cc9dd7fdea0af432c8e2becc867c932e1b9dd742f2a108997c2252e2bdebffffffff0281b72e00000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88aca0860100000000001976a9144533f5fb9b4817f713c48f0bfe96b9f50c476c9b88ac00000000" ); const result = await btc.signP2SHTransaction({ inputs: [ [ tx1, 1, "52210289b4a3ad52a919abd2bdd6920d8a6879b1e788c38aa76f0440a6f32a9f1996d02103a3393b1439d1693b063482c04bd40142db97bdf139eedd1b51ffb7070a37eac321030b9a409a1e476b0d5d17b804fcdb81cf30f9b99c6f3ae1178206e08bc500639853ae", undefined, ], ], associatedKeysets: ["0'/0/0"], outputScriptHex: "01905f0100000000001976a91472a5d75c8d2d0565b656a5232703b167d50d5a2b88ac", }); expect(result).toEqual([ "3045022100b5b1813992282b9a1fdd957b9751d79dc21018abc6586336e272212cc89cfe84022053765a1da0bdb5a0631a9866f1fd4c583589d5188b11cfa302fc20cd2611a71e", ]); }); test("btc 4", async () => { const transport = await openTransportReplayer( RecordStore.fromString(` => e04e000117048000002c800000008000000000000000000474657374 <= 00009000 => e04e80000100 <= 3045022100e32b32b8a6b4228155ba4d1a536d8fed9900606663fbbf4ea420ed8e944f9c18022053c97c74d2f6d8620d060584dc7886f5f3003684bb249508eb7066215172281a9000 `) ); const btc = new Btc(transport); const result = await btc.signMessageNew( "44'/0'/0'/0", Buffer.from("test").toString("hex") ); expect(result).toEqual({ r: "e32b32b8a6b4228155ba4d1a536d8fed9900606663fbbf4ea420ed8e944f9c18", s: "53c97c74d2f6d8620d060584dc7886f5f3003684bb249508eb7066215172281a", v: 0, }); }); test("btc seg multi", async () => { const transport = await openTransportReplayer( RecordStore.fromString(` => b001000000 <= 0107426974636f696e06312e332e323301029000 => b001000000 <= 0107426974636f696e06312e332e323201029000 => e040000015058000003180000001800000050000000000000000 <= 4104f004370a593b3cde1511801a1151c86dd09a2f246a3f9ac3ef0b0240c0aeb506feddb0a785f5039c3e3e829db9692364e333256284d0fe312177cb12b88551162131764a4336523431416334685a61704a7863334c5a6e69334e7169445837514562141c248b44b74cbe35a3a92801cfebaf895df8d65f5830264097260c863fc1e59000 => e040000015058000003180000001800000050000000000000000 <= 4104f004370a593b3cde1511801a1151c86dd09a2f246a3f9ac3ef0b0240c0aeb506feddb0a785f5039c3e3e829db9692364e333256284d0fe312177cb12b88551162131764a4336523431416334685a61704a7863334c5a6e69334e7169445837514562141c248b44b74cbe35a3a92801cfebaf895df8d65f5830264097260c863fc1e59000 => e0440002050100000002 <= 9000 => e04480022e02f5f6920fea15dda9c093b565cecbe8ba50160071d9bc8bc3474e09ab25a3367d00000000c03b47030000000000 <= 9000 => e044800204ffffffff <= 9000 => e04480022e023b9b487a91eee1293090cc9aba5acdde99e562e55b135609a766ffec4dd1100a0000000080778e060000000000 <= 9000 => e044800204ffffffff <= 9000 => e04a80002101ecd3e7020000000017a9142397c9bb7a3b8a08368a72b3e58c7bb85055579287 <= 00009000 => e0440080050100000001 <= 9000 => e04480802e02f5f6920fea15dda9c093b565cecbe8ba50160071d9bc8bc3474e09ab25a3367d00000000c03b47030000000019 <= 9000 => e04480801d76a9140a146582553b2f5537e13cef6659e82ed8f69b8f88acffffffff <= 9000 => e04800001b058000003180000001800000050000000000000000000000000001 <= 30440220081d5f82ec23759eaf93519819faa1037faabdc27277c8594f5e8e2ba04cb24502206dfff160629ef1fbae78c74d59bfa8c7d59f873c905b196cf2e3efa2273db988019000 => e0440080050100000001 <= 9000 => e04480802e023b9b487a91eee1293090cc9aba5acdde99e562e55b135609a766ffec4dd1100a0000000080778e060000000019 <= 9000 => e04480801d76a9140a146582553b2f5537e13cef6659e82ed8f69b8f88acffffffff <= 9000 => e04800001b058000003180000001800000050000000000000000000000000001 <= 3145022100c820c90ce84c6567617733cd6409c4b8f7469b863d811a3cdc73bf3fa43912bc0220320b7fd259939a6821d371f2b49a755d1ca588bffb1476fbb2da68907427b54b019000 `) ); const btc = new Btc(transport); const tx1 = btc.splitTransaction( "0100000000010130992c1559a43de1457f23380fefada09124d22594bbeb46ab6e9356e8407d39010000001716001417507f91a6594df7367a0561e4d3df376a829e1fffffffff02c03b47030000000017a9142397c9bb7a3b8a08368a72b3e58c7bb850555792875f810acf0900000017a914813a2e6c7538f0d0afbdeb5db38608804f5d76ab8702483045022100e09ca8a5357623438daee5b7804e73c9209de7c645efd405f13f83420157c48402207d3e4a30f362e062e361967c7afdd45e7f21878a067b661a6635669e620f99910121035606550fd51f6b063b69dc92bd182934a34463f773222743f300d3c7fd3ae47300000000", true ); const tx2 = btc.splitTransaction( "0100000000010176ef6abce7feecefbe1322da6cd21245f2d475a1836f13e99f56847bf7127f7c0100000017160014a4e29e297768fccd19cabc21cced93a6afc803eeffffffff0280778e060000000017a9142397c9bb7a3b8a08368a72b3e58c7bb8505557928795061b51b100000017a914c5cfa33e119f60c7cb40bd6b9cfe9e78b026eb6a8702473044022031f0c72683374275328ef0341ed1f233c55a37e21335f9c111c25645b50d0d4e0220670b833be0f688c237bf4466d2b94c99631ada3557c95a7d13bfbb9177125c340121020879f8616da54f8ac5476b97fbe0329c5a0e4cbd32e22e7348262bdfad99a44200000000", true ); const result = await btc.createPaymentTransactionNew({ inputs: [ [tx1, 0, undefined, undefined], [tx2, 0, undefined, undefined], ], associatedKeysets: ["49'/1'/5'/0/0", "49'/1'/5'/0/0"], changePath: undefined, outputScriptHex: "01ecd3e7020000000017a9142397c9bb7a3b8a08368a72b3e58c7bb85055579287", segwit: true, additionals: [], }); expect(result).toEqual( "01000000000102f5f6920fea15dda9c093b565cecbe8ba50160071d9bc8bc3474e09ab25a3367d00000000171600140a146582553b2f5537e13cef6659e82ed8f69b8fffffffff3b9b487a91eee1293090cc9aba5acdde99e562e55b135609a766ffec4dd1100a00000000171600140a146582553b2f5537e13cef6659e82ed8f69b8fffffffff01ecd3e7020000000017a9142397c9bb7a3b8a08368a72b3e58c7bb85055579287024730440220081d5f82ec23759eaf93519819faa1037faabdc27277c8594f5e8e2ba04cb24502206dfff160629ef1fbae78c74d59bfa8c7d59f873c905b196cf2e3efa2273db988012102f004370a593b3cde1511801a1151c86dd09a2f246a3f9ac3ef0b0240c0aeb50602483045022100c820c90ce84c6567617733cd6409c4b8f7469b863d811a3cdc73bf3fa43912bc0220320b7fd259939a6821d371f2b49a755d1ca588bffb1476fbb2da68907427b54b012102f004370a593b3cde1511801a1151c86dd09a2f246a3f9ac3ef0b0240c0aeb50600000000" ); }); test("btc sign p2sh seg", async () => { const transport = await openTransportReplayer( RecordStore.fromString(` => e0440002050100000001 <= 9000 => e04480022e021ba3852a59cded8d2760434fa75af58a617b21e4fbe1cf9c826ea2f14f80927d00000000102700000000000000 <= 9000 => e044800204ffffffff <= 9000 => e04a8000230188130000000000001976a9140ae1441568d0d293764a347b191025c51556cecd88ac <= 00009000 => e0440080050100000001 <= 9000 => e04480802e021ba3852a59cded8d2760434fa75af58a617b21e4fbe1cf9c826ea2f14f80927d00000000102700000000000047 <= 9000 => e0448080325121026666422d00f1b308fc7527198749f06fedb028b979c09f60d0348ef79c985e41210384257cf895f1ca492bbee5d748 <= 9000 => e0448080195ae0ef479036fdf59e15b92e37970a98d6fe7552aeffffffff <= 9000 => e04800001303800000000000000000000000000000000001 <= 3045022100932934ee326c19c81b72fb03cec0fb79ff980a8076639f77c7edec35bd59da1e02205e4030e8e0fd2405f6db2fe044c49d3f191adbdc0e05ec7ed4dcc4c6fe7310e5019000 `) ); const btc = new Btc(transport); const tx1 = btc.splitTransaction( "0100000001d3a05cd6e15582f40e68bb8b1559dc9e5b3e4f9f34d92c1217dc8c3355bc844e010000008a47304402207ab1a4768cbb036d4bce3c4a294c13cc5ae6076fc7bedce88c62aa80ae366da702204f8fea6923f8df36315c0c26cb42d8d7ab52ca4736776816e10d6ce51906d0600141044289801366bcee6172b771cf5a7f13aaecd237a0b9a1ff9d769cabc2e6b70a34cec320a0565fb7caf11b1ca2f445f9b7b012dda5718b3cface369ee3a034ded6ffffffff02102700000000000017a9141188cc3c265fbc01a025fc8adec9823effd0cef187185f9265170100001976a9140ae1441568d0d293764a347b191025c51556cecd88ac00000000", true ); const result = await btc.signP2SHTransaction({ inputs: [ [ tx1, 0, "5121026666422d00f1b308fc7527198749f06fedb028b979c09f60d0348ef79c985e41210384257cf895f1ca492bbee5d7485ae0ef479036fdf59e15b92e37970a98d6fe7552ae", undefined, ], ], associatedKeysets: ["0'/0/0"], outputScriptHex: "0188130000000000001976a9140ae1441568d0d293764a347b191025c51556cecd88ac", segwit: true, }); expect(result).toEqual([ "3045022100932934ee326c19c81b72fb03cec0fb79ff980a8076639f77c7edec35bd59da1e02205e4030e8e0fd2405f6db2fe044c49d3f191adbdc0e05ec7ed4dcc4c6fe7310e501", ]); }); test("signMessage", async () => { const transport = await openTransportReplayer( RecordStore.fromString(` => e04e00011d058000002c800000008000000000000000000000000006666f6f626172 <= 00009000 => e04e80000100 <= 314402205eac720be544d3959a760d9bfd6a0e7c86d128fd1030038f06d85822608804e20220385d83273c9d03c469596292fb354b07d193034f83c2633a4c1f057838e12a5b9000 `) ); const btc = new Btc(transport); const res = await btc.signMessageNew( "44'/0'/0'/0/0", Buffer.from("foobar").toString("hex") ); expect(res).toEqual({ v: 1, r: "5eac720be544d3959a760d9bfd6a0e7c86d128fd1030038f06d85822608804e2", s: "385d83273c9d03c469596292fb354b07d193034f83c2633a4c1f057838e12a5b", }); }); function testBackend(s: string): any { return async () => { return { publicKey: s, bitcoinAddress: "", chainCode: "" }; } } class TestBtc extends Btc { n: BtcNew; o: BtcOld; constructor(public tr: Transport) { super(tr); this.n = new BtcNew(new TestingClient(tr)); this.n.getWalletPublicKey = testBackend("new"); this.o = new BtcOld(tr); this.o.getWalletPublicKey = testBackend("old"); } protected new(): BtcNew { return this.n; } protected old(): BtcOld { return this.o; } } // test.each` // a | b | expected // ${1} | ${1} | ${2} // ${1} | ${2} | ${3} // ${2} | ${1} | ${3} // `('returns $expected when $a is added $c', ({ a, c, expected }) => { // expect(a + c).toBe(expected); // }); test.each` app | ver | path | format | display | exp ${"Bitcoin"} | ${"1.99.99"} | ${"m/44'/0'/1'"} | ${"bech32m"} | ${false} | ${""} ${"Bitcoin"} | ${"1.99.99"} | ${"m/44'/0'"} | ${"bech32m"} | ${false} | ${""} ${"Bitcoin"} | ${"2.0.0-alpha1"} | ${"m/44'/0'/1'"} | ${"bech32m"} | ${false} | ${"new"} ${"Bitcoin"} | ${"2.0.0-alpha1"} | ${"m/44'/0'"} | ${"bech32m"} | ${false} | ${"new"} ${"Bitcoin"} | ${"2.0.0-alpha1"} | ${"m/44'/0'/1'"} | ${"bech32"} | ${false} | ${"new"} ${"Bitcoin"} | ${"2.0.0-alpha1"} | ${"m/44'/0'"} | ${"bech32"} | ${undefined} | ${"old"} ${"Bitcoin"} | ${"2.0.0-alpha1"} | ${"m/44'/0'"} | ${"bech32"} | ${true} | ${"new"} `("dispatch $app $ver $path $format $display to $exp", async ({ app, ver, path, format, display, exp }) => { const appName = Buffer.of(app.length) .toString("hex") .concat(Buffer.from(app, "ascii").toString("hex")); const appVersion = Buffer.of(ver.length) .toString("hex") .concat(Buffer.from(ver, "ascii").toString("hex")); const resp = `01${appName}${appVersion}01029000`; const tr = await openTransportReplayer(RecordStore.fromString(`=> b001000000\n <= ${resp}`)); const btc = new TestBtc(tr); try { const key = await btc.getWalletPublicKey(path, { format: format, verify: display }); if (exp === "") { expect(1).toEqual(0); // Allways fail. Don't know how to do that properly } expect(key.publicKey).toEqual(exp); } catch (e: any) { if (exp != "") { throw e; } expect(exp).toEqual(""); } }) // test("getWalletPublicKey compatibility for internal hardened keys", async () => { // await testDispatch("Bitcoin", "1.99.99", "m/44'/0'/1'", "bech32m", ""); // await testDispatch("Bitcoin", "1.99.99", "m/44'/0'", "bech32m", ""); // await testDispatch("Bitcoin", "2.0.0-alpha1", "m/44'/0'/1'", "bech32m", "new"); // await testDispatch("Bitcoin", "2.0.0-alpha1", "m/44'/0'", "bech32m", "new"); // await testDispatch("Bitcoin", "2.0.0-alpha1", "m/44'/0'/1'", "bech32", "new"); // await testDispatch("Bitcoin", "2.0.0-alpha1", "m/44'/0'", "bech32", "old"); // }); async function testDispatch(name: string, version: string, path: string, addressFormat: AddressFormat | undefined, exp: string): Promise<void> { }
the_stack
import AceConfig from "@wowts/ace_config-3.0"; import AceConfigDialog from "@wowts/ace_config_dialog-3.0"; import { l } from "../ui/Localization"; import { OvaleClass } from "../Ovale"; import { AstNode, AstAnnotation, OvaleASTClass } from "../engine/ast"; import { Controls } from "../engine/controls"; import { format, gmatch, gsub, lower, match, sub } from "@wowts/string"; import { ipairs, pairs, tonumber, type, wipe, LuaObj, LuaArray, lualength, truthy, kpairs, } from "@wowts/lua"; import { concat, insert, sort } from "@wowts/table"; import { RAID_CLASS_COLORS, ClassId } from "@wowts/wow-mock"; import { isLuaArray } from "../tools/tools"; import { OvaleOptionsClass } from "../ui/Options"; import { Annotation, Profile, ParseNode, consumableItems, ovaleIconTags, classInfos, ActionListParseNode, DbcData, } from "./definitions"; import { OvaleDataClass } from "../engine/data"; import { Emiter } from "./emiter"; import { printRepeat, toOvaleFunctionName, toOvaleTaggedFunctionName, outputPool, toLowerSpecialization, toCamelCase, } from "./text-tools"; import { Parser } from "./parser"; import { Unparser } from "./unparser"; import { DebugTools, Tracer } from "../engine/debug"; import { OvaleCompileClass } from "../engine/compile"; import { Splitter } from "./splitter"; import { Generator, markNode, sweepNode } from "./generator"; import { AceModule } from "@wowts/tsaddon"; import { OptionUiAll } from "../ui/acegui-helpers"; let lastSimC = ""; let lastScript = ""; const name = "OvaleSimulationCraft"; export class OvaleSimulationCraftClass { private tracer: Tracer; private module: AceModule; constructor( private ovaleOptions: OvaleOptionsClass, private ovaleData: OvaleDataClass, private emiter: Emiter, private ovaleAst: OvaleASTClass, private parser: Parser, private unparser: Unparser, private ovaleDebug: DebugTools, private ovaleCompile: OvaleCompileClass, private splitter: Splitter, private generator: Generator, private ovale: OvaleClass, private controls: Controls ) { this.registerOptions(); this.module = ovale.createModule( "OvaleSimulationCraft", this.handleInitialize, this.handleDisable ); this.tracer = ovaleDebug.create("SimulationCraft"); } public addSymbol(annotation: Annotation, symbol: string) { const symbolTable = annotation.symbolTable || {}; const symbolList = annotation.symbolList; if (!symbolTable[symbol] && !this.ovaleData.defaultSpellLists[symbol]) { symbolTable[symbol] = true; symbolList[lualength(symbolList) + 1] = symbol; } annotation.symbolTable = symbolTable; annotation.symbolList = symbolList; } private registerOptions() { const actions: LuaObj<OptionUiAll> = { simc: { name: "SimulationCraft", type: "execute", func: function () { const appName = name; AceConfigDialog.SetDefaultSize(appName, 700, 550); AceConfigDialog.Open(appName); }, }, }; for (const [k, v] of pairs(actions)) { this.ovaleOptions.actions.args[k] = v; } const defaultDB = { overrideCode: "", }; for (const [k, v] of pairs(defaultDB)) { (<any>this.ovaleOptions.defaultDB.profile)[k] = v; } } private handleInitialize = () => { this.emiter.initializeDisambiguation(); this.createOptions(); }; private handleDisable = () => {}; // DebuggingInfo() { // self_pool.DebuggingInfo(); // self_childrenPool.DebuggingInfo(); // self_outputPool.DebuggingInfo(); // } toString(tbl: AstNode) { const output = printRepeat(tbl); return concat(output, "\n"); } release(profile: Profile) { if (profile.annotation) { const annotation = profile.annotation; if (annotation.astAnnotation) { this.ovaleAst.releaseAnnotation(annotation.astAnnotation); } if (annotation.nodeList) { this.parser.release(annotation.nodeList); } for (const [key, value] of kpairs(annotation)) { if (type(value) == "table") { wipe(value); } delete annotation[key]; } } wipe(profile); } private readProfile(simc: string) { const parsedProfile: LuaObj<any> = {}; for (const _line of gmatch(simc, "[^\r\n]+")) { const [line] = match(_line, "^%s*(.-)%s*$"); if (!(truthy(match(line, "^#.*")) || truthy(match(line, "^$")))) { const [k, operator, value] = match(line, "([^%+=]+)(%+?=)(.*)"); const key = <keyof Profile>k; if (operator == "=") { (<any>parsedProfile)[key] = value; } else if (operator == "+=") { if (type(parsedProfile[key]) != "table") { const oldValue = parsedProfile[key]; (<any>parsedProfile[key]) = {}; insert(<LuaArray<any>>parsedProfile[key], oldValue); } insert(<LuaArray<any>>parsedProfile[key], value); } } } for (const [k, v] of kpairs(parsedProfile)) { if (isLuaArray(v)) { (<any>parsedProfile)[k] = concat(<any>v); } } parsedProfile.templates = {}; for (const [k] of kpairs(parsedProfile)) { if (sub(<string>k, 1, 2) == "$(" && sub(<string>k, -1) == ")") { insert(parsedProfile.templates, k); } } return parsedProfile as Profile; } parseProfile( simc: string, dictionary?: LuaObj<number | string>, dbc?: DbcData ) { const profile = this.readProfile(simc); let classId: ClassId | undefined = undefined; let name: string | undefined = undefined; for (const [className] of kpairs(RAID_CLASS_COLORS)) { const lowerClass = <keyof Profile>lower(<string>className); if (profile[lowerClass]) { classId = className as ClassId; name = <string>profile[lowerClass]; } } if (!classId || !name || !profile.spec) { return undefined; } const annotation = new Annotation( this.ovaleData, name, classId, profile.spec ); if (dbc) annotation.dbc = dbc; if (dictionary) annotation.dictionary = dictionary; profile.annotation = annotation; let ok = true; // Parse the different "actions" commands in the script. Save them as ParseNode action_list const nodeList: LuaArray<ParseNode> = {}; const actionList: LuaArray<ActionListParseNode> = {}; for (const [k, _v] of kpairs(profile)) { let v = _v; if (ok && truthy(match(k, "^actions"))) { let [name] = match(k, "^actions%.([%w_]+)"); if (!name) { name = "_default"; } for ( let index = lualength(profile.templates); index >= 1; index += -1 ) { const template = profile.templates[index]; const variable = sub(template, 3, -2); const pattern = `%$%(${variable}%)`; v = gsub(<string>v, pattern, <string>profile[template]); } const node = this.parser.parseActionList( name, <string>v, nodeList, annotation ); if (node) { actionList[lualength(actionList) + 1] = node; } else { this.tracer.error( `Error while parsing action list ${name}` ); break; } } } sort(actionList, function (a, b) { return a.name < b.name; }); annotation.specialization = profile.spec; annotation.level = profile.level; ok = ok && annotation.classId !== undefined && annotation.specialization !== undefined && annotation.level !== undefined; annotation.pet = profile.default_pet; const consumables = annotation.consumables; for (const [k, v] of pairs(consumableItems)) { if (v) { if (profile[<keyof Profile>k] != undefined) { consumables[k] = <string>profile[<keyof Profile>k]; } } } if (profile.role == "tank") { annotation.role = profile.role; annotation.melee = annotation.classId; } else if (profile.role == "spell") { annotation.role = profile.role; annotation.ranged = annotation.classId; } else if (profile.role == "attack" || profile.role == "dps") { annotation.role = "attack"; if (profile.position == "ranged_back") { annotation.ranged = annotation.classId; } else { annotation.melee = annotation.classId; } } annotation.position = profile.position; const taggedFunctionName: LuaObj<boolean> = annotation.taggedFunctionName; for (const [, node] of ipairs(actionList)) { const fname = toOvaleFunctionName(node.name, annotation); taggedFunctionName[fname] = true; for (const [, tag] of pairs(ovaleIconTags)) { const [bodyName, conditionName] = toOvaleTaggedFunctionName( fname, tag ); if (bodyName && conditionName) { taggedFunctionName[lower(bodyName)] = true; taggedFunctionName[lower(conditionName)] = true; } } } annotation.functionTag = {}; profile.actionList = actionList; profile.annotation = annotation; annotation.nodeList = nodeList; if (!ok) { this.release(profile); return undefined; } return profile; } unparse(profile: Profile) { const output = outputPool.get(); if (profile.actionList) { for (const [, node] of ipairs(profile.actionList)) { output[lualength(output) + 1] = this.unparser.unparse(node) || ""; } } const s = concat(output, "\n"); outputPool.release(output); return s; } emitAST(profile: Profile) { const nodeList = {}; const ast = this.ovaleAst.newNodeWithChildren( "script", profile.annotation.astAnnotation ); const child = ast.child; const annotation = profile.annotation; let ok = true; if (profile.actionList) { if (annotation.astAnnotation) { annotation.astAnnotation.nodeList = nodeList; } else { annotation.astAnnotation = { nodeList: nodeList, definition: annotation.dictionary, }; } this.ovaleDebug.resetTrace(); const dictionaryAnnotation: AstAnnotation = { nodeList: {}, definition: profile.annotation.dictionary, }; const dictionaryFormat = ` Include(ovale_common) Include(ovale_%s_spells) %s `; const dictionaryCode = format( dictionaryFormat, lower(annotation.classId), this.ovaleOptions.db.profile.overrideCode || "" ); const [dictionaryAST] = this.ovaleAst.parseCode( "script", dictionaryCode, dictionaryAnnotation.nodeList, dictionaryAnnotation ); if (dictionaryAST && dictionaryAST.type == "script") { dictionaryAST.annotation = dictionaryAnnotation; annotation.dictionaryAST = dictionaryAST; annotation.dictionary = dictionaryAnnotation.definition; this.ovaleAst.propagateConstants(dictionaryAST); this.ovaleAst.propagateStrings(dictionaryAST); // this.ovaleAst.FlattenParameters(dictionaryAST); this.controls.reset(); this.ovaleCompile.evaluateScript(dictionaryAST, true); } for (const [, node] of ipairs(profile.actionList)) { const addFunctionNode = this.emiter.emitActionList( node, nodeList, annotation, undefined ); if ( addFunctionNode && addFunctionNode.type === "add_function" ) { // Add interrupt if not already added if (node.name === "_default" && !annotation.interrupt) { const defaultInterrupt = classInfos[annotation.classId][ annotation.specialization ]; if (defaultInterrupt && defaultInterrupt.interrupt) { const interruptCall = this.ovaleAst.newNodeWithParameters( "custom_function", annotation.astAnnotation ); interruptCall.name = lower( toLowerSpecialization(annotation) + "InterruptActions" ); annotation.interrupt = annotation.classId; annotation[defaultInterrupt.interrupt] = annotation.classId; insert( addFunctionNode.body.child, 1, interruptCall ); } } const actionListName = gsub(node.name, "^_+", ""); const commentNode = this.ovaleAst.newNode( "comment", annotation.astAnnotation ); commentNode.comment = `## actions.${actionListName}`; child[lualength(child) + 1] = commentNode; for (const [, tag] of pairs(ovaleIconTags)) { const [bodyNode, conditionNode] = this.splitter.splitByTag( tag, addFunctionNode, nodeList, annotation ); if (bodyNode && conditionNode) { child[lualength(child) + 1] = bodyNode; child[lualength(child) + 1] = conditionNode; } } } else { ok = false; break; } } } if (ok) { annotation.supportingFunctionCount = this.generator.insertSupportingFunctions(child, annotation); annotation.supportingInterruptCount = (annotation.interrupt && this.generator.insertInterruptFunctions( child, annotation )) || undefined; annotation.supportingControlCount = this.generator.insertSupportingControls(child, annotation); // annotation.supportingDefineCount = InsertSupportingDefines(child, annotation); this.generator.insertVariables(child, annotation); const [className, specialization] = [ annotation.classId, annotation.specialization, ]; const lowerclass = lower(className); const aoeToggle = `opt_${lowerclass}_${specialization}_aoe`; { const commentNode = this.ovaleAst.newNode( "comment", annotation.astAnnotation ); commentNode.comment = `## ${toCamelCase( specialization )} icons.`; insert(child, commentNode); const code = format( "AddCheckBox(%s L(AOE) default enabled=(specialization(%s)))", aoeToggle, specialization ); const [node] = this.ovaleAst.parseCode( "checkbox", code, nodeList, annotation.astAnnotation ); if (node) insert(child, node); } { const fmt = ` AddIcon enabled=(not checkboxon(%s) and specialization(%s)) enemies=1 help=shortcd { %s } `; const code = format( fmt, aoeToggle, specialization, this.generator.generateIconBody("shortcd", profile) ); const [node] = this.ovaleAst.parseCode( "icon", code, nodeList, annotation.astAnnotation ); if (node) insert(child, node); } { const fmt = ` AddIcon enabled=(checkboxon(%s) and specialization(%s)) help=shortcd { %s } `; const code = format( fmt, aoeToggle, specialization, this.generator.generateIconBody("shortcd", profile) ); const [node] = this.ovaleAst.parseCode( "icon", code, nodeList, annotation.astAnnotation ); if (node) insert(child, node); } { const fmt = ` AddIcon enemies=1 help=main enabled=(specialization(%s)) { %s } `; const code = format( fmt, specialization, this.generator.generateIconBody("main", profile) ); const [node] = this.ovaleAst.parseCode( "icon", code, nodeList, annotation.astAnnotation ); if (node) insert(child, node); } { const fmt = ` AddIcon help=aoe enabled=(checkboxon(%s) and specialization(%s)) { %s } `; const code = format( fmt, aoeToggle, specialization, this.generator.generateIconBody("main", profile) ); const [node] = this.ovaleAst.parseCode( "icon", code, nodeList, annotation.astAnnotation ); if (node) insert(child, node); } { const fmt = ` AddIcon enemies=1 help=cd enabled=(not checkboxon(%s) and specialization(%s)) { %s } `; const code = format( fmt, aoeToggle, specialization, this.generator.generateIconBody("cd", profile) ); const [node] = this.ovaleAst.parseCode( "icon", code, nodeList, annotation.astAnnotation ); if (node) insert(child, node); } { const fmt = ` AddIcon enabled=(checkboxon(%s) and specialization(%s)) help=cd { %s } `; const code = format( fmt, aoeToggle, specialization, this.generator.generateIconBody("cd", profile) ); const [node] = this.ovaleAst.parseCode( "icon", code, nodeList, annotation.astAnnotation ); if (node) insert(child, node); } markNode(ast); let [changed] = sweepNode(ast); while (changed) { markNode(ast); [changed] = sweepNode(ast); } markNode(ast); sweepNode(ast); } if (!ok) { this.ovaleAst.release(ast); return undefined; } return ast; } emit(profile: Profile, noFinalNewLine?: boolean) { const ast = this.emitAST(profile); if (!ast) return "error"; const annotation = profile.annotation; const className = annotation.classId; const lowerclass = lower(className); const specialization = annotation.specialization; const output = outputPool.get(); { output[ lualength(output) + 1 ] = `# Based on SimulationCraft profile ${annotation.name}.`; output[lualength(output) + 1] = `# class=${lowerclass}`; output[lualength(output) + 1] = `# spec=${specialization}`; if (profile.talents) { output[lualength(output) + 1] = `# talents=${profile.talents}`; } if (profile.glyphs) { output[lualength(output) + 1] = `# glyphs=${profile.glyphs}`; } if (profile.default_pet) { output[lualength(output) + 1] = `# pet=${profile.default_pet}`; } } { output[lualength(output) + 1] = ""; output[lualength(output) + 1] = "Include(ovale_common)"; output[lualength(output) + 1] = format( "Include(ovale_%s_spells)", lowerclass ); const overrideCode = this.ovaleOptions.db.profile.overrideCode; if (overrideCode && overrideCode != "") { output[lualength(output) + 1] = ""; output[lualength(output) + 1] = "# Overrides."; output[lualength(output) + 1] = overrideCode; } if ( annotation.supportingControlCount && annotation.supportingControlCount > 0 ) { output[lualength(output) + 1] = ""; } } output[lualength(output) + 1] = this.ovaleAst.unparse(ast); if (profile.annotation.symbolTable) { output[lualength(output) + 1] = ""; output[lualength(output) + 1] = "### Required symbols"; sort(profile.annotation.symbolList); for (const [, symbol] of ipairs(profile.annotation.symbolList)) { if ( !tonumber(symbol) && !profile.annotation.dictionary[symbol] && !this.ovaleData.buffSpellList[symbol] ) { this.tracer.print( "Warning: Symbol '%s' not defined", symbol ); } output[lualength(output) + 1] = `# ${symbol}`; } } annotation.dictionary = {}; if (annotation.dictionaryAST) { this.ovaleAst.release(annotation.dictionaryAST); } if (!noFinalNewLine && output[lualength(output)] != "") { output[lualength(output) + 1] = ""; } const s = concat(output, "\n"); outputPool.release(output); this.ovaleAst.release(ast); return s; } createOptions() { const options = { name: `${this.ovale.GetName()} SimulationCraft`, type: "group", args: { input: { order: 10, name: l["input"], type: "group", args: { description: { order: 10, name: `${l["simulationcraft_profile_content"]}\nhttps://code.google.com/p/simulationcraft/source/browse/profiles`, type: "description", }, input: { order: 20, name: l["simulationcraft_profile"], type: "input", multiline: 25, width: "full", get: () => { return lastSimC; }, set: (info: any, value: string) => { lastSimC = value; const profile = this.parseProfile(lastSimC); let code = ""; if (profile) { code = this.emit(profile); } lastScript = gsub(code, "\t", " "); }, }, }, }, overrides: { order: 20, name: l["overrides"], type: "group", args: { description: { order: 10, name: l["simulationcraft_overrides_description"], type: "description", }, overrides: { order: 20, name: l["overrides"], type: "input", multiline: 25, width: "full", get: () => { const code = this.ovaleOptions.db.profile.code; return gsub(code, "\t", " "); }, set: (info: any, value: string) => { this.ovaleOptions.db.profile.overrideCode = value; if (lastSimC) { const profile = this.parseProfile(lastSimC); let code = ""; if (profile) { code = this.emit(profile); } lastScript = gsub(code, "\t", " "); } }, }, }, }, output: { order: 30, name: l["output"], type: "group", args: { description: { order: 10, name: l["simulationcraft_profile_translated"], type: "description", }, output: { order: 20, name: l["script"], type: "input", multiline: 25, width: "full", get: function () { return lastScript; }, }, }, }, }, }; const appName = this.module.GetName(); AceConfig.RegisterOptionsTable(appName, options); AceConfigDialog.AddToBlizOptions( appName, "SimulationCraft", this.ovale.GetName() ); } }
the_stack
export const LATEST_VERSION_ID = 3; export const COOKIE_VERSION = 'VERSION_0_7_0'; // To be changed with each release. export const dummyImg = 'https://via.placeholder.com/725x278'; // for youtube video make isImage = false and path = {video embed id} // embed:- youtube video => share => click on embed and take {url with id} from it export const WHATS_NEW = [ { id: 0, version: 'v0.4.0', description: 'Released on 20 Sept 2021.', features: [ { title: 'Dashboards', description: 'In 0.4.0 release, Users can now integrate dashboard services, such as Apache Superset, Tableau, and Looker, and discover dashboards and charts in their organizations in a single place along with other data assets., Similar to Tables and Databases, users can describe the dashboard, tier them, add tags, and ownership.', isImage: false, path: 'https://www.youtube.com/embed/131LfI0eMNc', }, { title: 'Messaging service', description: 'Users can also integrate with messaging services, such as Apache Kafka (and Apache Pulsar in progress) to discover Topics. Our Message Queue connectors extractTopic configurations, cluster information, and schemas from Apache Kafka and Confluent’s Schema Registry to provide all important information at your fingertips. Users can provide rich descriptions, tiering, ownership, and tags to the topics through the UI or APIs.', isImage: false, path: 'https://www.youtube.com/embed/vHM99KC2A2w', }, { title: 'Data Profiler & Sample Data', description: 'The Data Profiler is a new feature that generates a data profile for a table during the ingestion process. The data profile will include information that will help understand data quality, such as data uniqueness, null counts, max and min, etc. The Data Sampler will collect sample data from an ingested table so that it can be subsequently used to get a sense of the data', isImage: false, path: 'https://www.youtube.com/embed/0NKBPWUcG9M', }, ], changeLogs: { OpenMetadata: `- Support for Kafka (and Pulsar WIP)\n- Support for Message Service and Topic entities in schemas, APIs, and UI\n- Kafka connector and ingestion support for Confluent Schema Registry\n- Support for Dashboards\n- Support for Dashboard services, Dashboards, and Charts entities in schemas, APIs, and UI\n- Looker, Superset, Tableau connector, and ingestion support`, 'Data Quality': `- Data Profiler - The Data Profiler is a new feature that generates a data profile for a table during the ingestion process. The data profile will include information that will help understand data quality, such as data uniqueness, null counts, max and min\n - Sample Data, The Data Sampler will collect sample data from an ingested table so that it can be subsequently used to get a sense of the data.`, 'Other features': `- Pluggable SSO integration - Auth0 support\n- Support for Presto`, 'User Interface': `- Sort search results based on Usage, Relevance, and Last updated time\n- Search string highlighted in search results\n- Support for Kafka and Dashboards from Looker, SuperSet, and Tableau`, 'Work in progress': `- Salesforce CRM connector\n- Data profiler to profile tables in ingestion framework and show it table details page\n- Redash dashboard connector`, }, }, { id: 1, version: 'v0.5.0', description: 'Released on 19 Oct 2021.', features: [ { title: 'Lineage', description: 'Schema and API support for Lineage.\n\nUI integration to show the lineage for Pipelines and Tables.\n\nIngestion support for Airflow to capture lineage.', isImage: false, path: 'https://www.youtube.com/embed/8-CwuKsf8Oc', }, { title: 'Data Profiler', description: 'In 0.5 release we are enhancing data profiler integration. UI now visualizes data profiler details. Users can understand column data in a table.', isImage: false, path: 'https://www.youtube.com/embed/FRP_bgWbZCc', }, { title: 'Pipelines', description: 'Pipelines are new entity addition to OpenMetadata. Add Airflow as a service ingest all pipelines metadata into OpenMetadata. Explore and Discover all your pipelines in single place.', isImage: false, path: 'https://www.youtube.com/embed/V7rYKdJe67U', }, { title: 'Complex Types', description: 'With 0.5 release we are supporting Complex Types in table schema through APIs and ingestion now supports Redshift, BigQuery, Snowflake, Hive to extract complex data types. UI Integration will allow users to expand and add description, tags to nested fields.', isImage: false, path: 'https://www.youtube.com/embed/35XfeP2--b4', }, { title: 'Trino & Redash', description: 'We added two new connectors, Trino and Redash.', isImage: false, path: 'https://www.youtube.com/embed/Tugbk6_uELY', }, ], changeLogs: { Lineage: `- Schema and API support for Lineage\n- UI integration to show the lineage for Pipelines and Tables\n- Ingestion support for Airflow to capture lineage`, 'Data Reliability': `- UI Integration for Data profiler\n- Unique , Null proportion\n- See how the table data grows through interactive visualization`, 'New Entities: Pipeline': `- Add Apache Airflow as a pipeline service\n- Ingest all of your pipeline's metadata into OpenMetadata\n- Explore and Search Pipelines\n- Add description, tags, ownership and tier your pipelines`, 'Complex Data types': `- Schema and API support to capture complex data types\n- Ingestion support to capture complex data types from Redshift, BigQuery, Snowflake and Hive\n- UI Support for nested complex data types, users can add description, tags to nested fields`, 'New Connectors': `- Trino connector\n- Redash connector\n- Amazon Glue - In progress`, 'User Interface': `- UI now completely built on top of JsonSchema generated code\n- Expand complex data types and allow users to update descriptions and tags\n- Pipeline Service and Details page\n- Pipeline Explore & Search integration\n- Search results will show if the query matches description or column names, description `, }, }, { id: 2, version: 'v0.6.0', description: 'Released on 17 Nov 2021.', features: [ { title: 'Metadata Versioning', description: 'OpenMetadata captures the changes in metadata as new versions of an entity. The version history for all entities is maintained in the Major.Minor number.', isImage: false, path: 'https://www.youtube.com/embed/0O0IbGerHtA', }, { title: 'One-Click Deployment of Ingestion Pipelines', description: 'OpenMetadata is providing a UI integration with Apache Airflow as a workflow engine to run ingestion, data profiling, data quality and other automation jobs.', isImage: false, path: 'https://www.youtube.com/embed/eDTDT_ZLeyk', }, ], changeLogs: { 'Metadata Versioning': `- OpenMetadata captures the changes in metadata as new versions of an entity.\n- The version history for all entities is maintained in the _Major.Minor_ number.\n- The initial version of an entity is 0.1\n- A backward compatible change will result in a _Minor_ version change (e.g., from 0.1 to 0.2)\n- A backward incompatible changes result in a _Major_ version change (e.g., from 0.2 to 1.2)\n- Timeline visualization tracks all the metadata changes from version to version.\n- Built _Versions_ APIs for developers to access a list of all versions, and also to get a specific version of an entity.\n- Helps debugging as users can identify changes that led to a data issue.\n- Helps crowdsourcing and collaboration within organizations as more users can be given access to change metadata and to be held accountable.`, 'Events API': `- When the state of metadata changes, an event is produced that indicates which entity changed, who changed it, and how it changed.\n- Events can be used to integrate metadata into other tools, or to trigger actions.\n- Followers of data assets can be notified of events that interest them.\n- Alerts can be sent to followers and downstream consumers about table schema changes, or backward incompatible changes, like when a column is deleted.\n- Events can be used to build powerful apps and automation that respond to the changes from activities.\n- See issue-[1138](https://github.com/open-metadata/OpenMetadata/issues/1138) for more details about this feature.`, 'One-Click Deployment of Ingestion Pipelines': `- OpenMetadata is providing a UI integration with Apache Airflow as a workflow engine to run ingestion, data profiling, data quality and other automation jobs.\n- From the UI, admins can configure a service to run the OpenMetadata pipelines, and add an ingestion schedule to automatically kick off the ingestion jobs.\n- This deploys a workflow onto the cluster.\n- This forms the basis for all the future automation workflows.`, 'New Entities: ML Models and Data Models': `- Two new data assets have been added - ML Models and Data Models.\n- ML Models are algorithms trained on data to find patterns or to make predictions.\n- We’ve added support for dbt to get the data models into OpenMetadata, so that users get to see what models are being used to generate the tables.`, 'New Connectors': `- AWS Glue\n- DBT\n- Maria DB`, 'User Interface': `- UI displays all the metadata changes of an entity over time as Version History. Clicking on the Version button, users can view the change log of an entity from the very beginning.\n- The UI supports setting up metadata ingestion workflows.\n- Improvements have been made in drawing the entity node details for lineage.\n- Entity link is supported for each tab on the details page.\n- Guided steps have been added for setting up ElasticSearch.\n- The entity details, search results page (Explore), landing pages, and components have been redesigned for better project structure and code maintenance.`, 'OpenMetadata Quickstart': '- Shipped a Python package to simplify OpenMetadata docker installation.\n<code class="tw-bg-grey-muted-lite tw-text-grey-body tw-font-medium">pip install openmetadata-ingestion[docker]\n\nmetadata docker --run</code>', 'Helm Charts': `- Installing OpenMetadata in your cloud provider or on-premise got easier.\n- We worked on Helm charts to get the OpenMetadata and dependencies up and running on Kubernetes.`, 'Other Features': '- Upgraded from JDBI 2 to JDBI 3, which will support newer versions.', }, }, { id: 3, version: 'v0.7.0', description: 'Released on 15 Dec 2021.', features: [ { title: 'New Home Screen', description: 'New and improved UX has been implemented for search and its resulting landing pages.', isImage: false, path: 'https://www.youtube.com/embed/PMc7huRR5HQ', }, { title: 'Change Activity Feeds', description: 'Enables users to view a summary of the metadata change events. The most recent changes are listed at the top.', isImage: false, path: 'https://www.youtube.com/embed/xOQMvn3iPhM', }, { title: 'Lineage Updates', description: 'Improved discoverability. Implemented incremental loading to lineage.', isImage: false, path: 'https://www.youtube.com/embed/dWc73gWryDw', }, { title: 'DBT Integration', description: 'DBT integration enables users to see what models are being used to generate tables.', isImage: false, path: 'https://www.youtube.com/embed/tQ6iBBnzpGc', }, { title: 'Automatic Indexing', description: 'SSL-enabled Elasticsearch (including self-signed certs) is supported. Automatically runs an indexing workflow as new entities are added or updated through ingestion workflows.', isImage: false, path: 'https://www.youtube.com/embed/Znr2UsbKAPk', }, ], changeLogs: { 'Activity Feeds': `- Enables users to view a summary of the metadata change events.\n- The most recent changes are listed at the top.\n- Entities (tables, dashboards, team names) are clickable.\n- Displays 'All Changes' and 'My Changes'.\n- A feed has been provided for data you are 'Following'.`, 'UX Improvements': `- New and improved UX has been implemented for search and its resulting landing pages.\n- The Explore page has an updated UI. Introduced a 3-column layout to present the search results and several visual element improvements to promote readability and navigation of the search results.\n- Users can filter by database name on the Explore page.\n- Support has been added to view the recent search terms.\n- Major version changes for backward incompatible changes are prominently displayed.`, 'DBT Integration': `- DBT integration enables users to see what models are being used to generate tables.\n- DBT models have been associated with Tables and are no longer treated as a separate Entity on the UI.\n- Each DBT model can produce a Table, and all the logic and metadata is now being captured as part of it.\n- DBT model is accessible from a tab in the table view.`, 'Storage Location': `- UI supports StorageLocation.\n- Can extract the location information from Glue.\n- The ingestion framework gets the details from Glue to publish the location information (such as S3 bucket, HDFS) for the external tables.\n- The table results view now displays the table location in addition to the service.`, Elasticsearch: `- SSL-enabled Elasticsearch (including self-signed certs) is supported.\n- Automatically runs an indexing workflow as new entities are added or updated through ingestion workflows.\n- Metadata indexing workflow is still available; in case indexes need to be cleanly created from the ground up.`, 'New Connectors': `- *Metabase*, an open-source BI solution\n- *Apache Druid* has been added to integrate Druid metadata.\n- *MLflow*, an open-source platform for the machine learning lifecycle\n- *Apache Atlas import connector*, imports metadata from Atlas installations into OpenMetadata.\n- *Amundsen import connector*, imports metadata from Amundsen into OpenMetadata.\n- *AWS Glue* - improved to extract metadata for tables and pipelines. Now uses the AWS boto session to get the credentials from the different credential providers, and also allows the common approach to provide credentials. Glue ingestion now supports Location.\n- *MSSQL* now has SSL support.`, 'Lineage View Improvements': `- Improved discoverability\n- Implemented incremental loading to lineage.\n- Users can inspect the Table’s columns.\n- Users can expand entity nodes to view more upstream or downstream lineage.\n- Helps data consumers and producers to assess the impact of changes to the data sources.`, 'Other Features': `- Admins can now access the user listing page, filter users by team, and manage admin privileges\n- Updated the Redoc version to support search in the API, as well as to add query parameter fields fixes.\n- 'Entity Name' character size has been increased to 256.`, }, }, ];
the_stack
"use strict"; // uuid: 95a216ec-8c6f-4254-9a44-fe8795b3ee4f // ------------------------------------------------------------------------ // Copyright (c) 2018 Alexandre Bento Freire. All rights reserved. // Licensed under the MIT License+uuid License. See License.txt for details // ------------------------------------------------------------------------ import * as sysFs from "fs"; import * as sysPath from "path"; import * as sysProcess from "process"; import * as gulp from "gulp"; import * as rimraf from "rimraf"; import * as globule from "globule"; import { exec as sysExec } from "child_process"; import { fsix } from "./shared/vendor/fsix.js"; import { BuildDTsFilesABeamer } from "./shared/dev-builders/build-d-ts-abeamer.js"; import { BuildShared } from "./shared/dev-builders/build-shared.js"; import { BuildSingleLibFile } from "./shared/dev-builders/build-single-lib-file.js"; import { BuildDocsLatest } from "./shared/dev-builders/build-docs-latest.js"; import { BuildGalleryLatest as BuildGalRel } from "./shared/dev-builders/build-gallery-latest.js"; import { DevCfg } from "./shared/dev-config.js"; /** @module developer | This module won't be part of release version */ /** * ## Description * * This gulp file builds the release files, definition files, cleans and * updates data. * * To see all the usages run `gulp` * * @HINT: It's advisable to execute these gulp tasks via `npm run task` * */ namespace Gulp { sysProcess.chdir(__dirname); /** List of files and folders to typical preserve on `rm -rf` */ // const PRESERVE_FILES = ['README.md', 'README-dev.md', '.git', '.gitignore']; const CLIENT_UUID = '// uuid: 3b50413d-12c3-4a6c-9877-e6ead77f58c5\n\n'; const COPYRIGHTS = '' + '// ------------------------------------------------------------------------\n' + '// Copyright (c) 2018 Alexandre Bento Freire. All rights reserved.\n' + '// Licensed under the MIT License+uuid License. See License.txt for details\n' + '// ------------------------------------------------------------------------\n\n'; const gulpMinify = require('gulp-minify'); const gulpReplace = require('gulp-replace'); // const preprocess = require('gulp-preprocess'); const gulpPreserveTime = require('gulp-preservetime'); // const autoprefixer = require('gulp-autoprefixer'); const gulpRename = require('gulp-rename'); const gulpZip = require('gulp-zip'); const gulpSequence = require('gulp-sequence'); const mergeStream = require('merge-stream'); const cfg = DevCfg.getConfig(__dirname); const modulesList = fsix.loadJsonSync(cfg.paths.MODULES_LIST_FILE) as Shared.ModulesList; const libModules = modulesList.libModules; const pluginModules = modulesList.pluginModules; // ------------------------------------------------------------------------ // Print Usage // ------------------------------------------------------------------------ gulp.task('default', () => { console.log(`gulp [task] Where task is bump-version - builds version files from package.json when: before publishing a new version clean - executes clean-gallery-src build-release-latest - builds the release files where all the files are compiled and minify when: before publishing a new **stable** version and after testing build-shared-lib - builds files from the client library to be used by server, tests and cli when: every time a module tagged with @module shared or constants that are useful for server and cli are modified build-docs-latest - builds both the end-user and developer documentation when: before publishing a new **stable** version and after testing post-build-docs-latest - changes links for offline testing and adds other improvements build-definition-files - builds definition files for end-user and developer when: after any public or shared member of a class is modified build-gallery-src-gifs - builds all the animated gifs for each example in the gallery when: before build-gallery-latest warn: this can be a long operation build-gallery-latest - builds release version of the gallery --local builds using local links when: before publishing a new gallery, after build-gallery-src-gifs clean-gallery-src - deletes all the ${cfg.paths.GALLERY_SRC_PATH}/story-frames files and folder when: cleaning day! clean-gallery-src-png - deletes all the ${cfg.paths.GALLERY_SRC_PATH}/story-frames/*.png update-gallery-src-scripts - builds a new version of ` + `${cfg.paths.GALLERY_SRC_PATH}/*/index.html with script list updated when: every time there is a new module on the library or a module change its name first must update on the ${cfg.paths.CLIENT_PATH}/lib/js/modules.json update-test-list - updates test-list.json and package.json with the full list of tests when: every time there is a new test or a test change its name list-docs-files-as-links - outputs the console the list of document files in markdown link format list-paths-macros - lists paths & macros README-to-online - converts all online README.md local links to online links README-to-local - converts all online README.md online links to local links `); }); gulp.task('list-paths-macros', (cb) => { console.log(`cfg.paths: ${JSON.stringify(cfg.paths, undefined, 2)}`); console.log(`cfg.macros: ${JSON.stringify(cfg.macros, undefined, 2)}`); cb(); }); // ------------------------------------------------------------------------ // rimrafExcept // ------------------------------------------------------------------------ /** * Recursive deletes files and folders except the ones defined in the except list * Only the direct children files and folders from the root are allowed * to be in except list * @param root Root folder * @param except list of file */ function rimrafExcept(root: string, except: string[]): void { if (!sysFs.existsSync(root)) { return; } sysFs.readdirSync(root).forEach(fileBase => { if (except.indexOf(fileBase) === -1) { const fileName = `${root}/${fileBase}`; rimraf.sync(`${fileName}`); } }); } // ------------------------------------------------------------------------ // updateHtmlPages // ------------------------------------------------------------------------ /** * Updates the html links. * For release and release-gallery it removes the individual links, * and replaces with the compiled version. * In other cases, just updates links. */ function updateHtmlPages(srcPath: string, destPath: string, newScriptFiles: string[], setReleaseLinks: boolean, srcOptions?: any): NodeJS.ReadWriteStream { return gulp.src(srcPath, srcOptions) .pipe(gulpReplace(/<body>((?:.|\n)+)<\/body>/, (_all, p: string) => { const lines = p.split('\n'); const outLines = []; let state = 0; lines.forEach(line => { if (state < 2) { if (line.match(/lib\/js\/[\w\-]+.js"/)) { state = 1; return; } else if (state === 1 && line.trim()) { newScriptFiles.forEach(srcFile => { outLines.push(` <script src="${srcFile}.js"></script>`); }); state = 2; } } outLines.push(line); }); return '<body>' + outLines.join('\n') + '</body>'; })) .pipe(gulpReplace(/^(?:.|\n)+$/, (all: string) => setReleaseLinks ? all.replace(/\.\.\/\.\.\/client\/lib/g, 'abeamer') : all, )) .pipe(gulp.dest(destPath)); } // ------------------------------------------------------------------------ // Clean // ------------------------------------------------------------------------ (gulp as any).task('clean', ['clean-gallery-src']); // ------------------------------------------------------------------------ // Bump Version // ------------------------------------------------------------------------ gulp.task('bump-version', (cb) => { const SRC_FILENAME = './package.json'; const BADGES_FOLDER = `./${cfg.paths.BADGES_PATH}/`; const WARN_MSG = ` // This file was generated via gulp bump-version // It has no uuid // // @WARN: Don't edit this file. See the ${SRC_FILENAME} \n`; const matches = fsix.readUtf8Sync(SRC_FILENAME).match(/"version": "([\d\.]+)"/); if (!matches) { throw `Unable to find the ${SRC_FILENAME} version`; } const version = matches[1]; const VERSION_OUT = `export const VERSION = "${version}";`; console.log(`${SRC_FILENAME} version is ${version}`); sysFs.writeFileSync('./shared/version.ts', WARN_MSG + VERSION_OUT + '\n'); sysFs.writeFileSync(`./${cfg.paths.JS_PATH}/version.ts`, WARN_MSG + `namespace ABeamer {\n ${VERSION_OUT}\n}\n`); const outBadgeFileBase = `v-${version}.gif`; const outBadgeFileName = `${BADGES_FOLDER}${outBadgeFileBase}`; if (!sysFs.existsSync(outBadgeFileName)) { const path = `${cfg.paths.GALLERY_SRC_PATH}/animate-badges`; const url = `http://localhost:9000/${path}/?var=name%3Dversion&` + `var=value%3D${version}&var=wait%3D2s`; const config = `./${path}/abeamer.ini`; // build animated badges const renderCmdLine = `node ./cli/abeamer-cli.js render --dp --url '${url}' --config ${config}`; console.log(renderCmdLine); fsix.runExternal(renderCmdLine, (_error, _stdout, stderr) => { if (stderr) { console.error(stderr); console.error('Animated Gif Badge Creation Failed'); console.log('Check out if the live server is running'); } else { const gifCmdLine = `node ./cli/abeamer-cli.js gif ./${path}/ --loop 8 --gif ${outBadgeFileName}`; console.log(gifCmdLine); fsix.runExternal(gifCmdLine, (_error2, stdout2, stderr2) => { if (stderr2) { console.error(stderr2); console.error('Animated Gif Badge Creation Failed'); } else { console.log(stdout2); console.error('Animated Gif Badge Created!'); } }); } }); } let vREADMEData = fsix.readUtf8Sync(`./README.md`); vREADMEData = vREADMEData.replace(/v-[\d\.]+\.gif/, outBadgeFileBase); sysFs.writeFileSync(`./README.md`, vREADMEData); fsix.runExternal('gulp build-shared-lib', () => { fsix.runExternal('tsc -p ./', () => { console.log('Version bumped'); cb(); }); }); }); // ------------------------------------------------------------------------ // Build Single Lib // ------------------------------------------------------------------------ const SINGLE_LIB_MODES = [ { folder: 'min', suffix: '', isDebug: false, path: '' }, { folder: 'debug.min', suffix: '-debug', isDebug: true, path: '' }, ].map(mode => { mode.path = `${cfg.paths.SINGLE_LIB_PATH}/${mode.folder}`; return mode; }); gulp.task('bs:clean', (cb) => { rimrafExcept(cfg.paths.SINGLE_LIB_PATH, []); cb(); }); gulp.task('bs:copy', () => { return mergeStream(SINGLE_LIB_MODES.map(mode => gulp.src([ './tsconfig.json', './client/lib/typings/**', '!./client/lib/typings/release/**', ], { base: '.' }) .pipe(gulp.dest(mode.path)), )); }); gulp.task('bs:build-single-ts', () => { SINGLE_LIB_MODES.forEach(mode => { const singleLibFile = `${mode.path}/abeamer${mode.suffix}.ts`; BuildSingleLibFile.build(libModules, cfg.paths.JS_PATH, `${mode.path}`, singleLibFile, 'gulp `build-release-latest`', [ 'Story', // story must always be exported ], mode.isDebug); }); }); gulp.task('bs:compile-single-ts', (cb) => { let finishCount = SINGLE_LIB_MODES.length; SINGLE_LIB_MODES.forEach(mode => { sysExec('tsc -p ./', { cwd: mode.path }, () => { finishCount--; if (!finishCount) { cb(); } }); }); }); gulp.task('build-single-lib-internal', gulpSequence( 'bs:clean', 'bs:copy', 'bs:build-single-ts', 'bs:compile-single-ts', )); // ------------------------------------------------------------------------ // Build Release // ------------------------------------------------------------------------ gulp.task('rel:clean', (cb) => { rimrafExcept(cfg.paths.RELEASE_LATEST_PATH, ['.git']); cb(); }); gulp.task('rel:client', () => { return gulp.src(DevCfg.expandArray(cfg.release.client)) .pipe(gulp.dest(`${cfg.paths.RELEASE_LATEST_PATH}/client`)) .pipe(gulpPreserveTime()); }); gulp.task('rel:jquery-typings', () => { return gulp.src(`node_modules/@types/jquery/**`) .pipe(gulp.dest(`${cfg.paths.RELEASE_LATEST_PATH}/${cfg.paths.TYPINGS_PATH}/vendor/jquery`)) .pipe(gulpPreserveTime()); }); gulp.task('rel:client-js-join', () => { return gulp .src(`${cfg.paths.SINGLE_LIB_PATH}/*/abeamer*.js`) .pipe(gulpMinify({ noSource: true, ext: { min: '.min.js', }, })) .pipe(gulpRename({ dirname: '' })) .pipe(gulpReplace(/^(.)/, CLIENT_UUID + COPYRIGHTS + '$1')) .pipe(gulp.dest(`${cfg.paths.RELEASE_LATEST_PATH}/${cfg.paths.JS_PATH}`)); }); gulp.task('rel:gallery', () => { return gulp.src([ `${cfg.paths.GALLERY_SRC_PATH}/${cfg.release.demosStr}/**`, `!${cfg.paths.GALLERY_SRC_PATH}/**/*.html`, `!${cfg.paths.GALLERY_SRC_PATH}/*/story-frames/*`, ], { base: cfg.paths.GALLERY_SRC_PATH }) .pipe(gulp.dest(`${cfg.paths.RELEASE_LATEST_PATH}/gallery`)) .pipe(gulpPreserveTime()); }); gulp.task('rel:root', () => { return gulp.src(DevCfg.expandArray(cfg.release.root)) .pipe(gulp.dest(cfg.paths.RELEASE_LATEST_PATH)) .pipe(gulpPreserveTime()); }); gulp.task('rel:README', () => { return gulp.src([ 'README.md', ]) .pipe(gulpReplace(/developer-badge\.gif/, 'end-user-badge.gif')) .pipe(gulp.dest(cfg.paths.RELEASE_LATEST_PATH)) .pipe(gulpPreserveTime()); }); gulp.task('rel:gallery-html', () => { return mergeStream( updateHtmlPages(`${cfg.paths.GALLERY_SRC_PATH}/${cfg.release.demosStr}/*.html`, `${cfg.paths.RELEASE_LATEST_PATH}/gallery`, [`../../${cfg.paths.JS_PATH}/abeamer.min`], true, { base: cfg.paths.GALLERY_SRC_PATH }) .pipe(gulpPreserveTime())); }); gulp.task('rel:minify', () => { // not required to preserve timestamp since `rel:add-copyrights` does the job return gulp.src(DevCfg.expandArray(cfg.jsFiles), { base: '.' }) .pipe(gulpMinify({ noSource: true, ext: { min: '.js', }, })) .pipe(gulp.dest(`${cfg.paths.RELEASE_LATEST_PATH}`)); }); gulp.task('rel:add-copyrights', (cb) => { globule.find(DevCfg.expandArray(cfg.jsFiles)).forEach(file => { const srcFileContent = fsix.readUtf8Sync(file); const uuidMatches = srcFileContent.match(/uuid:\s*([\w\-]+)/); if (uuidMatches) { const dstFileName = `${cfg.paths.RELEASE_LATEST_PATH}/${file}`; let content = fsix.readUtf8Sync(dstFileName); content = content.replace(/("use strict";)/, (all) => `${all}\n// uuid: ${uuidMatches[1]}\n` + COPYRIGHTS, ); sysFs.writeFileSync(dstFileName, content); const stat = sysFs.statSync(file); sysFs.utimesSync(dstFileName, stat.atime, stat.mtime); } }); cb(); }); // copies package.json cleaning the unnecessary config gulp.task('rel:build-package.json', () => { return gulp.src('./package.json') .pipe(gulpReplace(/^((?:.|\n)+)$/, (_all, p) => { const pkg = JSON.parse(p); // removes all dependencies pkg.devDependencies = {}; // removes unnecessary scripts const scripts = {}; ['compile', 'watch', 'abeamer', 'serve'].forEach(key => { scripts[key] = pkg.scripts[key]; }); pkg.scripts = scripts; // sets only the repo for the release version. // homepage and issue will remain intact // pkg.repository.url = pkg.repository.url + '-release'; return JSON.stringify(pkg, undefined, 2); })) .pipe(gulp.dest(`${cfg.paths.RELEASE_LATEST_PATH}`)) .pipe(gulpPreserveTime()); }); // copies tsconfig.ts to each demo cleaning the unnecessary config gulp.task('rel:build-tsconfig.ts', () => { return mergeStream( cfg.release.demos.map(demo => { return gulp.src('./tsconfig.json') .pipe(gulpReplace(/^((?:.|\n)+)$/, (_all, p) => { const tsconfig = JSON.parse(p); tsconfig.exclude = []; tsconfig["tslint.exclude"] = undefined; return JSON.stringify(tsconfig, undefined, 2); })) .pipe(gulp.dest(`${cfg.paths.RELEASE_LATEST_PATH}/gallery/${demo}`)) .pipe(gulpPreserveTime()); })); }); // creates a plugin list from modules-list.json // don't use gulp-file in order to preserve the time-date gulp.task('rel:build-plugins-list.json', () => { return gulp.src(cfg.paths.MODULES_LIST_FILE) .pipe(gulpReplace(/^((?:.|\n)+)$/, () => { return JSON.stringify(pluginModules, undefined, 2); })) .pipe(gulpRename('plugins-list.json')) .pipe(gulp.dest(`${cfg.paths.RELEASE_LATEST_PATH}/${cfg.paths.PLUGINS_PATH}`)) .pipe(gulpPreserveTime()); }); // joins abeamer.d.ts and abeamer-release.d.ts in a single file gulp.task('rel:build-abeamer.d.ts', () => { return gulp.src(`${cfg.paths.TYPINGS_PATH}/abeamer.d.ts`) .pipe(gulpReplace(/declare namespace ABeamer \{/, (all) => { const releaseDTs = fsix.readUtf8Sync(`${cfg.paths.TYPINGS_PATH}/release/abeamer-release.d.ts`); return all + releaseDTs .replace(/^(?:.|\n)*declare namespace ABeamer \{/, '') .replace(/}(?:\s|\n)*$/, ''); })) .pipe(gulp.dest(`${cfg.paths.RELEASE_LATEST_PATH}/${cfg.paths.TYPINGS_PATH}`)) .pipe(gulpPreserveTime()); }); gulp.task('build-release-latest-internal', gulpSequence( 'build-single-lib-internal', 'rel:clean', 'rel:client', 'rel:gallery', 'rel:gallery-html', 'rel:client-js-join', 'rel:root', 'rel:README', 'rel:minify', 'rel:add-copyrights', 'rel:jquery-typings', 'rel:build-package.json', 'rel:build-tsconfig.ts', 'rel:build-abeamer.d.ts', 'rel:build-plugins-list.json', )); // ------------------------------------------------------------------------ // Builds Shared Modules from Client // ------------------------------------------------------------------------ gulp.task('build-shared-lib', () => { BuildShared.build(libModules, cfg.paths.JS_PATH, cfg.paths.SHARED_LIB_PATH, 'gulp build-shared-lib'); }); // ------------------------------------------------------------------------ // Builds Definition Files // ------------------------------------------------------------------------ gulp.task('build-definition-files', () => { BuildDTsFilesABeamer.build(libModules, pluginModules, CLIENT_UUID, COPYRIGHTS, cfg); }); // ------------------------------------------------------------------------ // Builds the documentation // ------------------------------------------------------------------------ gulp.task('build-docs-latest', () => { BuildDocsLatest.build(libModules, pluginModules, cfg); }); gulp.task('post-build-docs-latest', () => { const wordMap: DevCfg.DevDocsWordMap = {}; cfg.docs.keywords.forEach(word => { wordMap[word] = { wordClass: 'keyword' }; }); cfg.docs.jsTypes.forEach(word => { wordMap[word] = { wordClass: 'type' }; }); cfg.docs.customTypes.forEach(wordPair => { wordMap[wordPair[0]] = { wordClass: 'type', title: wordPair[1], }; }); BuildDocsLatest.postBuild([ `{${cfg.paths.DOCS_LATEST_END_USER_PATH},${cfg.paths.DOCS_LATEST_DEVELOPER_PATH}}/en/site{/,/*/}*.html`], cfg.docs.replacePaths, wordMap); }); // ------------------------------------------------------------------------ // Builds Release Version Of The Gallery // ------------------------------------------------------------------------ gulp.task('gal-rel:clear', (cb) => { rimrafExcept(cfg.paths.GALLERY_LATEST_PATH, ['.git']); cb(); }); gulp.task('gal-rel:get-examples', (cb) => { BuildGalRel.populateReleaseExamples(cfg); cb(); }); gulp.task('gal-rel:copy-files', () => { return mergeStream(BuildGalRel.releaseExamples.map(ex => { const srcList = [`${ex.srcFullPath}/**`, `!${ex.srcFullPath}/{*.html,story.json,story-frames/*.png}`]; if (ex.srcFullPath.includes('remote-server')) { srcList.push(`!${ex.srcFullPath}/assets{/**,}`); } return gulp.src(srcList, { dot: true }) .pipe(gulp.dest(ex.dstFullPath)); })); }); gulp.task('gal-rel:update-html-files', () => { return mergeStream(BuildGalRel.releaseExamples.map(ex => { return updateHtmlPages(`${ex.srcFullPath}/*.html`, ex.dstFullPath, [`../../${cfg.paths.JS_PATH}/abeamer.min`], true); })); }); gulp.task('gal-rel:online-html-files', () => { const onlineLink = `${cfg.webLinks.webDomain}/${cfg.paths.RELEASE_LATEST_PATH}/client/lib`; return mergeStream(BuildGalRel.releaseExamples.map(ex => { return gulp.src([`${ex.dstFullPath}/index.html`]) .pipe(gulpReplace(/^(?:.|\n)+$/, (all: string) => all .replace(/"abeamer\//g, `"${onlineLink}/`) .replace(/(<head>)/g, '<!-- This file was created to be used online only. -->\n$1'), )) .pipe(gulpRename('index-online.html')) .pipe(gulp.dest(ex.dstFullPath)) .pipe(gulpPreserveTime()); })); }); gulp.task('gal-rel:create-zip', () => { return mergeStream(BuildGalRel.releaseExamples.map(ex => { return gulp.src([ `${ex.dstFullPath}/**`, `${ex.dstFullPath}/.allowed-plugins.json`, `!${ex.dstFullPath}/index-online.html`, `!${ex.dstFullPath}/*.zip`, `!${ex.dstFullPath}/story-frames/*.{json,gif,mp4}`, ]) .pipe(gulpZip(BuildGalRel.EXAMPLE_ZIP_FILE)) .pipe(gulp.dest(ex.dstFullPath)); })); }); gulp.task('gal-rel:process-readme', (cb) => { BuildGalRel.buildReadMe(cfg); cb(); }); (gulp as any).task('build-gallery-latest', gulpSequence( 'gal-rel:clear', 'gal-rel:get-examples', 'gal-rel:copy-files', 'gal-rel:update-html-files', 'gal-rel:online-html-files', 'gal-rel:create-zip', 'gal-rel:process-readme', )); // ------------------------------------------------------------------------ // Deletes gallery story-frames folder // ------------------------------------------------------------------------ gulp.task('clean-gallery-src', (cb) => { rimraf.sync(`${cfg.paths.GALLERY_SRC_PATH}/*/story-frames`); cb(); }); gulp.task('clean-gallery-src-png', (cb) => { rimraf.sync(`${cfg.paths.GALLERY_SRC_PATH}/*/story-frames/*.png`); cb(); }); // ------------------------------------------------------------------------ // Creates gallery examples gif image // ------------------------------------------------------------------------ (gulp as any).task('build-gallery-src-gifs', ['clean-gallery-src-png'], (cb) => { BuildGalRel.buildGifs(cfg); cb(); }); // ------------------------------------------------------------------------ // Update Gallery Scripts // ------------------------------------------------------------------------ gulp.task('update-gallery-src-scripts', () => { const DST_PATH = `${cfg.paths.GALLERY_SRC_PATH}-updated`; rimraf.sync(`${DST_PATH}/**`); const newScriptFiles = libModules.map(srcFile => `../../${cfg.paths.JS_PATH}/${srcFile}`); return mergeStream(updateHtmlPages(`${cfg.paths.GALLERY_SRC_PATH}/*/*.html`, DST_PATH, newScriptFiles, false)); }); // ------------------------------------------------------------------------ // Updates Test List // ------------------------------------------------------------------------ gulp.task('update-test-list', () => { const tests = []; sysFs.readdirSync(`./test/tests`).forEach(file => { file.replace(/(test-.*)\.ts/, (_all, testName) => { tests.push(testName); return ''; }); }); interface TestListFile { disabled: string[]; active: string[]; } const TEST_LIST_FILE = `./test/test-list.json`; const curTestList: TestListFile = fsix.loadJsonSync(TEST_LIST_FILE); tests.forEach(test => { if (curTestList.active.indexOf(test) === -1 && curTestList.disabled.indexOf(test) === -1) { console.log(`Adding test ${test} to ${TEST_LIST_FILE}`); curTestList.active.push(test); } }); fsix.writeJsonSync(TEST_LIST_FILE, curTestList); console.log(`Updated ${TEST_LIST_FILE}`); const PACKAGE_FILE = `./package.json`; const pkg: { scripts: { [script: string]: string } } = fsix.loadJsonSync(PACKAGE_FILE); const scripts = pkg.scripts; tests.forEach(test => { if (scripts[test] === undefined) { console.log(`Adding test ${test} to ${PACKAGE_FILE}`); scripts[test] = `mocha test/tests/${test}.js`; } }); fsix.writeJsonSync(PACKAGE_FILE, pkg); console.log(`Updated ${PACKAGE_FILE}`); }); // ------------------------------------------------------------------------ // Lists ./docs Files As Links // ------------------------------------------------------------------------ gulp.task('list-docs-files-as-links', (cb) => { sysFs.readdirSync(`./docs`).forEach(fileBase => { if (sysPath.extname(fileBase) !== '.md') { return; } const fileTitle = sysPath.parse(fileBase).name; const title = fileTitle.replace(/-/g, ' ') .replace(/\b(\w)/, (_all, firstChar: string) => firstChar.toUpperCase()); console.log(`- [${title}](${fileBase})`); }); cb(); }); // ------------------------------------------------------------------------ // Lists ./docs Files As Links // ------------------------------------------------------------------------ function changeReadmeLinks(toLocal: boolean): void { const IN_FILE = './README.md'; const BAK_FILE = IN_FILE + '.bak.md'; const srcRegEx = new RegExp('\\]\\(' + (toLocal ? cfg.webLinks.webDomain : '') + '/', 'g'); const dstLink = '](' + (toLocal ? '' : cfg.webLinks.webDomain) + '/'; let content = fsix.readUtf8Sync(IN_FILE); sysFs.writeFileSync(BAK_FILE, content); content = content.replace(srcRegEx, dstLink); sysFs.writeFileSync(IN_FILE, content); } gulp.task('README-to-online', () => { changeReadmeLinks(false); }); gulp.task('README-to-local', () => { changeReadmeLinks(true); }); }
the_stack
import styled from 'styled-components'; import ReactTooltip from 'react-tooltip'; import {media} from 'styles/media-breakpoints'; import classnames from 'classnames'; import {RGBColor} from 'reducers'; export const SelectText = styled.span` color: ${props => props.theme.labelColor}; font-size: ${props => props.theme.selectFontSize}; font-weight: 400; i { font-size: 13px; margin-right: 6px; } `; export const SelectTextBold = styled(SelectText)` color: ${props => props.theme.textColor}; font-weight: 500; `; export const IconRoundSmall = styled.div` display: flex; width: 18px; height: 18px; border-radius: 9px; background-color: ${props => props.theme.secondaryBtnBgdHover}; color: ${props => props.theme.secondaryBtnColor}; align-items: center; justify-content: center; :hover { cursor: pointer; background-color: ${props => props.theme.secondaryBtnBgdHover}; } `; export const CenterFlexbox = styled.div` display: flex; align-items: center; `; export const CenterVerticalFlexbox = styled.div` display: flex; flex-direction: column; align-items: center; `; export const SpaceBetweenFlexbox = styled.div` display: flex; justify-content: space-between; margin-left: -16px; `; export const SBFlexboxItem = styled.div` flex-grow: 1; margin-left: 16px; `; export const SBFlexboxNoMargin = styled.div` display: flex; justify-content: space-between; `; export const PanelLabel = styled.label.attrs({ className: 'side-panel-panel__label' })` color: ${props => props.theme.labelColor}; display: inline-block; font-size: 11px; font-weight: 400; margin-bottom: 4px; text-transform: capitalize; `; export const PanelLabelWrapper = styled.div.attrs({ className: 'side-panel-panel__label-wrapper' })` display: flex; align-items: self-start; `; export const PanelLabelBold = styled(PanelLabel)` font-weight: 500; `; export const PanelHeaderTitle = styled.span.attrs(props => ({ className: classnames('side-panel-panel__header__title', props.className) }))` color: ${props => props.theme.textColor}; font-size: 13px; letter-spacing: 0.43px; text-transform: capitalize; `; export const PanelHeaderContent = styled.div` display: flex; align-items: center; color: ${props => props.theme.textColor}; padding-left: 12px; .icon { color: ${props => props.theme.labelColor}; display: flex; align-items: center; margin-right: 12px; } `; export const PanelContent = styled.div.attrs(props => ({ className: classnames('side-panel-panel__content', props.className) }))` background-color: ${props => props.theme.panelContentBackground}; padding: 12px; `; interface SidePanelSectionProps { disabled?: boolean; } export const SidePanelSection = styled.div.attrs(props => ({ className: classnames('side-panel-section', props.className) }))<SidePanelSectionProps>` margin-bottom: 12px; opacity: ${props => (props.disabled ? 0.4 : 1)}; pointer-events: ${props => (props.disabled ? 'none' : 'all')}; `; export const SidePanelDivider = styled.div.attrs({ className: 'side-panel-divider' })` border-bottom: ${props => props.theme.sidepanelDividerBorder} solid ${props => props.theme.panelBorderColor}; margin-bottom: ${props => props.theme.sidepanelDividerMargin}px; height: ${props => props.theme.sidepanelDividerHeight}px; `; export const Tooltip = styled(ReactTooltip)` &.__react_component_tooltip { font-size: ${props => props.theme.tooltipFontSize}; font-weight: 400; padding: 7px 18px; box-shadow: ${props => props.theme.tooltipBoxShadow}; &.type-dark { background-color: ${props => props.theme.tooltipBg}; color: ${props => props.theme.tooltipColor}; &.place-bottom { :after { border-bottom-color: ${props => props.theme.tooltipBg}; } } &.place-top { :after { border-top-color: ${props => props.theme.tooltipBg}; } } &.place-right { :after { border-right-color: ${props => props.theme.tooltipBg}; } } &.place-left { :after { border-left-color: ${props => props.theme.tooltipBg}; } } } } `; export interface ButtonProps { negative?: boolean; secondary?: boolean; link?: boolean; floating?: boolean; cta?: boolean; large?: boolean; small?: boolean; disabled?: boolean; width?: string; inactive?: boolean; } export const Button = styled.div.attrs(props => ({ className: classnames('button', props.className) }))<ButtonProps>` align-items: center; background-color: ${props => props.negative ? props.theme.negativeBtnBgd : props.secondary ? props.theme.secondaryBtnBgd : props.link ? props.theme.linkBtnBgd : props.floating ? props.theme.floatingBtnBgd : props.cta ? props.theme.ctaBtnBgd : props.theme.primaryBtnBgd}; border-radius: ${props => props.theme.primaryBtnRadius}; color: ${props => props.negative ? props.theme.negativeBtnColor : props.secondary ? props.theme.secondaryBtnColor : props.link ? props.theme.linkBtnColor : props.floating ? props.theme.floatingBtnColor : props.cta ? props.theme.ctaBtnColor : props.theme.primaryBtnColor}; cursor: pointer; display: inline-flex; font-size: ${props => props.large ? props.theme.primaryBtnFontSizeLarge : props.small ? props.theme.primaryBtnFontSizeSmall : props.theme.primaryBtnFontSizeDefault}; font-weight: 500; font-family: ${props => props.theme.btnFontFamily}; justify-content: center; letter-spacing: 0.3px; line-height: 14px; outline: 0; padding: ${props => (props.large ? '14px 32px' : props.small ? '6px 9px' : '9px 12px')}; text-align: center; transition: ${props => props.theme.transition}; vertical-align: middle; width: ${props => props.width || 'auto'}; opacity: ${props => (props.disabled ? 0.4 : 1)}; pointer-events: ${props => (props.disabled ? 'none' : 'all')}; border: ${props => props.negative ? props.theme.negativeBtnBorder : props.secondary ? props.theme.secondaryBtnBorder : props.floating ? props.theme.floatingBtnBorder : props.link ? props.theme.linkBtnBorder : props.theme.primaryBtnBorder}; :hover, :focus, :active, &.active { background-color: ${props => props.negative ? props.theme.negativeBtnBgdHover : props.secondary ? props.theme.secondaryBtnBgdHover : props.link ? props.theme.linkBtnActBgdHover : props.floating ? props.theme.floatingBtnBgdHover : props.cta ? props.theme.ctaBtnBgdHover : props.theme.primaryBtnBgdHover}; color: ${props => props.negative ? props.theme.negativeBtnActColor : props.secondary ? props.theme.secondaryBtnActColor : props.link ? props.theme.linkBtnActColor : props.floating ? props.theme.floatingBtnActColor : props.cta ? props.theme.ctaBtnActColor : props.theme.primaryBtnActColor}; } svg { margin-right: ${props => (props.large ? '10px' : props.small ? '6px' : '8px')}; } `; interface InputProps { secondary?: boolean; } export const Input = styled.input<InputProps>` ${props => (props.secondary ? props.theme.secondaryInput : props.theme.input)}; `; export const InputLight = styled.input` ${props => props.theme.inputLT}; `; export const TextArea = styled.textarea<InputProps>` ${props => (props.secondary ? props.theme.secondaryInput : props.theme.input)}; `; export const TextAreaLight = styled.textarea` ${props => props.theme.inputLT} height: auto; white-space: pre-wrap; `; export const InlineInput = styled(Input)` ${props => props.theme.inlineInput}; `; export interface StyledPanelHeaderProps { active?: boolean; labelRCGColorValues?: RGBColor | null; } export const StyledPanelHeader = styled.div<StyledPanelHeaderProps>` background-color: ${props => props.active ? props.theme.panelBackgroundHover : props.theme.panelBackground}; border-left: 3px solid rgb( ${props => (props.labelRCGColorValues ? props.labelRCGColorValues.join(',') : 'transparent')} ); padding: 0 10px 0 0; height: ${props => props.theme.panelHeaderHeight}px; display: flex; justify-content: space-between; align-items: center; border-radius: ${props => props.theme.panelHeaderBorderRadius}; transition: ${props => props.theme.transition}; `; interface StyledPanelDropdownProps { type?: string; } export const StyledPanelDropdown = styled.div<StyledPanelDropdownProps>` ${props => props.theme.panelDropdownScrollBar} background-color: ${props => props.type === 'light' ? props.theme.modalDropdownBackground : props.theme.panelBackground}; overflow-y: auto; box-shadow: ${props => props.theme.panelBoxShadow}; border-radius: ${props => props.theme.panelBorderRadius}; max-height: 500px; position: relative; z-index: 999; `; export const ButtonGroup = styled.div` display: flex; .button { border-radius: 0; margin-left: 2px; } .button:first-child { border-bottom-left-radius: ${props => props.theme.primaryBtnRadius}; border-top-left-radius: ${props => props.theme.primaryBtnRadius}; margin-left: 0; } .button:last-child { border-bottom-right-radius: ${props => props.theme.primaryBtnRadius}; border-top-right-radius: ${props => props.theme.primaryBtnRadius}; } `; interface DatasetSquareProps { backgroundColor: RGBColor; } export const DatasetSquare = styled.div<DatasetSquareProps>` display: inline-block; width: 10px; height: 10px; background-color: rgb(${props => props.backgroundColor.join(',')}); margin-right: 12px; `; interface SelectionButtonProps { selected?: boolean; } export const SelectionButton = styled.div<SelectionButtonProps>` position: relative; border-radius: 2px; border: 1px solid ${props => props.selected ? props.theme.selectionBtnBorderActColor : props.theme.selectionBtnBorderColor}; color: ${props => props.selected ? props.theme.selectionBtnActColor : props.theme.selectionBtnColor}; background-color: ${props => props.selected ? props.theme.selectionBtnActBgd : props.theme.selectionBtnBgd}; cursor: pointer; font-weight: 500; margin-right: 6px; padding: 6px 16px; :hover { color: ${props => props.theme.selectionBtnActColor}; border: 1px solid ${props => props.theme.selectionBtnBorderActColor}; } `; export const Table = styled.table` width: 100%; border-spacing: 0; thead { tr th { background: ${props => props.theme.panelBackgroundLT}; color: ${props => props.theme.titleColorLT}; padding: 18px 12px; text-align: start; } } tbody { tr td { border-bottom: ${props => props.theme.panelBorderLT}; padding: 12px; } } `; export const StyledModalContent = styled.div` background: ${props => props.theme.panelBackgroundLT}; color: ${props => props.theme.textColorLT}; display: flex; flex-direction: row; font-size: 10px; padding: 24px ${props => props.theme.modalLateralPadding}; margin: 0 -${props => props.theme.modalLateralPadding}; justify-content: space-between; ${media.portable` flex-direction: column; padding: 16px ${props => props.theme.modalPortableLateralPadding}; margin: 0 -${props => props.theme.modalPortableLateralPadding}; `}; `; export const StyledModalVerticalPanel = styled.div.attrs({ className: 'modal-vertical-panel' })` display: flex; flex-direction: column; justify-content: space-around; font-size: 12px; .modal-section:first-child { margin-top: 24px; ${media.palm` margin-top: 0; `}; } input { margin-right: 8px; } `; export const StyledModalSection = styled.div.attrs({ className: 'modal-section' })` margin-bottom: 32px; .modal-section-title { font-weight: 500; } .modal-section-subtitle { color: ${props => props.theme.subtextColorLT}; } input { margin-top: 8px; } ${media.portable` margin-bottom: 24px; `}; ${media.palm` margin-bottom: 16px; `}; `; interface StyledModalInputFootnoteProps { error?: boolean; } export const StyledModalInputFootnote = styled.div.attrs({ className: 'modal-input__footnote' })<StyledModalInputFootnoteProps>` display: flex; justify-content: flex-end; color: ${props => (props.error ? props.theme.errorColor : props.theme.subtextColorLT)}; font-size: 10px; `; /** * Newer versions of mapbox.gl display an error message banner on top of the map by default * which will cause the map to display points in the wrong locations * This workaround will hide the error banner. */ export const StyledMapContainer = styled.div` width: 100%; height: 100%; .mapboxgl-map { .mapboxgl-missing-css { display: none; } .mapboxgl-ctrl-attrib { display: none; } } `; export const StyledAttrbution = styled.div.attrs({ className: 'mapbox-attribution-container' })` bottom: 0; right: 0; position: absolute; display: block; margin: 0 10px 2px; z-index: 0; .attrition-logo { display: flex; font-size: 10px; justify-content: flex-end; align-items: center; color: ${props => props.theme.labelColor}; margin-bottom: -4px; a.mapboxgl-ctrl-logo { width: 72px; margin-left: 6px; } } a { font-size: 10px; } `; interface StyledExportSectionProps { disabled?: boolean; } export const StyledExportSection = styled.div<StyledExportSectionProps>` display: flex; flex-direction: row; margin: 35px 0; width: 100%; color: ${props => props.theme.textColorLT}; font-size: 12px; opacity: ${props => (props.disabled ? 0.3 : 1)}; pointer-events: ${props => (props.disabled ? 'none' : 'all')}; .description { width: 185px; .title { font-weight: 500; } .subtitle { color: ${props => props.theme.subtextColorLT}; font-size: 11px; } } .warning { color: ${props => props.theme.errorColor}; font-weight: 500; } .description.full { width: 100%; } .selection { display: flex; flex-wrap: wrap; flex: 1; padding-left: 50px; select { background-color: white; border-radius: 1px; display: inline-block; font: inherit; line-height: 1.5em; padding: 0.5em 3.5em 0.5em 1em; margin: 0; box-sizing: border-box; appearance: none; width: 250px; height: 36px; background-image: linear-gradient(45deg, transparent 50%, gray 50%), linear-gradient(135deg, gray 50%, transparent 50%), linear-gradient(to right, #ccc, #ccc); background-position: calc(100% - 20px) calc(1em + 2px), calc(100% - 15px) calc(1em + 2px), calc(100% - 2.5em) 4.5em; background-size: 5px 5px, 5px 5px, 1px 1.5em; background-repeat: no-repeat; } select:focus { background-image: linear-gradient(45deg, green 50%, transparent 50%), linear-gradient(135deg, transparent 50%, green 50%), linear-gradient(to right, #ccc, #ccc); background-position: calc(100% - 15px) 1em, calc(100% - 20px) 1em, calc(100% - 2.5em) 4.5em; background-size: 5px 5px, 5px 5px, 1px 1.5em; background-repeat: no-repeat; border-color: green; outline: 0; } } `; export const StyledFilteredOption = styled(SelectionButton)` align-items: center; display: flex; flex-direction: column; justify-content: center; margin: 4px; padding: 8px 12px; width: 140px; .filter-option-title { color: ${props => props.theme.textColorLT}; font-size: 12px; font-weight: 500; } .filter-option-subtitle { color: ${props => props.theme.subtextColorLT}; font-size: 11px; } `; export const StyledType = styled(SelectionButton)` height: 100px; margin: 4px; padding: 6px 10px; width: 100px; `; export const WidgetContainer = styled.div` z-index: 1; `; export const BottomWidgetInner = styled.div` background-color: ${props => props.theme.bottomWidgetBgd}; padding: ${props => `${props.theme.bottomInnerPdVert}px ${props.theme.bottomInnerPdSide}px`}; position: relative; margin-top: ${props => props.theme.bottomPanelGap}px; `; interface MapControlButtonProps { active?: boolean; } export const MapControlButton = styled(Button).attrs({ className: 'map-control-button' })<MapControlButtonProps>` box-shadow: 0 6px 12px 0 rgba(0, 0, 0, 0.16); height: 32px; width: 32px; padding: 0; border-radius: 0; background-color: ${props => props.active ? props.theme.floatingBtnBgdHover : props.theme.floatingBtnBgd}; color: ${props => props.active ? props.theme.floatingBtnActColor : props.theme.floatingBtnColor}; border: ${props => props.active ? props.theme.floatingBtnBorderHover : props.theme.floatingBtnBorder}; :hover, :focus, :active, &.active { background-color: ${props => props.theme.floatingBtnBgdHover}; color: ${props => props.theme.floatingBtnActColor}; border: ${props => props.theme.floatingBtnBorderHover}; } svg { margin-right: 0; } `; export const StyledFilterContent = styled.div` background-color: ${props => props.theme.panelContentBackground}; padding: 12px; `; export const TruncatedTitleText = styled.div` white-space: nowrap; text-overflow: ellipsis; overflow: hidden; `; export const CheckMark = styled.span.attrs({ className: 'checkbox-inner' })` background-color: ${props => props.theme.selectionBtnBorderActColor}; position: absolute; top: 0; right: 0; display: block; width: 10px; height: 10px; border-top-left-radius: 2px; :after { position: absolute; display: table; border: 1px solid #fff; border-top: 0; border-left: 0; transform: rotate(45deg) scale(1) translate(-50%, -50%); opacity: 1; content: ' '; top: 40%; left: 30%; width: 3.2px; height: 6.22px; } `;
the_stack
import appMenu from '../../backend/appMenu' import express from 'express' import http from 'http' import xCloudClient from '../../frontend/xcloudclient' import TokenStore from '../../backend/TokenStore'; import Application from '../../frontend/application'; import fs from 'fs' declare const MAIN_WINDOW_WEBPACK_ENTRY: string; declare const WEBUI_PRELOAD_WEBPACK_ENTRY: string; declare const WEBUI_WEBPACK_ENTRY: string; // interface OpentrackPosition { // [key: string]: number; // } export class WebuiPluginBackend { _isRunning = false _menu:appMenu _tokenStore:TokenStore _server:any _serverStatus = { port: -1 } _syncInterval:any _xCloudClient:any constructor(menu:appMenu, tokenStore:TokenStore = undefined) { this._menu = menu this._tokenStore = tokenStore } load() { // this._menu._ipc.on('opentrack-sync', (event:any, variables:any) => { // // console.log('IPCMain received:', variables) // // Backend is always in the lead of settings. // event.reply('opentrack-sync', { // isRunning: this._isRunning, // position: this._position // }) // }) // this._menu._ipc.on('opentrack-position', (event:any, variables:any) => { // event.reply('opentrack-position', { // position: this._position // }) // }) } start() { this._isRunning = true this.startServer() this._menu.setMenu('webui', this.getMenu()) } stop() { this._isRunning = false this.stopServer() this._menu.setMenu('webui', this.getMenu()) } _resolvePath(window:string, file:string) { let path = '' if(window === 'main_window'){ path = MAIN_WINDOW_WEBPACK_ENTRY } else if(window === 'webui'){ path = WEBUI_WEBPACK_ENTRY } let htmlFile:Buffer = Buffer.from(path) if(path.slice(0, 4) == 'file'){ console.log('load file:', path.slice(7).replace('index.html', file)) htmlFile = fs.readFileSync(path.slice(7).replace('index.html', file)) } else { // We assume that we have an http url (from webpack) htmlFile = fs.readFileSync('.webpack/renderer/'+window+'/'+file) } return htmlFile } startServer(port = 8080) { console.log('Starting WebUI Webserver...') // this._server = express() const requestListener = (req:any, res:any) => { console.log(req.method, req.url) if(req.url == '/'){ res.writeHead(200); const htmlFile = this._resolvePath('webui', 'index.html') res.end(htmlFile) } else if(req.url == '/webui/index.js'){ res.writeHead(200, { 'Content-Type': 'text/javascript' }) const htmlFile = this._resolvePath('webui', 'index.js') res.end(htmlFile) } else if(req.url == '/dist/opusWorker.min.js'){ res.writeHead(200, { 'Content-Type': 'text/javascript' }) const htmlFile = this._resolvePath('main_window', 'dist/opusWorker.min.js') res.end(htmlFile) } else if(req.url == '/opus/libopus-decoder.min.js'){ res.writeHead(200, { 'Content-Type': 'text/javascript' }) const htmlFile = this._resolvePath('main_window', 'opus/libopus-decoder.min.js') res.end(htmlFile) } else if(req.url == '/opus/oggOpusDecoder.js'){ res.writeHead(200, { 'Content-Type': 'text/javascript' }) const htmlFile = this._resolvePath('main_window', 'opus/oggOpusDecoder.js') res.end(htmlFile) } else if(req.url == '/opus/libopus-decoder.wasm.min.wasm'){ res.writeHead(200, { 'Content-Type': 'application/wasm' }) const htmlFile = this._resolvePath('main_window', 'opus/libopus-decoder.wasm.min.wasm') res.end(htmlFile) } else if(req.url == '/api/consoles'){ this._xCloudClient = new xCloudClient({ _tokenStore: this._tokenStore } as Application, 'uks.gssv-play-prodxhome.xboxlive.com', this._tokenStore._streamingToken, 'home') this._xCloudClient.getConsoles().then((consoles:any) => { console.log('consoles', consoles) res.writeHead(200); res.end(JSON.stringify(consoles)) }).catch((error:any) => { console.log('consoles error', error) res.writeHead(error.status); res.end('API returned http status: ' + error.status) }) } else if(req.url.includes('/api/xcloud/play/')) { const title = req.url.slice(17) this._xCloudClient = new xCloudClient({ _tokenStore: this._tokenStore } as Application, this._tokenStore._xCloudRegionHost, this._tokenStore._xCloudStreamingToken, 'cloud') this._xCloudClient.startSession(title).then((config:any) => { res.writeHead(200); res.end(JSON.stringify(config)); }).catch((error:any) => { res.writeHead(500); res.end('Error in starting stream: '+error); }) } else if(req.url.includes('/api/xhome/play/')) { const consoleId = req.url.slice(16) this._xCloudClient = new xCloudClient({ _tokenStore: this._tokenStore } as Application, 'uks.gssv-play-prodxhome.xboxlive.com', this._tokenStore._streamingToken, 'home') this._xCloudClient.startSession(consoleId).then((config:any) => { res.writeHead(200); res.end(JSON.stringify(config)); }).catch((error:any) => { res.writeHead(500); res.end('Error in starting stream: '+error); }) } else if(req.url.includes('/api/sdp')) { if(req.method == 'POST'){ let body = ''; req.on('data', (chunk:any) => { body += chunk.toString(); // convert Buffer to string }); req.on('end', () => { const incomingData = JSON.parse(body) this._xCloudClient.sendSdp(incomingData.sdp).then((config:any) => { console.log(config) res.writeHead(200); res.end(JSON.stringify(config)); }).catch((error:any) => { res.writeHead(500); res.end('Error in sending SDP data: '+error); }) }); } else { res.writeHead(500); res.end('Only POST is supported'); } } else if(req.url.includes('/api/ice')) { if(req.method == 'POST'){ let body = ''; req.on('data', (chunk:any) => { body += chunk.toString(); // convert Buffer to string }); req.on('end', () => { const incomingData = JSON.parse(body) this._xCloudClient.sendIce(incomingData).then((config:any) => { console.log(config) res.writeHead(200); res.end(JSON.stringify(config)); }).catch((error:any) => { res.writeHead(500); res.end('Error in sending ICE data: '+error); }) }); } else { res.writeHead(500); res.end('Only POST is supported'); } } else if(req.url == '/api/keepalive'){ this._xCloudClient.sendKeepalive().then((response:any) => { res.writeHead(200); res.end(JSON.stringify(response)) }).catch((error:any) => { console.log('keepalive error:', error) res.writeHead(error.status); res.end('API returned http status: ' + error.status) }) } else { res.writeHead(404); res.end('Not found: '+req.url); } } this._server = http.createServer(requestListener); this._server.listen(port); // this._server.get('/', (req:any, res:any) => { // console.log('GET /') // res.send('Hello World!') // }) // this._server.get('/api/consoles', (req:any, res:any) => { // console.log('GET /api/consoles') // this._xCloudClient.getConsoles().then((consoles:any) => { // console.log('consoles', consoles) // res.send(consoles) // }).catch((error:any) => { // console.log('consoles error', error) // res.send(error) // }) // }) this._serverStatus.port = port // this._server.listen(port, () => { // console.log(`WebUI listening at http://localhost:${port}`) // }) } stopServer() { console.log('Stopping WebUI Webserver...') clearInterval(this._syncInterval) this._serverStatus.port = -1 // this._server.stop() this._xCloudClient = undefined this._server.close() console.log('WebUI Webserver stopped.') } getMenu() { return { label: 'WebUI (beta)', submenu: [ { label: (this._isRunning === true) ? 'Stop Webserver' : 'Start Webserver', click: async () => { if(this._isRunning === false){ this.start() } else { this.stop() } } }, { label: this.getStatusLabel(), enabled: false, }, { type: 'separator' }, ...this.getPositionsMenu(), ] } } getPositionsMenu():any { const menu:Array<any> = [ { label: 'Open WebUI in browser', enabled: this._isRunning, click: async () => { const { shell } = require('electron') await shell.openExternal('http://localhost:'+this._serverStatus.port) } } ] return menu } getStatusLabel(){ if(this._isRunning === true){ return 'Status: Running on port '+this._serverStatus.port } else { return 'Status: Not running' } } }
the_stack
import type { Editor, JSONContent } from '@tiptap/react'; import { capitalize } from 'lodash'; import type { Fragment, Node as ProseMirrorNode } from 'prosemirror-model'; import type { RicosEditorProps } from 'ricos-common'; import { BLOCKQUOTE, BULLET_LIST_TYPE, CODE_BLOCK_TYPE, generateId, HEADER_BLOCK, NUMBERED_LIST_TYPE, UNSTYLED, } from 'ricos-content'; import { tiptapToDraft } from 'ricos-converters'; import { Decoration_Type, Node_Type } from 'ricos-schema'; import type { TiptapAdapter } from 'ricos-tiptap-types'; import type { RicosCustomStyles, TextAlignment } from 'wix-rich-content-common'; import { defaultFontSizes, defaultMobileFontSizes, DOC_STYLE_TYPES, RICOS_LINK_TYPE, RICOS_MENTION_TYPE, RICOS_TEXT_COLOR_TYPE, RICOS_TEXT_HIGHLIGHT_TYPE, } from 'wix-rich-content-common'; import { TO_TIPTAP_TYPE } from '../../consts'; import { findNodeById } from '../../helpers'; export class RichContentAdapter implements TiptapAdapter { private readonly initialContent: Fragment; private readonly shouldRevealConverterErrors: boolean | undefined; constructor(public tiptapEditor: Editor, ricosEditorProps: RicosEditorProps) { this.tiptapEditor = tiptapEditor; this.initialContent = this.tiptapEditor.state.doc.content; this.getEditorCommands = this.getEditorCommands.bind(this); this.shouldRevealConverterErrors = ricosEditorProps.experiments?.removeRichContentSchemaNormalizer?.enabled; } isContentChanged = (): boolean => !this.initialContent.eq(this.tiptapEditor.state.doc.content); getContainer = () => { return this.tiptapEditor?.options?.element; }; getDraftContent = () => tiptapToDraft(this.tiptapEditor.getJSON() as JSONContent, this.shouldRevealConverterErrors); focus() { this.tiptapEditor.commands.focus(); } blur() { this.tiptapEditor.commands.blur(); } getEditorCommands() { return { ...this.editorMocks, toggleInlineStyle: inlineStyle => { const editorCommand = this.tiptapEditor.chain().focus(); const styleName = `toggle${capitalize(inlineStyle)}`; editorCommand[styleName]().run(); }, hasInlineStyle: style => { const { state: { doc, selection: { from, to, $from }, }, } = this.tiptapEditor; const marks = {}; if (from === to) { $from.nodeBefore?.marks.forEach(({ type: { name } }) => { marks[name] = true; }); } else { doc.nodesBetween(from, to, node => { node.marks.forEach(({ type: { name } }) => { marks[name] = true; }); }); } return marks[style]; }, insertBlock: (pluginType, data) => { const type = TO_TIPTAP_TYPE[pluginType]; let id = ''; if (type) { const { content, ..._attrs } = data; id = data.id || generateId(); const attrs = { id, ...flatComponentState(_attrs) }; this.tiptapEditor.chain().focus().insertContent([{ type, attrs, content }]).run(); } else { console.error(`No such plugin type ${pluginType}`); } return id; }, insertBlockWithBlankLines: (pluginType, data, settings = { updateSelection: true }) => { const type = TO_TIPTAP_TYPE[pluginType]; let id = ''; if (type) { const { content, ..._attrs } = data; id = data.id || generateId(); const attrs = { id, ...flatComponentState(_attrs) }; const { state: { selection: { to: lastNodePosition }, }, } = this.tiptapEditor; const { updateSelection } = settings; this.tiptapEditor .chain() .focus() .insertContent([ { type: 'PARAGRAPH', attrs: { id: generateId() } }, { type, attrs, content }, { type: 'PARAGRAPH', attrs: { id: generateId() } }, ]) .setNodeSelection(updateSelection ? lastNodePosition + 1 : lastNodePosition + 2) .run(); } else { console.error(`No such plugin type ${pluginType}`); } return id; }, deleteBlock: blockKey => { return this.tiptapEditor.commands.deleteNode(blockKey); }, findNodeByKey() {}, setBlock: (blockKey, pluginType, data) => { return this.tiptapEditor.commands.setNodeAttrsById(blockKey, flatComponentState(data)); }, updateBlock: (blockKey, pluginType, data) => { return this.tiptapEditor.commands.updateNodeAttrsById(blockKey, flatComponentState(data)); }, getSelection: () => { const { state: { doc, selection: { from, to }, }, } = this.tiptapEditor; const selectedNodes: ProseMirrorNode[] = []; doc.nodesBetween(from, to, node => { selectedNodes.push(node); }); return { isFocused: this.tiptapEditor.isFocused, isCollapsed: this.tiptapEditor.state.selection.empty, startKey: selectedNodes[0].attrs.id, endKey: selectedNodes[selectedNodes.length - 1].attrs.id, }; }, insertDecoration: (type, data) => { const decorationCommandMap = { [RICOS_LINK_TYPE]: data => ({ command: 'setLink', args: { link: data } }), [RICOS_TEXT_COLOR_TYPE]: data => ({ command: 'setColor', args: data.color }), [RICOS_TEXT_HIGHLIGHT_TYPE]: data => ({ command: 'setHighlight', args: data.color }), [RICOS_MENTION_TYPE]: data => ({ command: 'insertMention', args: data.mention }), }; if (decorationCommandMap[type]) { const { command, args } = decorationCommandMap[type](data); const editorCommand = this.tiptapEditor.chain().focus(); editorCommand[command](args).run(); } else { console.error(`${type} decoration not supported`); } }, hasLinkInSelection: () => { const { state: { doc, selection: { from, to }, }, } = this.tiptapEditor; const marks: Record<string, boolean> = {}; doc.nodesBetween(from, to, node => { node.marks.forEach(({ type: { name } }) => { marks[name] = true; }); }); return marks[Decoration_Type.LINK] || marks[Decoration_Type.ANCHOR]; }, getLinkDataInSelection: () => { const { state: { doc, selection: { from, to }, }, } = this.tiptapEditor; let link; doc.nodesBetween(from, to, node => { node.marks.forEach(mark => { const { type: { name }, } = mark; if (name === Decoration_Type.LINK) { link = mark.attrs.link; } else if (name === Decoration_Type.ANCHOR) { link = { anchor: mark.attrs.anchor }; } }); }); return link; }, setBlockType: type => { const blockTypeCommandMap = { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore [UNSTYLED]: () => this.tiptapEditor.commands.setParagraph(), // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore [HEADER_BLOCK.ONE]: () => this.tiptapEditor.commands.toggleHeading({ level: 1 }), // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore [HEADER_BLOCK.TWO]: () => this.tiptapEditor.commands.toggleHeading({ level: 2 }), // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore [HEADER_BLOCK.THREE]: () => this.tiptapEditor.commands.toggleHeading({ level: 3 }), // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore [HEADER_BLOCK.FOUR]: () => this.tiptapEditor.commands.toggleHeading({ level: 4 }), // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore [HEADER_BLOCK.FIVE]: () => this.tiptapEditor.commands.toggleHeading({ level: 5 }), // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore [HEADER_BLOCK.SIX]: () => this.tiptapEditor.commands.toggleHeading({ level: 6 }), // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore [BLOCKQUOTE]: () => this.tiptapEditor.commands.toggleBlockquote(), // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore [CODE_BLOCK_TYPE]: () => this.tiptapEditor.commands.toggleCodeBlock(), // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore [BULLET_LIST_TYPE]: () => this.tiptapEditor.commands.toggleBulletList(), // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore [NUMBERED_LIST_TYPE]: () => this.tiptapEditor.commands.toggleOrderedList(), }; const currentSetBlockTypeCommand = blockTypeCommandMap[type]; if (currentSetBlockTypeCommand) { currentSetBlockTypeCommand(); } else { throw new Error(`${type} block type not supported`); } }, isBlockTypeSelected: type => { const blockTypeActiveCommandMap = { [UNSTYLED]: () => this.tiptapEditor.isActive('unstyled'), [HEADER_BLOCK.ONE]: () => this.tiptapEditor.isActive(Node_Type.HEADING, { level: 1 }), [HEADER_BLOCK.TWO]: () => this.tiptapEditor.isActive(Node_Type.HEADING, { level: 2 }), [HEADER_BLOCK.THREE]: () => this.tiptapEditor.isActive(Node_Type.HEADING, { level: 3 }), [HEADER_BLOCK.FOUR]: () => this.tiptapEditor.isActive(Node_Type.HEADING, { level: 4 }), [HEADER_BLOCK.FIVE]: () => this.tiptapEditor.isActive(Node_Type.HEADING, { level: 5 }), [HEADER_BLOCK.SIX]: () => this.tiptapEditor.isActive(Node_Type.HEADING, { level: 6 }), [CODE_BLOCK_TYPE]: () => this.tiptapEditor.isActive(Node_Type.CODE_BLOCK), [BLOCKQUOTE]: () => this.tiptapEditor.isActive(Node_Type.BLOCKQUOTE), [NUMBERED_LIST_TYPE]: () => this.tiptapEditor.isActive(Node_Type.ORDERED_LIST), [BULLET_LIST_TYPE]: () => this.tiptapEditor.isActive(Node_Type.BULLETED_LIST), }; const currentBlockTypeActiveCommand = blockTypeActiveCommandMap[type]; if (currentBlockTypeActiveCommand) { return currentBlockTypeActiveCommand(); } else { throw new Error(`${type} block type not supported`); } }, deleteDecoration: type => { const deleteDecorationCommandMap = { [RICOS_LINK_TYPE]: () => this.tiptapEditor.commands.unsetLink(), }; if (deleteDecorationCommandMap[type]) { deleteDecorationCommandMap[type](); } else { console.error(`delete ${type} decoration type not supported`); } }, setTextAlignment: alignment => { this.tiptapEditor.commands.setTextAlign(alignment); }, undo: () => this.tiptapEditor.commands.undo(), redo: () => this.tiptapEditor.commands.redo(), insertText: text => this.tiptapEditor .chain() .focus() .command(({ tr }) => { tr.insertText(text); return true; }) .run(), getAllBlocksKeys: () => { const keys: string[] = []; this.tiptapEditor.state.doc.descendants((node: ProseMirrorNode) => { keys.push(node.attrs.id); }); return keys; }, getBlockComponentData: id => { const nodesWithPos = findNodeById(this.tiptapEditor.state.tr, id); if (nodesWithPos[0]) { const { node } = nodesWithPos[0]; return node.attrs; } else { console.error('Failed to find node and return its data'); } }, }; } editorMocks = { getAnchorableBlocks: () => ({ anchorableBlocks: [], pluginsIncluded: [], }), getColor: () => 'unset', getFontSize: () => 'big', getTextAlignment: (): TextAlignment => { const { state: { doc, selection: { from, to }, }, } = this.tiptapEditor; const textStyles: string[] = []; doc.nodesBetween(from, to, node => { const textAlignment = node.attrs?.textStyle?.textAlignment; if (textAlignment) { textStyles.push(textAlignment); } }); let currentTextStyle = 'auto'; if (textStyles[0]) { currentTextStyle = textStyles[0].toLowerCase(); } return currentTextStyle as TextAlignment; }, isBlockTypeSelected: () => false, isUndoStackEmpty: () => false, isRedoStackEmpty: () => false, getSelectedData: () => 'blah', getPluginsList: () => [], scrollToBlock: _blockKey => {}, isBlockInContent: _blockKey => false, toggleBlockOverlay: _blockKey => false, getBlockSpacing: () => 5, saveEditorState: () => {}, loadEditorState: () => {}, saveSelectionState: () => {}, loadSelectionState: () => {}, triggerDecoration: () => {}, setBlockType: () => {}, _setSelection: () => {}, getDocumentStyle: () => undefined, getAnchorBlockInlineStyles: () => { return {}; }, getInlineStylesInSelection: () => { return {}; }, updateDocumentStyle: () => {}, clearSelectedBlocksInlineStyles: () => {}, getWiredFontStyles: (customStyles?: RicosCustomStyles, isMobile?: boolean) => { const fontStyles = {}; Object.values(DOC_STYLE_TYPES).forEach((docType: string) => { fontStyles[docType] = { 'font-size': isMobile ? defaultMobileFontSizes[docType] : defaultFontSizes[docType], 'font-family': 'HelveticaNeue, Helvetica, Arial', }; }); return fontStyles; }, isAtomicBlockInSelection: () => false, isTextBlockInSelection: () => true, getAnchorBlockType: () => 'paragraph', focus: () => {}, }; } const flatComponentState = data => { const { componentState, ...rest } = data; return { ...(rest || {}), ...(componentState || {}) }; };
the_stack
module Rx { export interface Observable<T> { /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ selectSwitch<TResult>(selector: _ValueOrSelector<T, ObservableOrPromise<TResult>>): Observable<TResult>; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ selectSwitch<TResult>(selector: _ValueOrSelector<T, ArrayOrIterable<TResult>>): Observable<TResult>; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ selectSwitch<TOther, TResult>(selector: _ValueOrSelector<T, ObservableOrPromise<TOther>>, resultSelector: special._FlatMapResultSelector<T, TOther, TResult>, thisArg?: any): Observable<TResult>; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ selectSwitch<TOther, TResult>(selector: _ValueOrSelector<T, ArrayOrIterable<TOther>>, resultSelector: special._FlatMapResultSelector<T, TOther, TResult>, thisArg?: any): Observable<TResult>; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ flatMapLatest<TResult>(selector: _ValueOrSelector<T, ObservableOrPromise<TResult>>): Observable<TResult>; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ flatMapLatest<TResult>(selector: _ValueOrSelector<T, ArrayOrIterable<TResult>>): Observable<TResult>; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ flatMapLatest<TOther, TResult>(selector: _ValueOrSelector<T, ObservableOrPromise<TOther>>, resultSelector: special._FlatMapResultSelector<T, TOther, TResult>, thisArg?: any): Observable<TResult>; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ flatMapLatest<TOther, TResult>(selector: _ValueOrSelector<T, ArrayOrIterable<TOther>>, resultSelector: special._FlatMapResultSelector<T, TOther, TResult>, thisArg?: any): Observable<TResult>; } } (function() { var o: Rx.Observable<string>; var n: Rx.Observable<number>; n = o.flatMapLatest(x => Rx.Observable.from([1, 2, 3])); n = o.flatMapLatest(x => Rx.Observable.from([1, 2, 3]).toPromise()); n = o.flatMapLatest(x => [1, 2, 3]); n = o.flatMapLatest(x => Rx.Observable.from([1, 2, 3]), (x, y) => y); n = o.flatMapLatest(x => Rx.Observable.from([1, 2, 3]).toPromise(), (x, y) => y); n = o.flatMapLatest(x => [1, 2, 3], (x, y) => y); n = o.flatMapLatest(Rx.Observable.from([1, 2, 3])); n = o.flatMapLatest(Rx.Observable.from([1, 2, 3]).toPromise()); n = o.flatMapLatest([1, 2, 3]); n = o.flatMapLatest(Rx.Observable.from([1, 2, 3]), (x, y) => y); n = o.flatMapLatest(Rx.Observable.from([1, 2, 3]).toPromise(), (x, y) => y); n = o.flatMapLatest([1, 2, 3], (x, y) => y); n = o.selectSwitch(x => Rx.Observable.from([1, 2, 3])); n = o.selectSwitch(x => Rx.Observable.from([1, 2, 3]).toPromise()); n = o.selectSwitch(x => [1, 2, 3]); n = o.selectSwitch(x => Rx.Observable.from([1, 2, 3]), (x, y) => y); n = o.selectSwitch(x => Rx.Observable.from([1, 2, 3]).toPromise(), (x, y) => y); n = o.selectSwitch(x => [1, 2, 3], (x, y) => y); n = o.selectSwitch(Rx.Observable.from([1, 2, 3])); n = o.selectSwitch(Rx.Observable.from([1, 2, 3]).toPromise()); n = o.selectSwitch([1, 2, 3]); n = o.selectSwitch(Rx.Observable.from([1, 2, 3]), (x, y) => y); n = o.selectSwitch(Rx.Observable.from([1, 2, 3]).toPromise(), (x, y) => y); n = o.selectSwitch([1, 2, 3], (x, y) => y); });
the_stack
import 'chrome://resources/cr_elements/cr_button/cr_button.m.js'; import 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; import 'chrome://resources/cr_elements/cr_searchable_drop_down/cr_searchable_drop_down.js'; import 'chrome://resources/cr_elements/hidden_style_css.m.js'; import 'chrome://resources/cr_elements/shared_vars_css.m.js'; import 'chrome://resources/js/action_link.js'; import 'chrome://resources/cr_elements/action_link_css.m.js'; import 'chrome://resources/cr_elements/md_select_css.m.js'; import 'chrome://resources/cr_elements/icons.m.js'; import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js'; import '../print_preview_utils.js'; import './destination_dialog_css.js'; import './destination_list.js'; import './print_preview_search_box.js'; import './print_preview_shared_css.js'; import './print_preview_vars_css.js'; import './provisional_destination_resolver.js'; import '../strings.m.js'; import './throbber_css.js'; import './destination_list_item.js'; import {CrDialogElement} from 'chrome://resources/cr_elements/cr_dialog/cr_dialog.m.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {EventTracker} from 'chrome://resources/js/event_tracker.m.js'; import {ListPropertyUpdateMixin} from 'chrome://resources/js/list_property_update_mixin.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {WebUIListenerMixin} from 'chrome://resources/js/web_ui_listener_mixin.js'; import {beforeNextRender, html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {Destination, GooglePromotedDestinationId} from '../data/destination.js'; import {DestinationStore, DestinationStoreEventType} from '../data/destination_store.js'; import {PrintServerStore, PrintServerStoreEventType} from '../data/print_server_store.js'; import {DestinationSearchBucket, MetricsContext} from '../metrics.js'; import {NativeLayerImpl} from '../native_layer.js'; import {PrintServer, PrintServersConfig} from '../native_layer_cros.js'; import {PrintPreviewDestinationListItemElement} from './destination_list_item.js'; import {PrintPreviewSearchBoxElement} from './print_preview_search_box.js'; import {PrintPreviewProvisionalDestinationResolverElement} from './provisional_destination_resolver.js'; type PrintServersChangedEventDetail = { printServerNames: string[], isSingleServerFetchingMode: boolean, }; export interface PrintPreviewDestinationDialogCrosElement { $: { dialog: CrDialogElement, provisionalResolver: PrintPreviewProvisionalDestinationResolverElement, searchBox: PrintPreviewSearchBoxElement, }; } const PrintPreviewDestinationDialogCrosElementBase = ListPropertyUpdateMixin(WebUIListenerMixin(PolymerElement)); export class PrintPreviewDestinationDialogCrosElement extends PrintPreviewDestinationDialogCrosElementBase { static get is() { return 'print-preview-destination-dialog-cros'; } static get template() { return html`{__html_template__}`; } static get properties() { return { destinationStore: { type: Object, observer: 'onDestinationStoreSet_', }, activeUser: { type: String, observer: 'onActiveUserChange_', }, currentDestinationAccount: String, users: Array, printServerSelected_: { type: String, value: '', observer: 'onPrintServerSelected_', }, destinations_: { type: Array, value: () => [], }, loadingDestinations_: { type: Boolean, value: false, }, metrics_: Object, searchQuery_: { type: Object, value: null, }, isSingleServerFetchingMode_: { type: Boolean, value: false, }, printServerNames_: { type: Array, value() { return ['']; }, }, loadingServerPrinters_: { type: Boolean, value: false, }, loadingAnyDestinations_: { type: Boolean, computed: 'computeLoadingDestinations_(' + 'loadingDestinations_, loadingServerPrinters_)' }, }; } destinationStore: DestinationStore; activeUser: string; currentDestinationAccount: string; users: string[]; private printServerSelected_: string; private destinations_: Destination[]; private loadingDestinations_: boolean; private metrics_: MetricsContext; private searchQuery_: RegExp|null; private isSingleServerFetchingMode_: boolean; private printServerNames_: string[]; private loadingServerPrinters_: boolean; private loadingAnyDestinations_: boolean; private tracker_: EventTracker = new EventTracker(); private destinationInConfiguring_: Destination|null = null; private initialized_: boolean = false; private printServerStore_: PrintServerStore|null = null; disconnectedCallback() { super.disconnectedCallback(); this.tracker_.removeAll(); } ready() { super.ready(); this.addEventListener('keydown', e => this.onKeydown_(e as KeyboardEvent)); this.printServerStore_ = new PrintServerStore( (eventName: string, callback: (p: any) => void) => this.addWebUIListener(eventName, callback)); this.tracker_.add( this.printServerStore_, PrintServerStoreEventType.PRINT_SERVERS_CHANGED, this.onPrintServersChanged_.bind(this)); this.tracker_.add( this.printServerStore_, PrintServerStoreEventType.SERVER_PRINTERS_LOADING, this.onServerPrintersLoading_.bind(this)); this.printServerStore_.getPrintServersConfig().then(config => { this.printServerNames_ = config.printServers.map(printServer => printServer.name); this.isSingleServerFetchingMode_ = config.isSingleServerFetchingMode; }); if (this.destinationStore) { this.printServerStore_.setDestinationStore(this.destinationStore); } } private fireAccountChange_(account: string) { this.dispatchEvent(new CustomEvent( 'account-change', {bubbles: true, composed: true, detail: account})); } private onKeydown_(e: KeyboardEvent) { e.stopPropagation(); const searchInput = this.$.searchBox.getSearchInput(); if (e.key === 'Escape' && (e.composedPath()[0] !== searchInput || !searchInput.value.trim())) { this.$.dialog.cancel(); e.preventDefault(); } } private onDestinationStoreSet_() { assert(this.destinations_.length === 0); const destinationStore = assert(this.destinationStore); this.tracker_.add( destinationStore, DestinationStoreEventType.DESTINATIONS_INSERTED, this.updateDestinations_.bind(this)); this.tracker_.add( destinationStore, DestinationStoreEventType.DESTINATION_SEARCH_DONE, this.updateDestinations_.bind(this)); this.initialized_ = true; if (this.printServerStore_) { this.printServerStore_.setDestinationStore(this.destinationStore); } } private onActiveUserChange_() { if (this.activeUser) { this.shadowRoot!.querySelector('select')!.value = this.activeUser; } this.updateDestinations_(); } private updateDestinations_() { if (this.destinationStore === undefined || !this.initialized_) { return; } this.updateList( 'destinations_', destination => destination.key, this.getDestinationList_()); this.loadingDestinations_ = this.destinationStore.isPrintDestinationSearchInProgress; } private getDestinationList_(): Destination[] { // Filter out the 'Save to Drive' option so it is not shown in the // list of available options. return this.destinationStore.destinations(this.activeUser) .filter( destination => destination.id !== GooglePromotedDestinationId.DOCS && destination.id !== GooglePromotedDestinationId.SAVE_TO_DRIVE_CROS); } private onCloseOrCancel_() { if (this.searchQuery_) { this.$.searchBox.setValue(''); } const cancelled = this.$.dialog.getNative().returnValue !== 'success'; this.metrics_.record( cancelled ? DestinationSearchBucket.DESTINATION_CLOSED_UNCHANGED : DestinationSearchBucket.DESTINATION_CLOSED_CHANGED); if (this.currentDestinationAccount && this.currentDestinationAccount !== this.activeUser) { this.fireAccountChange_(this.currentDestinationAccount); } } private onCancelButtonClick_() { this.$.dialog.cancel(); } /** * @param e Event containing the selected destination list item element. */ private onDestinationSelected_( e: CustomEvent<PrintPreviewDestinationListItemElement>) { const listItem = e.detail; const destination = listItem.destination; // ChromeOS local destinations that don't have capabilities need to be // configured before selecting, and provisional destinations need to be // resolved. Other destinations can be selected. if (destination.readyForSelection) { this.selectDestination_(destination); return; } // Provisional destinations if (destination.isProvisional) { this.$.provisionalResolver.resolveDestination(destination) .then(this.selectDestination_.bind(this)) .catch(function() { console.warn( 'Failed to resolve provisional destination: ' + destination.id); }) .then(() => { if (this.$.dialog.open && listItem && !listItem.hidden) { listItem.focus(); } }); return; } // Destination must be a CrOS local destination that needs to be set up. // The user is only allowed to set up printer at one time. if (this.destinationInConfiguring_) { return; } // Show the configuring status to the user and resolve the destination. listItem.onConfigureRequestAccepted(); this.destinationInConfiguring_ = destination; this.destinationStore.resolveCrosDestination(destination) .then( response => { this.destinationInConfiguring_ = null; listItem.onConfigureComplete(true); destination.capabilities = response.capabilities; this.selectDestination_(destination); // After destination is selected, start fetching for the EULA // URL. this.destinationStore.fetchEulaUrl(destination.id); }, () => { this.destinationInConfiguring_ = null; listItem.onConfigureComplete(false); }); } private selectDestination_(destination: Destination) { this.destinationStore.selectDestination(destination); this.$.dialog.close(); } show() { if (!this.metrics_) { this.metrics_ = MetricsContext.destinationSearch(); } this.$.dialog.showModal(); this.loadingDestinations_ = this.destinationStore === undefined || this.destinationStore.isPrintDestinationSearchInProgress; this.metrics_.record(DestinationSearchBucket.DESTINATION_SHOWN); if (this.activeUser) { beforeNextRender(assert(this.shadowRoot!.querySelector('select')), () => { this.shadowRoot!.querySelector('select')!.value = this.activeUser; }); } } /** @return Whether the dialog is open. */ isOpen(): boolean { return this.$.dialog.hasAttribute('open'); } private onPrintServerSelected_(printServerName: string) { if (!this.printServerStore_) { return; } this.printServerStore_.choosePrintServers(printServerName); } /** * @param e Event containing the current print server names and fetching mode. */ private onPrintServersChanged_( e: CustomEvent<PrintServersChangedEventDetail>) { this.isSingleServerFetchingMode_ = e.detail.isSingleServerFetchingMode; this.printServerNames_ = e.detail.printServerNames; } /** * @param e Event containing whether server printers are currently loading. */ private onServerPrintersLoading_(e: CustomEvent<boolean>) { this.loadingServerPrinters_ = e.detail; } private computeLoadingDestinations_(): boolean { return this.loadingDestinations_ || this.loadingServerPrinters_; } private onUserChange_() { const select = this.shadowRoot!.querySelector('select')!; const account = select.value; if (account) { this.loadingDestinations_ = true; this.fireAccountChange_(account); this.metrics_.record(DestinationSearchBucket.ACCOUNT_CHANGED); } else { select.value = this.activeUser; NativeLayerImpl.getInstance().signIn(); this.metrics_.record(DestinationSearchBucket.ADD_ACCOUNT_SELECTED); } } private onManageButtonClick_() { this.metrics_.record(DestinationSearchBucket.MANAGE_BUTTON_CLICKED); NativeLayerImpl.getInstance().managePrinters(); } } customElements.define( PrintPreviewDestinationDialogCrosElement.is, PrintPreviewDestinationDialogCrosElement);
the_stack
import __Vec2 = require("./Vec2") export import Vec2 = __Vec2.Vec2; import __Vec3 = require("./Vec3") export import Vec3 = __Vec3.Vec3; import __Quat = require("./Quat") export import Quat = __Quat.Quat; import __Color = require("./Color") export import Color = __Color.Color; import __Transform = require("./Transform") export import Transform = __Transform.Transform; import __Component = require("./Component") declare function __CPP_Debug_DrawCross(pos: Vec3, size: number, color: Color, transform: Transform): void; declare function __CPP_Debug_DrawLines(lines: Debug.Line[], color: Color): void; declare function __CPP_Debug_Draw2DLines(lines: Debug.Line[], color: Color): void; declare function __CPP_Debug_DrawLineBox(min: Vec3, max: Vec3, color: Color, transform: Transform): void; declare function __CPP_Debug_DrawSolidBox(min: Vec3, max: Vec3, color: Color, transform: Transform): void; declare function __CPP_Debug_DrawLineSphere(center: Vec3, radius: number, color: Color, transform: Transform): void; declare function __CPP_Debug_Draw2DText(text: string, pos: Vec2, color: Color, sizeInPixel: number, alignHorz: Debug.HorizontalAlignment): void; declare function __CPP_Debug_Draw3DText(text: string, pos: Vec3, color: Color, sizeInPixel: number): void; declare function __CPP_Debug_DrawInfoText(corner: Debug.ScreenPlacement, text: string, color: Color): void; declare function __CPP_Debug_GetResolution(): Vec2; declare function __CPP_Debug_ReadCVarBool(name: string): boolean; declare function __CPP_Debug_ReadCVarInt(name: string): number; declare function __CPP_Debug_ReadCVarFloat(name: string): number; declare function __CPP_Debug_ReadCVarString(name: string): string; declare function __CPP_Debug_WriteCVarBool(name: string, value: boolean): void; declare function __CPP_Debug_WriteCVarInt(name: string, value: number): void; declare function __CPP_Debug_WriteCVarFloat(name: string, value: number): void; declare function __CPP_Debug_WriteCVarString(name: string, value: string): void; declare function __CPP_Debug_RegisterCVar(name: string, type: number, defaultValue: any, description: string): void; declare function __CPP_Debug_RegisterCFunc(owner: __Component.TypescriptComponent, funcName: string, funcDesc: string, func: any, ...argTypes: Debug.ArgType[]): void; /** * Debug visualization functionality. */ export namespace Debug { export enum HorizontalAlignment { Left, Center, Right, } export enum ScreenPlacement { TopLeft, TopCenter, TopRight, BottomLeft, BottomCenter, BottomRight, } // TODO: // DrawLineBoxCorners // DrawLineCapsuleZ // DrawLineFrustum export function GetResolution(): Vec2 { return __CPP_Debug_GetResolution(); } /** * Renders a cross of three lines at the given position. * * @param pos Position in world-space where to render the cross. * @param size Length of the cross lines. * @param color Color of the cross lines. * @param transform Optional transformation (rotation, scale, translation) of the cross. */ export function DrawCross(pos: Vec3, size: number, color: Color, transform: Transform = null): void { __CPP_Debug_DrawCross(pos, size, color, transform); } /** * Represents a line in 3D. */ export class Line { startX: number = 0; startY: number = 0; startZ: number = 0; endX: number = 0; endY: number = 0; endZ: number = 0; } /** * Draws a set of lines with one color in 3D world space. */ export function DrawLines(lines: Line[], color: Color = null): void { __CPP_Debug_DrawLines(lines, color); } /** * Draws a set of lines with one color in 2D screen space. Depth (z coordinate) is used for sorting but not for perspective. */ export function Draw2DLines(lines: Line[], color: Color = null): void { __CPP_Debug_Draw2DLines(lines, color); } /** * Draws an axis-aligned box out of lines. * If the box should not be axis-aligned, the rotation must be set through the transform parameter. * * @param min The minimum corner of the AABB. * @param max The maximum corner of the AABB. * @param color The color of the lines. * @param transform Optional transformation (rotation, scale, translation) of the bbox. */ export function DrawLineBox(min: Vec3, max: Vec3, color: Color = null, transform: Transform = null): void { __CPP_Debug_DrawLineBox(min, max, color, transform); } /** * Draws an axis-aligned solid box. * If the box should not be axis-aligned, the rotation must be set through the transform parameter. * * @param min The minimum corner of the AABB. * @param max The maximum corner of the AABB. * @param color The color of the faces. * @param transform Optional transformation (rotation, scale, translation) of the bbox. */ export function DrawSolidBox(min: Vec3, max: Vec3, color: Color = null, transform: Transform = null): void { __CPP_Debug_DrawSolidBox(min, max, color, transform); } /** * Draws a sphere out of lines. * * @param center The world-space position of the sphere. * @param radius The radius of the sphere. * @param color The color of the lines. * @param transform An optional transform. Mostly for convenience to just pass in an object's transform, * but also makes it possible to squash the sphere with non-uniform scaling. */ export function DrawLineSphere(center: Vec3, radius: number, color: Color = null, transform: Transform = null): void { __CPP_Debug_DrawLineSphere(center, radius, color, transform); } /** * Draws text at a pixel position on screen. * * The string may contain newlines (\n) for multi-line output. * If horizontal alignment is right, the entire text block is aligned according to the longest line. * * Data can be output as a table, by separating columns with tabs (\n). For example:\n * "| Col 1\t| Col 2\t| Col 3\t|\n| abc\t| 42\t| 11.23\t|" * * @param pos The screen-space position where to render the text. * @param sizeInPixel The size of the text in pixels. */ export function Draw2DText(text: string, pos: Vec2, color: Color = null, sizeInPixel: number = 16, alignHorz: HorizontalAlignment = HorizontalAlignment.Left): void { __CPP_Debug_Draw2DText(text, pos, color, sizeInPixel, alignHorz); } /** * Draws text at a 3D position, always facing the camera. * * @param pos The world-space position where to render the text. * @param sizeInPixel The size of the text in pixels. The text will always be the same size and facing the camera. */ export function Draw3DText(text: string, pos: Vec3, color: Color = null, sizeInPixel: number = 16): void { __CPP_Debug_Draw3DText(text, pos, color, sizeInPixel); } /** * Draws text in one of the screen corners. * Makes sure text in the same corner does not overlap. * Has the same formatting options as Draw2DText(). * * @param corner In which area of the screen to position the text. */ export function DrawInfoText(corner: Debug.ScreenPlacement, text: string, color: Color = null): void { __CPP_Debug_DrawInfoText(corner, text, color); } /** * Reads the boolean CVar of the given name and returns its value. * If no CVar with this name exists or it uses a different type, 'undefined' is returned. */ export function ReadCVar_Boolean(name: string): boolean { // [tested] return __CPP_Debug_ReadCVarBool(name); } /** * Reads the boolean CVar of the given name and returns its value. * If no CVar with this name exists or it uses a different type, 'undefined' is returned. */ export function ReadCVar_Int(name: string): number { // [tested] return __CPP_Debug_ReadCVarInt(name); } /** * Reads the boolean CVar of the given name and returns its value. * If no CVar with this name exists or it uses a different type, 'undefined' is returned. */ export function ReadCVar_Float(name: string): number { // [tested] return __CPP_Debug_ReadCVarFloat(name); } /** * Reads the boolean CVar of the given name and returns its value. * If no CVar with this name exists or it uses a different type, 'undefined' is returned. */ export function ReadCVar_String(name: string): string { // [tested] return __CPP_Debug_ReadCVarString(name); } /** * Stores the given value in the CVar with the provided name. * Throws an error if no such CVar exists or the existing one is not of the expected type. */ export function WriteCVar_Boolean(name: string, value: boolean): void { // [tested] return __CPP_Debug_WriteCVarBool(name, value); } /** * Stores the given value in the CVar with the provided name. * Throws an error if no such CVar exists or the existing one is not of the expected type. */ export function WriteCVar_Int(name: string, value: number): void { // [tested] return __CPP_Debug_WriteCVarInt(name, value); } /** * Stores the given value in the CVar with the provided name. * Throws an error if no such CVar exists or the existing one is not of the expected type. */ export function WriteCVar_Float(name: string, value: number): void { // [tested] return __CPP_Debug_WriteCVarFloat(name, value); } /** * Stores the given value in the CVar with the provided name. * Throws an error if no such CVar exists or the existing one is not of the expected type. */ export function WriteCVar_String(name: string, value: string): void { // [tested] return __CPP_Debug_WriteCVarString(name, value); } /** * Creates a new CVar with the given name, value and description. * If a CVar with this name was already created before, the call is ignored. * The CVar can be modified like any other CVar and thus allows external configuration of the script code. * When the world in which this script is executed is destroyed, the CVar will cease existing as well. */ export function RegisterCVar_Int(name: string, value: number, description: string): void { // [tested] __CPP_Debug_RegisterCVar(name, 0, value, description); } /** * See RegisterCVar_Int */ export function RegisterCVar_Float(name: string, value: number, description: string): void { // [tested] __CPP_Debug_RegisterCVar(name, 1, value, description); } /** * See RegisterCVar_Int */ export function RegisterCVar_Boolean(name: string, value: boolean, description: string): void { // [tested] __CPP_Debug_RegisterCVar(name, 2, value, description); } /** * See RegisterCVar_Int */ export function RegisterCVar_String(name: string, value: string, description: string): void { // [tested] __CPP_Debug_RegisterCVar(name, 3, value, description); } export enum ArgType { // see ezVariant::Type for values Boolean = 2, Number = 12, String = 27, } /** * Registers a function as a console function. * The function can be registered multiple times with different 'func' arguments, to bind the call to multiple objects, * however, the list of argument types must be identical each time. * * @param owner The component that owns this function. If the component dies, the function will not be called anymore. * @param funcName The name under which to expose the function. E.g. "Print" * @param funcDesc A description of the function. Should ideally begin with the argument list to call it by. E.g.: "(text: string): Prints 'text' on screen." * @param func The typescript function to execute. Must accept the arguments as described by 'argTypes'. E.g. "function Print(text: string)". * @param argTypes Variadic list describing the type of each argument. E.g. "ez.Debug.ArgType.String, ez.Debug.ArgType.Number" */ export function RegisterConsoleFunc(owner: __Component.TypescriptComponent, funcName: string, funcDesc: string, func: any, ...argTypes: Debug.ArgType[]): void { // [tested] __CPP_Debug_RegisterCFunc(owner, funcName, funcDesc, func, ...argTypes); } }
the_stack
require('dotenv').config(); import { FileStorageProviderEnum } from '@gauzy/contracts'; import { IEnvironment, IGauzyFeatures } from './ienvironment'; if (process.env.IS_ELECTRON && process.env.GAUZY_USER_PATH) { require('app-root-path').setPath(process.env.GAUZY_USER_PATH); } export const environment: IEnvironment = { port: process.env.API_PORT || 3000, host: process.env.API_HOST || 'http://localhost', baseUrl: process.env.API_BASE_URL || 'http://localhost:3000', clientBaseUrl: process.env.CLIENT_BASE_URL || 'http://localhost:4200', production: true, envName: 'prod', env: { LOG_LEVEL: 'debug' }, EXPRESS_SESSION_SECRET: process.env.EXPRESS_SESSION_SECRET || 'gauzy', USER_PASSWORD_BCRYPT_SALT_ROUNDS: 12, JWT_SECRET: process.env.JWT_SECRET || 'secretKey', fileSystem: { name: (process.env.FILE_PROVIDER as FileStorageProviderEnum) || FileStorageProviderEnum.LOCAL }, awsConfig: { accessKeyId: process.env.AWS_ACCESS_KEY_ID, secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY, region: process.env.AWS_REGION, s3: { bucket: process.env.AWS_S3_BUCKET } }, facebookConfig: { loginDialogUri: 'https://www.facebook.com/v2.12/dialog/oauth', accessTokenUri: 'https://graph.facebook.com/v2.12/oauth/access_token', clientId: process.env.FACEBOOK_CLIENT_ID, clientSecret: process.env.FACEBOOK_CLIENT_SECRET, fbGraphVersion: process.env.FACEBOOK_GRAPH_VERSION, oauthRedirectUri: process.env.FACEBOOK_CALLBACK_URL || `${process.env.API_HOST}:${process.env.API_PORT}/api/auth/facebook/callback`, state: '{fbstate}' }, googleConfig: { clientId: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, callbackUrl: process.env.GOOGLE_CALLBACK_URL || `${process.env.API_HOST}:${process.env.API_PORT}/api/auth/google/callback` }, githubConfig: { clientId: process.env.GITHUB_CLIENT_ID, clientSecret: process.env.GITHUB_CLIENT_SECRET, callbackUrl: process.env.GITHUB_CALLBACK_URL || `http://${process.env.API_HOST}:${process.env.API_PORT}/api/auth/google/callback` }, microsoftConfig: { clientId: process.env.MICROSOFT_CLIENT_ID, clientSecret: process.env.MICROSOFT_CLIENT_SECRET, resource: process.env.MICROSOFT_RESOURCE, tenant: process.env.MICROSOFT_TENANT, callbackUrl: process.env.MICROSOFT_CALLBACK_URL || `http://${process.env.API_HOST}:${process.env.API_PORT}/api/auth/microsoft/callback` }, linkedinConfig: { clientId: process.env.LINKEDIN_CLIENT_ID, clientSecret: process.env.LINKEDIN_CLIENT_SECRET, callbackUrl: process.env.LINKEDIN_CALLBACK_URL || `http://${process.env.API_HOST}:${process.env.API_PORT}/api/auth/linked/callback` }, twitterConfig: { clientId: process.env.TWITTER_CLIENT_ID, clientSecret: process.env.TWITTER_CLIENT_SECRET, callbackUrl: process.env.TWITTER_CALLBACK_URL || `http://${process.env.API_HOST}:${process.env.API_PORT}/api/auth/twitter/callback` }, fiverrConfig: { clientId: process.env.FIVERR_CLIENT_ID, clientSecret: process.env.FIVERR_CLIENT_SECRET }, keycloakConfig: { realm: process.env.KEYCLOAK_REALM, clientId: process.env.KEYCLOAK_CLIENT_ID, secret: process.env.KEYCLOAK_SECRET, authServerUrl: process.env.KEYCLOAK_AUTH_SERVER_URL, cookieKey: process.env.KEYCLOAK_COOKIE_KEY }, auth0Config: { clientID: process.env.AUTH0_CLIENT_ID, clientSecret: process.env.AUTH0_CLIENT_SECRET, domain: process.env.AUTH0_DOMAIN }, sentry: { dns: process.env.SENTRY_DSN }, defaultIntegratedUserPass: process.env.INTEGRATED_USER_DEFAULT_PASS || '123456', upworkConfig: { callbackUrl: process.env.UPWORK_CALLBACK_URL || `http://${process.env.API_HOST}:${process.env.API_PORT}/api/integrations/upwork/callback` }, isElectron: process.env.IS_ELECTRON === 'true' ? true : false, gauzyUserPath: process.env.GAUZY_USER_PATH, allowSuperAdminRole: process.env.ALLOW_SUPER_ADMIN_ROLE === 'false' ? false : true, /** * Endpoint for Gauzy AI API (optional), e.g.: http://localhost:3005/graphql */ gauzyAIGraphQLEndpoint: process.env.GAUZY_AI_GRAPHQL_ENDPOINT, gauzyCloudEndpoint: process.env.GAUZY_CLOUD_ENDPOINT, smtpConfig: { host: process.env.MAIL_HOST, port: parseInt(process.env.MAIL_PORT, 10), secure: process.env.MAIL_PORT === '465' ? true : false, // true for 465, false for other ports auth: { user: process.env.MAIL_USERNAME, pass: process.env.MAIL_PASSWORD }, from: process.env.MAIL_FROM_ADDRESS }, defaultCurrency: process.env.DEFAULT_CURRENCY || 'USD', unleashConfig: { url: process.env.UNLEASH_API_URL, appName: process.env.UNLEASH_APP_NAME, environment: 'production', instanceId: process.env.UNLEASH_INSTANCE_ID, refreshInterval: parseInt(process.env.UNLEASH_REFRESH_INTERVAL) || 1000, metricsInterval: parseInt(process.env.UNLEASH_METRICS_INTERVAL) || 1000 }, demo: process.env.DEMO === 'true' ? true : false, demoCredentialConfig: { superAdminEmail: process.env.DEMO_SUPER_ADMIN_EMAIL || `admin@ever.co`, superAdminPassword: process.env.DEMO_SUPER_ADMIN_PASSWORD || `admin`, adminEmail: process.env.DEMO_ADMIN_EMAIL || `local.admin@ever.co`, adminPassword: process.env.DEMO_ADMIN_PASSWORD || `admin`, employeeEmail: process.env.DEMO_EMPLOYEE_EMAIL || `employee@ever.co`, employeePassword: process.env.DEMO_EMPLOYEE_PASSWORD || `123456` }, }; export const gauzyToggleFeatures: IGauzyFeatures = { FEATURE_DASHBOARD: process.env.FEATURE_DASHBOARD === 'false' ? false : true, FEATURE_TIME_TRACKING: process.env.FEATURE_TIME_TRACKING === 'false' ? false : true, FEATURE_ESTIMATE: process.env.FEATURE_ESTIMATE === 'false' ? false : true, FEATURE_ESTIMATE_RECEIVED: process.env.FEATURE_ESTIMATE_RECEIVED === 'false' ? false : true, FEATURE_INVOICE: process.env.FEATURE_INVOICE === 'false' ? false : true, FEATURE_INVOICE_RECURRING: process.env.FEATURE_INVOICE_RECURRING === 'false' ? false : true, FEATURE_INVOICE_RECEIVED: process.env.FEATURE_INVOICE_RECEIVED === 'false' ? false : true, FEATURE_INCOME: process.env.FEATURE_INCOME === 'false' ? false : true, FEATURE_EXPENSE: process.env.FEATURE_EXPENSE === 'false' ? false : true, FEATURE_PAYMENT: process.env.FEATURE_PAYMENT === 'false' ? false : true, FEATURE_PROPOSAL: process.env.FEATURE_PROPOSAL === 'false' ? false : true, FEATURE_PROPOSAL_TEMPLATE: process.env.FEATURE_PROPOSAL_TEMPLATE === 'false' ? false : true, FEATURE_PIPELINE: process.env.FEATURE_PIPELINE === 'false' ? false : true, FEATURE_PIPELINE_DEAL: process.env.FEATURE_PIPELINE_DEAL === 'false' ? false : true, FEATURE_DASHBOARD_TASK: process.env.FEATURE_DASHBOARD_TASK === 'false' ? false : true, FEATURE_TEAM_TASK: process.env.FEATURE_TEAM_TASK === 'false' ? false : true, FEATURE_MY_TASK: process.env.FEATURE_MY_TASK === 'false' ? false : true, FEATURE_JOB: process.env.FEATURE_JOB === 'false' ? false : true, FEATURE_EMPLOYEES: process.env.FEATURE_EMPLOYEES === 'false' ? false : true, FEATURE_EMPLOYEE_TIME_ACTIVITY: process.env.FEATURE_EMPLOYEE_TIME_ACTIVITY === 'false' ? false : true, FEATURE_EMPLOYEE_TIMESHEETS: process.env.FEATURE_EMPLOYEE_TIMESHEETS === 'false' ? false : true, FEATURE_EMPLOYEE_APPOINTMENT: process.env.FEATURE_EMPLOYEE_APPOINTMENT === 'false' ? false : true, FEATURE_EMPLOYEE_APPROVAL: process.env.FEATURE_EMPLOYEE_APPROVAL === 'false' ? false : true, FEATURE_EMPLOYEE_APPROVAL_POLICY: process.env.FEATURE_EMPLOYEE_APPROVAL_POLICY === 'false' ? false : true, FEATURE_EMPLOYEE_LEVEL: process.env.FEATURE_EMPLOYEE_LEVEL === 'false' ? false : true, FEATURE_EMPLOYEE_POSITION: process.env.FEATURE_EMPLOYEE_POSITION === 'false' ? false : true, FEATURE_EMPLOYEE_TIMEOFF: process.env.FEATURE_EMPLOYEE_TIMEOFF === 'false' ? false : true, FEATURE_EMPLOYEE_RECURRING_EXPENSE: process.env.FEATURE_EMPLOYEE_RECURRING_EXPENSE === 'false' ? false : true, FEATURE_EMPLOYEE_CANDIDATE: process.env.FEATURE_EMPLOYEE_CANDIDATE === 'false' ? false : true, FEATURE_MANAGE_INTERVIEW: process.env.FEATURE_MANAGE_INTERVIEW === 'false' ? false : true, FEATURE_MANAGE_INVITE: process.env.FEATURE_MANAGE_INVITE === 'false' ? false : true, FEATURE_ORGANIZATION: process.env.FEATURE_ORGANIZATION === 'false' ? false : true, FEATURE_ORGANIZATION_EQUIPMENT: process.env.FEATURE_ORGANIZATION_EQUIPMENT === 'false' ? false : true, FEATURE_ORGANIZATION_INVENTORY: process.env.FEATURE_ORGANIZATION_INVENTORY === 'false' ? false : true, FEATURE_ORGANIZATION_TAG: process.env.FEATURE_ORGANIZATION_TAG === 'false' ? false : true, FEATURE_ORGANIZATION_VENDOR: process.env.FEATURE_ORGANIZATION_VENDOR === 'false' ? false : true, FEATURE_ORGANIZATION_PROJECT: process.env.FEATURE_ORGANIZATION_PROJECT === 'false' ? false : true, FEATURE_ORGANIZATION_DEPARTMENT: process.env.FEATURE_ORGANIZATION_DEPARTMENT === 'false' ? false : true, FEATURE_ORGANIZATION_TEAM: process.env.FEATURE_ORGANIZATION_TEAM === 'false' ? false : true, FEATURE_ORGANIZATION_DOCUMENT: process.env.FEATURE_ORGANIZATION_DOCUMENT === 'false' ? false : true, FEATURE_ORGANIZATION_EMPLOYMENT_TYPE: process.env.FEATURE_ORGANIZATION_EMPLOYMENT_TYPE === 'false' ? false : true, FEATURE_ORGANIZATION_RECURRING_EXPENSE: process.env.FEATURE_ORGANIZATION_RECURRING_EXPENSE === 'false' ? false : true, FEATURE_ORGANIZATION_HELP_CENTER: process.env.FEATURE_ORGANIZATION_HELP_CENTER === 'false' ? false : true, FEATURE_CONTACT: process.env.FEATURE_CONTACT === 'false' ? false : true, FEATURE_GOAL: process.env.FEATURE_GOAL === 'false' ? false : true, FEATURE_GOAL_REPORT: process.env.FEATURE_GOAL_REPORT === 'false' ? false : true, FEATURE_GOAL_SETTING: process.env.FEATURE_GOAL_SETTING === 'false' ? false : true, FEATURE_REPORT: process.env.FEATURE_REPORT === 'false' ? false : true, FEATURE_USER: process.env.FEATURE_USER === 'false' ? false : true, FEATURE_ORGANIZATIONS: process.env.FEATURE_ORGANIZATIONS === 'false' ? false : true, FEATURE_APP_INTEGRATION: process.env.FEATURE_APP_INTEGRATION === 'false' ? false : true, FEATURE_SETTING: process.env.FEATURE_SETTING === 'false' ? false : true, FEATURE_EMAIL_HISTORY: process.env.FEATURE_EMAIL_HISTORY === 'false' ? false : true, FEATURE_EMAIL_TEMPLATE: process.env.FEATURE_EMAIL_TEMPLATE === 'false' ? false : true, FEATURE_IMPORT_EXPORT: process.env.FEATURE_IMPORT_EXPORT === 'false' ? false : true, FEATURE_FILE_STORAGE: process.env.FEATURE_FILE_STORAGE === 'false' ? false : true, FEATURE_PAYMENT_GATEWAY: process.env.FEATURE_PAYMENT_GATEWAY === 'false' ? false : true, FEATURE_SMS_GATEWAY: process.env.FEATURE_SMS_GATEWAY === 'false' ? false : true, FEATURE_SMTP: process.env.FEATURE_SMTP === 'false' ? false : true, FEATURE_ROLES_PERMISSION: process.env.FEATURE_ROLES_PERMISSION === 'false' ? false : true };
the_stack
import { ComponentFixture, fakeAsync, TestBed, tick, waitForAsync } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { Component, Type, ViewChild } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { Subject } from 'rxjs'; import { PicklistModule } from './picklist.module'; import { PicklistService } from './picklist.service'; import { PicklistComponent } from './picklist.component'; describe('PicklistComponent', () => { describe('custom templates', () => { it('should display custom option template', waitForAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" [(ngModel)]="selectedCities"> <ng-template hcPickOptionTmp let-item="item"> <div class="custom-option">{{item.name}}</div> </ng-template> </hc-picklist>`); fixture.detectChanges(); fixture.whenStable().then(() => { const el = fixture.debugElement.query(By.css('.custom-option')).nativeElement; expect(el).not.toBeNull(); }); })); it('should display custom header templates', waitForAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" [(ngModel)]="selectedCities"> <ng-template hcPaneHeaderLeftTmp><span class="header-left">left header</span></ng-template> <ng-template hcPaneHeaderRightTmp><span class="header-right">right header</span></ng-template> </hc-picklist>`); fixture.detectChanges(); fixture.whenStable().then(() => { const toolbar = fixture.debugElement.query(By.css('.header-left')).nativeElement; expect(toolbar.innerHTML).toBe('left header'); const footer = fixture.debugElement.query(By.css('.header-right')).nativeElement; expect(footer.innerHTML).toBe('right header'); }); })); it('should display custom footer and toolbar template', waitForAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" [(ngModel)]="selectedCities"> <ng-template hcPaneToolbarTmp> <span class="toolbar-label">toolbar</span> </ng-template> <ng-template hcPaneFooterTmp> <span class="footer-label">footer</span> </ng-template> </hc-picklist>`); fixture.detectChanges(); fixture.whenStable().then(() => { const toolbar = fixture.debugElement.query(By.css('.toolbar-label')).nativeElement; expect(toolbar.innerHTML).toBe('toolbar'); const footer = fixture.debugElement.query(By.css('.footer-label')).nativeElement; expect(footer.innerHTML).toBe('footer'); }); })); it('should display custom item template', waitForAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" [(ngModel)]="selectedCities" [addCustomItem]="true"> <ng-template hcPickCustomItemTmp let-search="searchTerm"> <span class="custom-item-template">{{searchTerm}}</span> </ng-template> </hc-picklist>`); fixture.componentInstance.picklist._availablePane.searchTerm = 'custom-item'; fixture.componentInstance.picklist._detectChanges(); fixture.detectChanges(); fixture.whenStable().then(() => { const template = fixture.debugElement.query(By.css('.custom-item-template')).nativeElement; expect(template).toBeDefined(); }); })); it('should display custom pane headers', waitForAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" [(ngModel)]="selectedCities" [addCustomItem]="true"> <ng-template hcPickCustomItemTmp let-search="searchTerm"> <span class="custom-item-template">{{searchTerm}}</span> </ng-template> </hc-picklist>`); fixture.componentInstance.picklist._availablePane.searchTerm = 'custom-item'; fixture.componentInstance.picklist._detectChanges(); fixture.detectChanges(); fixture.whenStable().then(() => { const template = fixture.debugElement.query(By.css('.custom-item-template')).nativeElement; expect(template).toBeDefined(); }); })); }); describe('max selected items', () => { it('should be able to select only two elements', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" [(ngModel)]="selectedCities" [maxSelectedItems]="2"> </hc-picklist>`); const arrowIcon = fixture.debugElement.query(By.css('.hc-picklist-right-arrow-btn')); const availablePane = fixture.componentInstance.picklist._availablePane; tickAndDetectChanges(fixture); availablePane.select(availablePane.itemsList.items[1]); availablePane.select(availablePane.itemsList.items[2]); tickAndDetectChanges(fixture); expect(arrowIcon.nativeElement.disabled).toBeFalsy(); fixture.componentInstance.picklist.moveLeftToRight(); tickAndDetectChanges(fixture); availablePane.select(availablePane.itemsList.items[1]); tickAndDetectChanges(fixture); expect(arrowIcon.nativeElement.disabled).toBeTruthy(); })); }); describe('HTML template based items', () => { it('should create items from hc-pick-option', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist> <hc-pick-option [value]="true">Yes</hc-pick-option> <hc-pick-option [value]="false">No</hc-pick-option> </hc-picklist>`); tickAndDetectChanges(fixture); const items = fixture.componentInstance.picklist._availablePane.itemsList.items; expect(items.length).toBe(3); expect(items[1]).toEqual(jasmine.objectContaining({ label: 'Yes', value: true, disabled: false })); expect(items[2]).toEqual(jasmine.objectContaining({ label: 'No', value: false, disabled: false })); })); it('should be able to update hc-pick-option state', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist> <hc-pick-option [disabled]="disabled" [value]="true">Yes</hc-pick-option> <hc-pick-option [value]="false">No</hc-pick-option> </hc-picklist>`); tickAndDetectChanges(fixture); const picklist = fixture.componentInstance.picklist; expect(picklist._availablePane.itemsList.items[1].disabled).toBeFalsy(); fixture.componentInstance.disabled = true; tickAndDetectChanges(fixture); expect(picklist._availablePane.itemsList.items[1].disabled).toBeTruthy(); })); it('should be able to update hc-pick-option label', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist> <hc-pick-option [disabled]="disabled" [value]="true">{{label}}</hc-pick-option> <hc-pick-option [value]="false">No</hc-pick-option> </hc-picklist>`); fixture.componentInstance.label = 'Indeed'; tickAndDetectChanges(fixture); const items = fixture.componentInstance.picklist._availablePane.itemsList.items; expect(items[1].label).toBe('Indeed'); })); }); describe('Model bindings and data changes', () => { let picklist: PicklistComponent; it('should update ngModel on value change', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" bindLabel="name" [(ngModel)]="selectedCities"></hc-picklist>`); picklist = fixture.componentInstance.picklist; // select two cities selectOptions(picklist, [1, 2]); expect(fixture.componentInstance.selectedCities.length).toBe(2); expect(fixture.componentInstance.selectedCities[0].name).toBe('Vilnius'); expect(fixture.componentInstance.selectedCities[1].name).toBe('Kaunas'); // empty out selection picklist._selectedPane.selectAll(); picklist.moveRightToLeft(); expect(fixture.componentInstance.selectedCities.length).toBe(0); })); it('should update internal model on ngModel change', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" bindLabel="name" [(ngModel)]="selectedCities"></hc-picklist>`); picklist = fixture.componentInstance.picklist; fixture.componentInstance.selectedCities = [fixture.componentInstance.cities[0]]; tickAndDetectChanges(fixture); expect(picklist._selectedPane.itemsList.items.length).toBe(2); expect(picklist._selectedPane.itemsList.items[1].label).toBe('Vilnius'); fixture.componentInstance.selectedCities = []; tickAndDetectChanges(fixture); expect(picklist._selectedPane.itemsList.items).toEqual([]); })); it('should update internal model after it was toggled with *ngIf', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist *ngIf="visible" [items]="cities" bindLabel="name" [(ngModel)]="selectedCities"></hc-picklist>`); // select first city fixture.componentInstance.selectedCities = [fixture.componentInstance.cities[0]]; tickAndDetectChanges(fixture); expect(fixture.componentInstance.picklist._selectedPane.itemsList.items.length).toBe(2); // toggle to hide/show fixture.componentInstance.toggleVisible(); tickAndDetectChanges(fixture); fixture.componentInstance.toggleVisible(); tickAndDetectChanges(fixture); fixture.componentInstance.selectedCities = []; tickAndDetectChanges(fixture); expect(fixture.componentInstance.picklist._selectedPane.itemsList.items.length).toBe(0); })); describe('when ngModel set with a value that is not an exisiting option', () => { it('when bindValue is used, should throw an error', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" bindLabel="name" bindValue="id" [(ngModel)]="selectedCityIds"></hc-picklist>`); fixture.componentInstance.cities = []; expect(() => { fixture.componentInstance.selectedCityIds = [7]; tickAndDetectChanges(fixture); }).toThrow(); })); it(`should set items correctly when bindValue is not used`, fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" bindLabel="name" [(ngModel)]="selectedCities"></hc-picklist>`); // clear out available options, set 'Pailgis' as selected fixture.componentInstance.cities = []; fixture.componentInstance.selectedCities = [{ id: 7, name: 'Pailgis' }]; tickAndDetectChanges(fixture); picklist = fixture.componentInstance.picklist; expect(picklist._selectedPane.itemsList.items[1].label).toBe('Pailgis'); expect(picklist._availablePane.itemsList.items.length).toBe(0); // even if pailgis added as an option later, should be removed from available list because its already selected fixture.componentInstance.cities = [{ id: 7, name: 'Pailgis' }]; tickAndDetectChanges(fixture); expect(picklist._availablePane.itemsList.items.length).toBe(0); })); it('should bind whole object as value when bindValue prop is specified with empty string in template', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" bindLabel="name" bindValue="" [(ngModel)]="selectedCities"></hc-picklist>`); // clear out available options, set 'Pailgis' as selected fixture.componentInstance.cities = []; fixture.componentInstance.selectedCities = [{ id: 7, name: 'Pailgis' }]; tickAndDetectChanges(fixture); picklist = fixture.componentInstance.picklist; expect(picklist._selectedPane.itemsList.items[1].label).toBe('Pailgis'); expect(picklist._availablePane.itemsList.items.length).toBe(0); })); it('when externalSearchSubject is used', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" bindLabel="name" [externalSearchSubject]="filter" [(ngModel)]="selectedCities"> </hc-picklist>`); picklist = fixture.componentInstance.picklist; fixture.componentInstance.cities = []; fixture.componentInstance.selectedCities = [{ id: 1, name: 'Vilnius' }, { id: 2, name: 'Kaunas' }]; tickAndDetectChanges(fixture); expect(picklist._selectedPane.itemsList.items.length).toBe(3); expect(picklist._selectedPane.itemsList.items[1]).toEqual(jasmine.objectContaining({ label: 'Vilnius', value: { id: 1, name: 'Vilnius' } })); expect(picklist._selectedPane.itemsList.items[2]).toEqual(jasmine.objectContaining({ label: 'Kaunas', value: { id: 2, name: 'Kaunas' } })); fixture.componentInstance.cities = [ { id: 1, name: 'Vilnius' }, { id: 2, name: 'Kaunas' }, { id: 3, name: 'Pabrade' }, ]; tickAndDetectChanges(fixture); expect(picklist._selectedPane.itemsList.items[1]).toEqual(jasmine.objectContaining({ label: 'Vilnius', value: { id: 1, name: 'Vilnius' } })); expect(picklist._selectedPane.itemsList.items[2]).toEqual(jasmine.objectContaining({ label: 'Kaunas', value: { id: 2, name: 'Kaunas' } })); })); it('should set items correctly if there is no bindLabel', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" [(ngModel)]="selectedCities"></hc-picklist>`); fixture.componentInstance.cities = []; fixture.componentInstance.selectedCities = [{ id: 7, name: 'Pailgis' }]; tickAndDetectChanges(fixture); fixture.componentInstance.cities = [{ id: 1, name: 'Vilnius' }, { id: 2, name: 'Kaunas' }]; tickAndDetectChanges(fixture); expect(fixture.componentInstance.picklist._selectedPane.itemsList.items[1]).toEqual(jasmine.objectContaining({ value: { id: 7, name: 'Pailgis' } })); })); it('should handle a simple primitive value', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="citiesNames" [(ngModel)]="selectedCities"></hc-picklist>`); fixture.componentInstance.cities = []; tickAndDetectChanges(fixture); fixture.componentInstance.selectedCities = [<any>'Kaunas']; tickAndDetectChanges(fixture); expect(fixture.componentInstance.picklist._selectedPane.itemsList.items[1]).toEqual(jasmine.objectContaining({ value: 'Kaunas', label: 'Kaunas' })); })); }); it('should preserve latest selected value when items are changing', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" bindLabel="name" [(ngModel)]="selectedCities"></hc-picklist>`); picklist = fixture.componentInstance.picklist; // select a couple options, refresh available items fixture.componentInstance.selectedCities = [fixture.componentInstance.cities[0]]; selectOptions(picklist, [1, 2]); tickAndDetectChanges(fixture); fixture.componentInstance.cities = [...fixture.componentInstance.cities]; tickAndDetectChanges(fixture); expect(fixture.componentInstance.selectedCities.length).toBe(2); // empty out selection, refresh available items picklist._selectedPane.selectAll(); picklist.moveRightToLeft(); tickAndDetectChanges(fixture); fixture.componentInstance.cities = [...fixture.componentInstance.cities]; tickAndDetectChanges(fixture); expect(fixture.componentInstance.selectedCities.length).toBe(0); })); it('should map selected items with items in dropdown', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" bindLabel="name" [(ngModel)]="selectedCities"></hc-picklist>`); picklist = fixture.componentInstance.picklist; fixture.componentInstance.selectedCities = [fixture.componentInstance.cities[0]]; tickAndDetectChanges(fixture); fixture.componentInstance.cities = [...fixture.componentInstance.cities]; tickAndDetectChanges(fixture); expect(fixture.componentInstance.selectedCities[0]).toEqual(fixture.componentInstance.cities[0]); })); it('should clear disabled selected values when setting new model', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" bindLabel="name" [(ngModel)]="selectedCities"></hc-picklist>`); const disabled = { ...fixture.componentInstance.cities[1], disabled: true }; fixture.componentInstance.selectedCities = <any>[fixture.componentInstance.cities[0], disabled]; tickAndDetectChanges(fixture); fixture.componentInstance.cities[1].disabled = true; fixture.componentInstance.cities = [...fixture.componentInstance.cities]; tickAndDetectChanges(fixture); fixture.componentInstance.selectedCities = []; tickAndDetectChanges(fixture); expect(fixture.componentInstance.picklist._selectedPane.items).toEqual([]); })); it('should clear previous selected value even if it is disabled', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" bindLabel="name" [(ngModel)]="selectedCities"></hc-picklist>`); fixture.componentInstance.cities[0].disabled = true; fixture.componentInstance.cities = [...fixture.componentInstance.cities]; fixture.componentInstance.selectedCities = [fixture.componentInstance.cities[0]]; tickAndDetectChanges(fixture); fixture.componentInstance.selectedCities = [fixture.componentInstance.cities[1]]; tickAndDetectChanges(fixture); expect(fixture.componentInstance.picklist._selectedPane.itemsList.items[1].label) .toBe(fixture.componentInstance.cities[1].name); })); it('should clear previous select value when setting new model', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" bindLabel="name" [(ngModel)]="selectedCities"></hc-picklist>`); fixture.componentInstance.selectedCities = [fixture.componentInstance.cities[0]]; tickAndDetectChanges(fixture); picklist = fixture.componentInstance.picklist; expect(picklist._selectedPane.itemsList.items.length).toBe(2); // default group + 1 items fixture.componentInstance.selectedCities = [fixture.componentInstance.cities[1]]; tickAndDetectChanges(fixture); expect(picklist._selectedPane.itemsList.items.length).toBe(2); // default group + 1 items fixture.componentInstance.selectedCities = []; tickAndDetectChanges(fixture); expect(picklist._selectedPane.items.length).toBe(0); })); it('should bind to custom object properties', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" bindLabel="name" bindValue="id" [(ngModel)]="selectedCityIds"> </hc-picklist>`); picklist = fixture.componentInstance.picklist; // from component to model selectOptions(picklist, [1]); tickAndDetectChanges(fixture); expect(fixture.componentInstance.selectedCityIds[0]).toEqual(1); // from model to component fixture.componentInstance.selectedCityIds = [2]; tickAndDetectChanges(fixture); expect(fixture.componentInstance.picklist._selectedPane.itemsList.items[1]).toEqual(jasmine.objectContaining({ value: fixture.componentInstance.cities[1] })); })); it('should bind to nested label property', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="countries" bindLabel="description.name" [(ngModel)]="selectedCountries"> </hc-picklist>`); picklist = fixture.componentInstance.picklist; // from component to model selectOptions(picklist, [2]); fixture.detectChanges(); expect(fixture.componentInstance.picklist._selectedPane.itemsList.items[1]).toEqual(jasmine.objectContaining({ label: 'USA', value: fixture.componentInstance.countries[1] })); // from model to component fixture.componentInstance.selectedCountries = [fixture.componentInstance.countries[0]]; tickAndDetectChanges(fixture); expect(fixture.componentInstance.picklist._selectedPane.itemsList.items[1]).toEqual(jasmine.objectContaining({ label: 'Lithuania', value: fixture.componentInstance.countries[0] })); })); it('should bind to nested value property', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="countries" bindLabel="description.name" bindValue="description.id" [(ngModel)]="selectedCountries"> </hc-picklist>`); picklist = fixture.componentInstance.picklist; // from component to model selectOptions(picklist, [1]); tickAndDetectChanges(fixture); expect(fixture.componentInstance.selectedCountries[0]).toEqual('a'); // from model to component fixture.componentInstance.selectedCountries = [fixture.componentInstance.countries[2].description.id]; tickAndDetectChanges(fixture); expect(fixture.componentInstance.picklist._selectedPane.itemsList.items[1]).toEqual(jasmine.objectContaining({ label: 'Australia', value: fixture.componentInstance.countries[2] })); selectOptions(picklist, [3]); tickAndDetectChanges(fixture); expect(fixture.componentInstance.selectedCountries[0]).toEqual('c'); })); it('should bind to simple array', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="citiesNames" [(ngModel)]="selectedCities"></hc-picklist>`); picklist = fixture.componentInstance.picklist; // from component to model selectOptions(picklist, [1]); tickAndDetectChanges(fixture); expect(fixture.componentInstance.selectedCities[0]).toBe(<any>'Vilnius'); // from model to component fixture.componentInstance.selectedCities = [<any>'Kaunas']; tickAndDetectChanges(fixture); expect(fixture.componentInstance.picklist._selectedPane.itemsList.items[1]) .toEqual(jasmine.objectContaining({ label: 'Kaunas', value: 'Kaunas' })); })); it('should bind to object', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" bindLabel="name" [(ngModel)]="selectedCities"></hc-picklist>`); picklist = fixture.componentInstance.picklist; // from component to model selectOptions(picklist, [1]); tickAndDetectChanges(fixture); expect(fixture.componentInstance.selectedCities[0]).toEqual(fixture.componentInstance.cities[0]); // from model to component fixture.componentInstance.selectedCities = [fixture.componentInstance.cities[1]]; tickAndDetectChanges(fixture); expect(picklist._selectedPane.itemsList.items[1]).toEqual(jasmine.objectContaining({ value: fixture.componentInstance.cities[1] })); })); describe('hc-pick-option', () => { it('should create items from hc-pick-option', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [(ngModel)]="selectedCityIds"> <hc-pick-option *ngFor="let city of cities" [value]="city.id">{{city.name}}</hc-pick-option> </hc-picklist>`); picklist = fixture.componentInstance.picklist; tickAndDetectChanges(fixture); expect(picklist._availablePane.itemsList.items.length).toEqual(4); // 3 given cities plus default group })); it('should be possible to clear out items set from hc-pick-options', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [(ngModel)]="selectedCityIds"> <hc-pick-option *ngFor="let city of cities" [value]="city.id">{{city.name}}</hc-pick-option> </hc-picklist>`); picklist = fixture.componentInstance.picklist; tickAndDetectChanges(fixture); expect(picklist._availablePane.itemsList.items.length).toEqual(4); fixture.componentInstance.cities = []; tickAndDetectChanges(fixture); expect(picklist._availablePane.itemsList.items.length).toEqual(0); })); it('should bind value', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [(ngModel)]="selectedCityIds"> <hc-pick-option [value]="1">A</hc-pick-option> <hc-pick-option [value]="2">B</hc-pick-option> </hc-picklist>`); picklist = fixture.componentInstance.picklist; // from component to model selectOptions(picklist, [1]); tickAndDetectChanges(fixture); expect(fixture.componentInstance.selectedCityIds[0]).toEqual(1); // from model to component fixture.componentInstance.selectedCityIds = [2]; tickAndDetectChanges(fixture); expect(fixture.componentInstance.picklist._selectedPane.itemsList.items[1]).toEqual(jasmine.objectContaining({ value: 2, label: 'B' })); })); it('should not fail while resolving selected item from object', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [(ngModel)]="selectedCities"> <hc-pick-option [value]="cities[0]">Vilnius</hc-pick-option> <hc-pick-option [value]="cities[1]">Kaunas</hc-pick-option> </hc-picklist>`); const selected = { name: 'Vilnius', id: 1 }; fixture.componentInstance.selectedCities = [selected]; tickAndDetectChanges(fixture); expect(fixture.componentInstance.picklist._selectedPane.itemsList.items[1]).toEqual(jasmine.objectContaining({ value: selected, label: '' })); })); }); describe('Pre-selected model', () => { it('should select by bindValue when primitive type', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" bindLabel="name" bindValue="id" placeholder="select value" [(ngModel)]="selectedCityIds"> </hc-picklist>`); fixture.componentInstance.selectedCityIds = [2]; tickAndDetectChanges(fixture); const result = jasmine.objectContaining({ value: { id: 2, name: 'Kaunas' }}); expect(fixture.componentInstance.picklist._selectedPane.itemsList.items[1]).toEqual(result); })); it('should select by bindValue ', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" bindLabel="name" bindValue="id" placeholder="select value" [(ngModel)]="selectedCityIds"> </hc-picklist>`); fixture.componentInstance.cities = [{ id: 0, name: 'Vilnius' }]; fixture.componentInstance.selectedCityIds = [0]; tickAndDetectChanges(fixture); const result = jasmine.objectContaining({ value: { id: 0, name: 'Vilnius' }}); expect(fixture.componentInstance.picklist._selectedPane.itemsList.items[1]).toEqual(result); })); it('should select by bindLabel when binding to object', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" bindLabel="name" placeholder="select value" [(ngModel)]="selectedCities"> </hc-picklist>`); fixture.componentInstance.selectedCities = [{ id: 2, name: 'Kaunas' }]; tickAndDetectChanges(fixture); const result = jasmine.objectContaining({ value: { id: 2, name: 'Kaunas' }}); expect(fixture.componentInstance.picklist._selectedPane.itemsList.items[1]).toEqual(result); })); it('should select by object reference', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" bindLabel="name" placeholder="select value" [(ngModel)]="selectedCities"> </hc-picklist>`); fixture.componentInstance.selectedCities = [fixture.componentInstance.cities[1]]; tickAndDetectChanges(fixture); const result = jasmine.objectContaining({ value: { id: 2, name: 'Kaunas' }}); expect(fixture.componentInstance.picklist._selectedPane.itemsList.items[1]).toEqual(result); })); it('should select by compareWith function when bindValue is not used', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" bindLabel="name" placeholder="select value" [compareWith]="compareWith" [(ngModel)]="selectedCities"> </hc-picklist>`); const city = { name: 'Vilnius', id: 7, district: 'Ozo parkas' }; fixture.componentInstance.cities.push(city); fixture.componentInstance.cities = [...fixture.componentInstance.cities]; fixture.componentInstance.selectedCities = [{ name: 'Vilnius', district: 'Ozo parkas' } as any]; tickAndDetectChanges(fixture); expect(fixture.componentInstance.picklist._selectedPane.itemsList.items[1].value).toEqual(city); })); it('should select by compareWith function when bindValue is used', fakeAsync(() => { const fixture = createTestingModule( HcPicklistTestCmp, `<hc-picklist [items]="cities" bindLabel="name" bindValue="id" placeholder="select value" [compareWith]="compareWith" [(ngModel)]="selectedCityIds"> </hc-picklist>`); const cmp = fixture.componentInstance; cmp.selectedCityIds = [cmp.cities[1].id.toString()]; cmp.compareWith = (city, model: string) => city.id === +model; tickAndDetectChanges(fixture); expect(cmp.picklist._selectedPane.itemsList.items[1].value).toEqual(cmp.cities[1]); })); }); }); }); function createTestingModule<T>(cmp: Type<T>, template: string): ComponentFixture<T> { TestBed.configureTestingModule({ imports: [FormsModule, PicklistModule], declarations: [cmp], providers: [PicklistService] }) .overrideComponent(cmp, { set: { template: template } }); TestBed.compileComponents(); const fixture = TestBed.createComponent(cmp); fixture.detectChanges(); return fixture; } @Component({ template: `` }) class HcPicklistTestCmp { @ViewChild(PicklistComponent, { static: false }) picklist: PicklistComponent; label = 'Yes'; clearOnBackspace = false; disabled = false; readonly = false; dropdownPosition = 'bottom'; visible = true; externalSearchTermMinLength = 0; filter = new Subject<string>(); searchFn: (term: string, item: any) => boolean; selectOnTab = true; hideSelected = false; citiesLoading = false; selectedCityIds: number[]; selectedCities: { id: number; name: string }[]; cities: any[] = [ { id: 1, name: 'Vilnius' }, { id: 2, name: 'Kaunas' }, { id: 3, name: 'Pabrade' }, ]; citiesNames = this.cities.map(x => x.name); selectedCountries = new Array<any>(); countries = [ { id: 1, description: { name: 'Lithuania', id: 'a' } }, { id: 2, description: { name: 'USA', id: 'b' } }, { id: 3, description: { name: 'Australia', id: 'c' } } ]; customItemFunc(term: string) { return { id: term, name: term, custom: true }; } customItemFuncPromise(term: string) { return Promise.resolve({ id: 5, name: term, valid: true }); } compareWith(a, b) { return a.name === b.name && a.district === b.district; } toggleVisible() { this.visible = !this.visible; } } function tickAndDetectChanges(fixture: ComponentFixture<any>) { fixture.detectChanges(); tick(); } function selectOptions(picklist: PicklistComponent, indicesToSelect: number[]) { indicesToSelect.forEach(i => { picklist._availablePane.select(picklist._availablePane.itemsList.items[i]); }); picklist.moveLeftToRight(); }
the_stack
import { asyncExec } from './utils' export enum ContactShieldSetting { DEFAULT_INCUBATION_PERIOD = 14 } export enum ContactShieldEngine { TOKEN_A = "TOKEN_WINDOW_MODE" } export enum HMSPermission { ACCESS_NETWORK_STATE = "android.permission.ACCESS_NETWORK_STATE", BLUETOOTH = "android.permission.BLUETOOTH", BLUETOOTH_ADMIN = "android.permission.BLUETOOTH_ADMIN", ACCESS_COARSE_LOCATION = "android.permission.ACCESS_COARSE_LOCATION", ACCESS_FINE_LOCATION = "android.permission.ACCESS_FINE_LOCATION" } export enum RiskLevel { RISK_LEVEL_INVALID = 0, RISK_LEVEL_LOWEST = 1, RISK_LEVEL_LOW = 2, RISK_LEVEL_MEDIUM_LOW = 3, RISK_LEVEL_MEDIUM = 4, RISK_LEVEL_MEDIUM_HIGH = 5, RISK_LEVEL_HIGH = 6, RISK_LEVEL_EXT_HIGH = 7, RISK_LEVEL_HIGHEST = 8 } export enum HMSStatusCode { STATUS_SUCCESS = 0, STATUS_FAILURE = -1, STATUS_API_DISORDER = 8001, STATUS_APP_QUOTA_LIMITED = 8100, STATUS_DISK_FULL = 8101, STATUS_BLUETOOTH_OPERATION_ERROR = 8102, STATUS_MISSING_PERMISSION_BLUETOOTH = 8016, STATUS_MISSING_SETTING_LOCATION_ON = 8020, STATUS_INTERNAL_ERROR = 8060, STATUS_MISSING_PERMISSION_INTERNET = 8064 } export interface PeriodicKey { content: Int8Array; initialRiskLevel: number; periodicKeyLifeTime: number; periodicKeyValidTime: number; reportType: number; } export interface SharedKeyData { token: string; diagnosisConfiguration: DiagnosisConfiguration; fileList: string[] } export interface SharedKeyDataKeys { token: string; diagnosisConfiguration: DiagnosisConfiguration; fileList: string[]; publicKeys: string[]; } export interface SharedKeyDataMapping { daysSinceCreationToContagiousness: any; defaultReportType: number; defaultContagiousness: number; } export interface DailySketchConfiguration { weightsOfReportType: number[], weightsOfContagiousness: number[], thresholdOfAttenuationInDb: number[], weightsOfAttenuationBucket: number[], thresholdOfDaysSinceHit: number, minWindowScore: number, } export interface DiagnosisConfiguration { attenuationDurationThresholds?: number[]; attenuationRiskValues?: number[]; attenuationWeight?: number; daysAfterContactedRiskValues?: number[]; daysAfterContactedWeight?: number; durationRiskValues?: number[]; durationWeight?: number; initialRiskLevelRiskValues?: number[]; initialRiskLevelWeight?: number; minimumRiskValueThreshold?: number; } export interface ContactSketch { attenuationDurations: number[]; daysSinceLastHit: number; maxRiskValue: number; numberOfHits: number; summationRiskValue: number; } export interface ContactDetail { attenuationDurations: number[]; attenuationRiskValue: number; dayNumber: number; durationMinutes: number; initialRiskLevel: number; totalRiskValue: number; } export interface ContactWindow { dateMillis: number; reportType: number; scanInfos: ScanInfo[]; } export interface ScanInfo { averageAttenuation: number; minimumAttenuation: number; secondsSinceLastScan: number; } export interface StatusCode { statusCode: number; statusMessage: string; } export function clearData(): Promise<void> { return asyncExec('HMSContactShield', 'ContactShieldModule', ["clearData"]); } export function getContactDetail(token: string): Promise<ContactDetail[]> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['getContactDetail', token ? token : ""]); } export function startContactShield(incubationPeriod: number): Promise<void> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['startContactShield', incubationPeriod ? incubationPeriod : ContactShieldSetting.DEFAULT_INCUBATION_PERIOD]); } export function startContactShieldOld(incubationPeriod: number): Promise<void> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['startContactShieldOld', incubationPeriod ? incubationPeriod : ContactShieldSetting.DEFAULT_INCUBATION_PERIOD]); } export function startContactShieldNoPersistent(incubationPeriod: number): Promise<void> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['startContactShieldNoPersistent', incubationPeriod ? incubationPeriod : ContactShieldSetting.DEFAULT_INCUBATION_PERIOD]); } export function stopContactShield(): Promise<void> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['stopContactShield']); } export function getContactSketch(token: string): Promise<ContactSketch> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['getContactSketch', token ? token : ""]); } export function getContactWindow(token: string): Promise<ContactWindow[]> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['getContactWindow', token ? token : ""]); } export function getPeriodicKey(): Promise<PeriodicKey[]> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['getPeriodicKey']); } export async function isContactShieldRunning(): Promise<boolean> { const { result } = await asyncExec('HMSContactShield', 'ContactShieldModule', ['isContactShieldRunning']); return result; } export function putSharedKeyFiles(sharedKeyData: SharedKeyData): Promise<void> { // Set defaults sharedKeyData.diagnosisConfiguration = Object.assign({ attenuationDurationThresholds: [50, 74], attenuationRiskValues: [4, 4, 4, 4, 4, 4, 4, 4], attenuationWeight: 50, daysAfterContactedRiskValues: [4, 4, 4, 4, 4, 4, 4, 4], daysAfterContactedWeight: 50, durationRiskValues: [4, 4, 4, 4, 4, 4, 4, 4], durationWeight: 50, initialRiskLevelRiskValues: [4, 4, 4, 4, 4, 4, 4, 4], initialRiskLevelWeight: 50, minimumRiskValueThreshold: 1 }, sharedKeyData.diagnosisConfiguration) return asyncExec('HMSContactShield', 'ContactShieldModule', ['putSharedKeyFiles', sharedKeyData]); } export function putSharedKeyFilesOld(sharedKeyData: SharedKeyData): Promise<void> { // Set defaults sharedKeyData.diagnosisConfiguration = Object.assign({ attenuationDurationThresholds: [50, 74], attenuationRiskValues: [4, 4, 4, 4, 4, 4, 4, 4], attenuationWeight: 50, daysAfterContactedRiskValues: [4, 4, 4, 4, 4, 4, 4, 4], daysAfterContactedWeight: 50, durationRiskValues: [4, 4, 4, 4, 4, 4, 4, 4], durationWeight: 50, initialRiskLevelRiskValues: [4, 4, 4, 4, 4, 4, 4, 4], initialRiskLevelWeight: 50, minimumRiskValueThreshold: 1 }, sharedKeyData.diagnosisConfiguration) return asyncExec('HMSContactShield', 'ContactShieldModule', ['putSharedKeyFilesOld', sharedKeyData]); } export function disableLogger(): Promise<void> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['disableLogger']); } export function enableLogger(): Promise<void> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['enableLogger']); } export function handleCallback(event: string, callback: (data: any) => void): void { window.subscribeHMSEvent(event, callback); } export function registerReceiver(): Promise<void> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['registerReceiver']); } export function unregisterReceiver(): Promise<void> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['unregisterReceiver']); } export function hasPermission(permission: HMSPermission): Promise<boolean> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['hasPermission', permission]); } export function requestPermissions(permissions: HMSPermission[]): Promise<void> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['requestPermissions', permissions]); } export function getStatus(): Promise<any> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['getStatus']); } export function getContactShieldVersion(): Promise<number> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['getContactShieldVersion']); } export function getDeviceCalibrationConfidence(): Promise<number> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['getDeviceCalibrationConfidence']); } export function isSupportScanningWithoutLocation(): Promise<boolean> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['isSupportScanningWithoutLocation']); } export function setSharedKeysDataMapping(sharedKey: SharedKeyDataMapping): Promise<any> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['setSharedKeysDataMapping', sharedKey]); } export function getSharedKeysDataMapping(): Promise<SharedKeyDataMapping> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['getSharedKeysDataMapping']); } export function getDailySketch(dailySketch: DailySketchConfiguration): Promise<any> { // Set defaults dailySketch = Object.assign({ weightsOfReportType: [0], weightsOfContagiousness: [0], thresholdOfAttenuationInDb: [0], weightsOfAttenuationBucket: [0], thresholdOfDaysSinceHit: 0, minWindowScore: 0, }, dailySketch) return asyncExec('HMSContactShield', 'ContactShieldModule', ['getDailySketch', dailySketch]); } export function putSharedKeyFilesKeys(sharedKeyFiles: SharedKeyDataKeys): Promise<any> { // Set defaults sharedKeyFiles.diagnosisConfiguration = Object.assign({ attenuationDurationThresholds: [50, 74], attenuationRiskValues: [4, 4, 4, 4, 4, 4, 4, 4], attenuationWeight: 50, daysAfterContactedRiskValues: [4, 4, 4, 4, 4, 4, 4, 4], daysAfterContactedWeight: 50, durationRiskValues: [4, 4, 4, 4, 4, 4, 4, 4], durationWeight: 50, initialRiskLevelRiskValues: [4, 4, 4, 4, 4, 4, 4, 4], initialRiskLevelWeight: 50, minimumRiskValueThreshold: 1 }, sharedKeyFiles.diagnosisConfiguration) return asyncExec('HMSContactShield', 'ContactShieldModule', ['putSharedKeyFilesKeys', sharedKeyFiles]); } export function putSharedKeyFilesProvider(files: string[]): Promise<any> { return asyncExec('HMSContactShield', 'ContactShieldModule', ['putSharedKeyFilesProvider', files]); }
the_stack
const shell = new ActiveXObject('Shell.Application'); const getWindowsFolder = () => shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfWINDOWS); // https://msdn.microsoft.com/en-us/library/windows/desktop/gg537735(v=vs.85).aspx (() => { const folder = getWindowsFolder(); if (!folder) { return; } const folderItem = folder.ParseName('system.ini'); if (!folderItem) { return; } shell.AddToRecent(folderItem.Path); })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774065(v=vs.85).aspx (() => { const folder = shell.BrowseForFolder(0, 'Example', 0, Shell32.ShellSpecialFolderConstants.ssfWINDOWS); })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/gg537736(v=vs.85).aspx const canStartStop = shell.CanStartStopService('service name'); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774069(v=vs.85).aspx shell.ControlPanelItem('desk.cpl'); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774073(v=vs.85).aspx shell.Explore('C:\\'); // https://msdn.microsoft.com/en-us/library/windows/desktop/gg537737(v=vs.85).aspx const explorerPolicy = shell.ExplorerPolicy('ValueName'); // https://msdn.microsoft.com/en-us/library/windows/desktop/gg537739(v=vs.85).aspx const settingValue = shell.GetSetting(Shell32.SettingKey.SSF_SHOWALLOBJECTS); // https://msdn.microsoft.com/en-us/library/windows/desktop/gg537740(v=vs.85).aspx const processorLevel = shell.GetSystemInformation('ProcessorLevel'); // https://msdn.microsoft.com/en-us/library/windows/desktop/gg537741(v=vs.85).aspx const isRestricted = shell.IsRestricted('system', 'undockwithoutlogon'); // https://msdn.microsoft.com/en-us/library/windows/desktop/gg537742(v=vs.85).aspx const isServiceRunning = shell.IsServiceRunning('Themes'); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774086(v=vs.85).aspx shell.Open(Shell32.ShellSpecialFolderConstants.ssfWINDOWS); // https://msdn.microsoft.com/en-us/library/windows/desktop/gg537743(v=vs.85).aspx shell.ServiceStart('Messenger', true); // https://msdn.microsoft.com/en-us/library/windows/desktop/gg537744(v=vs.85).aspx shell.ServiceStop('Messenger', true); // https://msdn.microsoft.com/en-us/library/windows/desktop/gg537745(v=vs.85).aspx shell.ShellExecute("notepad.exe", "", "", "open", Shell32.ShellExecuteShow.Normal); // https://msdn.microsoft.com/en-us/library/windows/desktop/gg537746(v=vs.85).aspx?cs-save-lang=1&cs-lang=jscript#code-snippet-1 shell.ShowBrowserBar(Shell32.ExplorerBarCLSID.Favorites, true); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774107(v=vs.85).aspx const wshShell = new ActiveXObject('WScript.Shell'); wshShell.Popup(shell.Windows().Count.toString()); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787866(v=vs.85).aspx shell.NameSpace(`c:\\windows`)!.CopyHere('c:\\autoexec.bat'); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787870(v=vs.85).aspx (() => { const folder = shell.NameSpace('c:\\windows'); const folderItem = folder ? folder.ParseName('clock.avi') : undefined; if (folder && folderItem) { const info = folder.GetDetailsOf(folderItem, Shell32.FileSystemDetails.Type); } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787874(v=vs.85).aspx shell.NameSpace('c:\\windows')!.MoveHere('c:\\temp.txt', Shell32.FileOperationFlag.FOF_NOCONFIRMATION); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787876(v=vs.85).aspx shell.NameSpace('c:\\')!.NewFolder('TestFolder'); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787858(v=vs.85).aspx (() => { const folder = shell.NameSpace("\\\\server\\share\\folder"); const offlineStatus = folder ? folder.OfflineStatus : undefined; })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787880(v=vs.85).aspx (() => { const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfPROGRAMS); WScript.Echo(folder!.ParentFolder.Title); })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787860(v=vs.85).aspx // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787816(v=vs.85).aspx // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787850(v=vs.85).aspx (() => { const folder = shell.NameSpace('C:\\WINDOWS'); const folderItem = folder ? folder.Self : undefined; if (folderItem) { const verbs = folderItem.Verbs(); folderItem.InvokeVerb(); } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787812(v=vs.85).aspx (() => { const parentFolder = getWindowsFolder(); const folderItem = parentFolder ? parentFolder.ParseName('system32') : undefined; const folder = folderItem ? folderItem.GetFolder : undefined; })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787814(v=vs.85).aspx // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787824(v=vs.85).aspx (() => { const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfPROGRAMS); const folderItem = folder ? folder.ParseName('Internet Explorer.lnk') : undefined; if (folderItem && folderItem.IsLink) { const link = folderItem.GetLink; } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787818(v=vs.85).aspx // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787819(v=vs.85).aspx // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787821(v=vs.85).aspx (() => { const folder = getWindowsFolder(); const folderItem = folder ? folder.Self : undefined; if (folderItem) { const isBrowsable = folderItem.IsBrowsable; const isFileSystem = folderItem.IsFileSystem; const isFolder = folderItem.IsFolder; } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787825(v=vs.85).aspx (() => { const folder = getWindowsFolder(); const folderItem = folder!.ParseName('notepad.exe'); if (folderItem) { const oldDate = folderItem.ModifyDate; folderItem.ModifyDate = new Date(1900, 1, 1, 18, 5).getVarDate(); } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787827(v=vs.85).aspx (() => { const rootFolder = shell.NameSpace('C:\\'); const folderItem = rootFolder ? rootFolder.ParseName('autoexec.bat') : undefined; if (folderItem) { const oldName = folderItem.Name; folderItem.Name = 'test.bat'; } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787829(v=vs.85).aspx (() => { const folder = getWindowsFolder(); const folderItem = folder ? folder.Self : undefined; const parent = folderItem ? folderItem.Parent : undefined; if (parent) { WScript.Echo('Got parent object'); } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787844(v=vs.85).aspx (() => { const folder = getWindowsFolder(); const folderItem = folder ? folder.Self : undefined; const path = folderItem ? folderItem.Path : ''; })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787846(v=vs.85).aspx (() => { const folder = getWindowsFolder(); const folderItem = folder!.ParseName('notepad.exe'); const size = folderItem ? folderItem.Size : undefined; })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787848(v=vs.85).aspx (() => { const folder = getWindowsFolder(); if (folder) { WScript.Echo(folder.Self.Type); } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787798(v=vs.85).aspx (() => { const folder = getWindowsFolder(); const folderItems = folder ? folder.Items() : undefined; const count = folderItems ? folderItems.Count : undefined; })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787794(v=vs.85).aspx (() => { const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfDRIVES); if (folder) { folder.Items().InvokeVerbEx(); } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774170(v=vs.85).aspx // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774174(v=vs.85).aspx (() => { const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfPROGRAMS); const verbs = folder ? folder.Self.Verbs() : undefined; if (verbs) { const verb = verbs.Item(0); WScript.Echo(verb.Name); verb.DoIt(); } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787787(v=vs.85).aspx (() => { const folder = getWindowsFolder(); if (folder) { const folderItems = folder.Items(); WScript.Echo(folderItems.Count); folderItems.Filter(Shell32.ShellFolderEnumerationFlags.SHCONTF_NONFOLDERS, '*.txt'); WScript.Echo(folderItems.Count); } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb787791(v=vs.85).aspx // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774162(v=vs.85).aspx (() => { const echoFirstVerbName = (folder: Shell32.Folder3 | null) => { if (!folder) { return; } const verbs = folder.Items().Verbs; WScript.Echo(verbs.Item(0).Name); }; let folder = getWindowsFolder(); echoFirstVerbName(folder); folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfCONTROLS); echoFirstVerbName(folder); })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774158(v=vs.85).aspx (() => { const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfCONTROLS); if (folder) { const verbs = folder.Self.Verbs(); WScript.Echo(verbs.Count); } })(); const getIELink = () => { const folder = shell.NameSpace(Shell32.ShellSpecialFolderConstants.ssfPROGRAMS); const folderItem = folder ? folder.ParseName('Internet Explorer.lnk') : undefined; return { link: folderItem ? folderItem.GetLink : undefined, folderItem }; }; // https://msdn.microsoft.com/en-us/library/windows/desktop/bb773990(v=vs.85).aspx (() => { const { link, folderItem } = getIELink(); if (link && folderItem) { WScript.Echo(link.GetIconLocation(folderItem.Path)); } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb773996(v=vs.85).aspx (() => { const { link } = getIELink(); if (link) { link.Resolve(Shell32.ShellLinkResolveFlags.NoUI); } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb773998(v=vs.85).aspx (() => { const { link } = getIELink(); if (link) { link.Description = 'New Description'; link.Save(); } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774002(v=vs.85).aspx (() => { const { link } = getIELink(); if (link) { link.SetIconLocation(link.Path, 1); link.Save(); } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb773986(v=vs.85).aspx (() => { const { link } = getIELink(); if (link) { WScript.Echo(link.Arguments); link.Arguments = '/s'; link.Save(); } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb773988(v=vs.85).aspx (() => { const { link } = getIELink(); if (link) { WScript.Echo(link.Description); link.Description = 'Test'; link.Save(); } })(); const parseHotkey = (hotkey: number) => { // missing implementation return { shift: false, ctrl: false, alt: false, extended: false, hotkey }; }; const buildHotkey = (hotkey: number, shift: boolean = false, ctrl: boolean = false, alt: boolean = false, extended: boolean = false) => { // missing implementation return 0; }; // https://msdn.microsoft.com/en-us/library/windows/desktop/bb773992(v=vs.85).aspx (() => { const { link } = getIELink(); if (link) { const { hotkey } = parseHotkey(link.Hotkey); WScript.Echo(hotkey); link.Hotkey = buildHotkey(4); } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb773994(v=vs.85).aspx (() => { const { link } = getIELink(); if (link) { WScript.Echo(link.Path); link.Path = 'C:\\Program Files\\IE\\IEXPLORE.EXE'; } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774006(v=vs.85).aspx (() => { const { link } = getIELink(); if (link) { WScript.Echo(link.ShowCommand); link.ShowCommand = Shell32.LinkShowWindowState.Normal; } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774008(v=vs.85).aspx (() => { const { link } = getIELink(); if (link) { WScript.Echo(link.WorkingDirectory); link.WorkingDirectory = ''; } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774115(v=vs.85).aspx (() => { const { link } = getIELink(); if (link) { const target = link.Target; if (target) { WScript.Echo(target.Size); } } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774055(v=vs.85).aspx (() => { const folder = getWindowsFolder(); const folderItem = folder ? folder.ParseName('notepad.exe') : undefined; if (folderItem) { WScript.Echo(folderItem.ExtendedProperty('infotip')); } const wordDoc = shell.NameSpace('C:\\')!.ParseName('test.doc'); if (wordDoc) { const FMTID_SummaryInfo = "{F29F85E0-4FF9-1068-AB91-08002B27B3D9}"; const PID_TITLE = "2"; const PID_AUTHOR = "4"; const SCID_TITLE = `${FMTID_SummaryInfo} ${PID_TITLE}`; const SCID_AUTHOR = `${FMTID_SummaryInfo} ${PID_AUTHOR}`; const docTitle = wordDoc.ExtendedProperty(SCID_TITLE); const docAuthor = wordDoc.ExtendedProperty(SCID_AUTHOR); } })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774057(v=vs.85).aspx (() => { const folder = getWindowsFolder(); const folderItem = folder ? folder.ParseName('notepad.exe') : undefined; if (folderItem) { folderItem.InvokeVerbEx("open", "c:\\autoexec.bat"); } })(); const collectionToArray = <T>(col: any): T[] => { // tslint:disable-line no-unnecessary-generics const results: T[] = []; const enumerator = new Enumerator<T>(col); enumerator.moveFirst(); while (!enumerator.atEnd()) { results.push(enumerator.item()); enumerator.moveNext(); } return results; }; interface String { endsWith(searchString: string, length?: number): boolean; } if (!String.prototype.endsWith) { String.prototype.endsWith = function(search, this_len) { if (this_len === undefined || this_len > this.length) { this_len = this.length; } return this.substring(this_len - search.length, this_len) === search; }; } // shell.Windows() includes items other than Explorer windows, such as Internet Explorer tabs const getExplorerWindows = () => collectionToArray<SHDocVw.InternetExplorer>(shell.Windows()) .filter(x => x.FullName.toLowerCase().endsWith('explorer.exe')); const getFolderViews = () => getExplorerWindows() .map(x => x.Document as Shell32.ShellFolderView); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774045(v=vs.85).aspx (() => { getFolderViews().forEach(x => ActiveXObject.on(x, 'SelectionChanged', function(this: Shell32.ShellFolderView) { WScript.Echo(`Selection change in ${this.Folder.Title} -- count: ${this.SelectedItems().Count}`); }) ); })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb773970(v=vs.85).aspx WScript.Echo(shell.Windows().Item().Path); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb773969(v=vs.85).aspx WScript.Echo(shell.Windows().Count); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774043(v=vs.85).aspx (() => { getFolderViews().forEach(x => WScript.Echo(`${x.Folder.Title} -- ${x.SelectedItems().Count} selected items`) ); })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774047(v=vs.85).aspx // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774022(v=vs.85).aspx // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774053(v=vs.85).aspx (() => { const folderView = getExplorerWindows()[0].Document as Shell32.ShellFolderView; const folder = folderView.Folder; if (folder) { const folderItem = folder.Self; folderView.SelectItem(folder.Self, Shell32.ShellFolderViewSelectItem.Focus); } WScript.Echo(folderView.ViewOptions); })(); // https://msdn.microsoft.com/en-us/library/windows/desktop/bb774020(v=vs.85).aspx (() => { const folderView = getExplorerWindows()[0].Document as Shell32.ShellFolderView; const focusedItem = folderView.FocusedItem; if (focusedItem) { WScript.Echo(`Focused item in first Excplorer window -- ${focusedItem.Path}`); } })(); (() => { const router = new ActiveXObject('Shell.FolderView'); const folder = getFolderViews()[0]; router.SetFolderView(folder); ActiveXObject.on(router, 'EnumDone', () => WScript.Echo('Current folder view was finisehd enumerating')); ActiveXObject.on(router, 'SelectionChanged', () => WScript.Echo('Selection changed in current folder view')); // the folder view monitored by the ShellFolderViewOC object can be changed via SetFolderView without disconnecting and reconnecting the handlers })();
the_stack
import {PolymerElement, html} from '@polymer/polymer'; import {computed, customElement, observe, property} from '@polymer/decorators'; import '../../../components/polymer/irons_and_papers'; import * as PolymerDom from '../../../components/polymer/dom'; import * as tf_graph_scene from '../tf_graph_common/scene'; import * as tf_graph_util from '../tf_graph_common/util'; import * as tf_graph_render from '../tf_graph_common/render'; import {LegacyElementMixin} from '../../../components/polymer/legacy_element_mixin'; @customElement('tf-graph-debugger-data-card') class TfGraphDebuggerDataCard extends LegacyElementMixin(PolymerElement) { static readonly template = html` <style> :host { font-size: 12px; margin: 0; padding: 0; display: block; } h2 { padding: 0; text-align: center; margin: 0; } .health-pill-legend { padding: 15px; } .health-pill-legend h2 { text-align: left; } .health-pill-entry { margin: 10px 10px 10px 0; } .health-pill-entry .color-preview { width: 26px; height: 26px; border-radius: 3px; display: inline-block; margin: 0 10px 0 0; } .health-pill-entry .color-label, .health-pill-entry .tensor-count { color: #777; display: inline-block; height: 26px; font-size: 22px; line-height: 26px; vertical-align: top; } .health-pill-entry .tensor-count { float: right; } #health-pill-step-slider { width: 100%; margin: 0 0 0 -15px; /* 31 comes from adding a padding of 15px from both sides of the paper-slider, subtracting * 1px so that the slider width aligns with the image (the last slider marker takes up 1px), * and adding 2px to account for a border of 1px on both sides of the image. 30 - 1 + 2. * Apparently, the paper-slider lacks a mixin for those padding values. */ width: calc(100% + 31px); } #health-pills-loading-spinner { width: 20px; height: 20px; vertical-align: top; } #health-pill-step-number-input { text-align: center; vertical-align: top; } #numeric-alerts-table-container { max-height: 400px; overflow-x: hidden; overflow-y: auto; } #numeric-alerts-table { text-align: left; } #numeric-alerts-table td { vertical-align: top; } #numeric-alerts-table .first-offense-td { display: inline-block; } .first-offense-td { width: 80px; } .tensor-device-td { max-width: 140px; word-wrap: break-word; } .tensor-section-within-table { color: #266236; cursor: pointer; opacity: 0.8; text-decoration: underline; } .tensor-section-within-table:hover { opacity: 1; } .device-section-within-table { color: #666; } .mini-health-pill { width: 130px; } .mini-health-pill > div { height: 100%; width: 60px; border-radius: 3px; } #event-counts-th { padding: 0 0 0 10px; } .negative-inf-mini-health-pill-section { background: rgb(255, 141, 0); width: 20px; } .positive-inf-mini-health-pill-section { background: rgb(0, 62, 212); width: 20px; } .nan-mini-health-pill-section { background: rgb(204, 47, 44); width: 20px; } .negative-inf-mini-health-pill-section, .positive-inf-mini-health-pill-section, .nan-mini-health-pill-section { color: #fff; display: inline-block; height: 100%; line-height: 20px; margin: 0 0 0 10px; text-align: center; } .no-numeric-alerts-notification { margin: 0; } </style> <paper-material elevation="1" class="card health-pill-legend"> <div class="title"> Enable all (not just sampled) steps. Requires slow disk read. </div> <paper-toggle-button id="enableAllStepsModeToggle" checked="{{allStepsModeEnabled}}" > </paper-toggle-button> <h2> Step of Health Pills: <template is="dom-if" if="[[allStepsModeEnabled]]"> <input type="number" id="health-pill-step-number-input" min="0" max="[[_biggestStepEverSeen]]" value="{{specificHealthPillStep::input}}" /> </template> <template is="dom-if" if="[[!allStepsModeEnabled]]"> [[_currentStepDisplayValue]] </template> <paper-spinner-lite active hidden$="[[!areHealthPillsLoading]]" id="health-pills-loading-spinner" ></paper-spinner-lite> </h2> <template is="dom-if" if="[[allStepsModeEnabled]]"> <paper-slider id="health-pill-step-slider" immediate-value="{{specificHealthPillStep}}" max="[[_biggestStepEverSeen]]" snaps step="1" value="{{specificHealthPillStep}}" ></paper-slider> </template> <template is="dom-if" if="[[!allStepsModeEnabled]]"> <template is="dom-if" if="[[_maxStepIndex]]"> <paper-slider id="health-pill-step-slider" immediate-value="{{healthPillStepIndex}}" max="[[_maxStepIndex]]" snaps step="1" value="{{healthPillStepIndex}}" ></paper-slider> </template> </template> <h2> Health Pill <template is="dom-if" if="[[healthPillValuesForSelectedNode]]"> Counts for Selected Node </template> <template is="dom-if" if="[[!healthPillValuesForSelectedNode]]"> Legend </template> </h2> <template is="dom-repeat" items="[[healthPillEntries]]"> <div class="health-pill-entry"> <div class="color-preview" style="background:[[item.background_color]]" ></div> <div class="color-label">[[item.label]]</div> <div class="tensor-count"> [[_computeTensorCountString(healthPillValuesForSelectedNode, index)]] </div> </div> </template> <div hidden$="[[!_hasDebuggerNumericAlerts(debuggerNumericAlerts)]]"> <h2 id="numeric-alerts-header">Numeric Alerts</h2> <p>Alerts are sorted from top to bottom by increasing timestamp.</p> <div id="numeric-alerts-table-container"> <table id="numeric-alerts-table"> <thead> <tr> <th>First Offense</th> <th>Tensor (Device)</th> <th id="event-counts-th">Event Counts</th> </tr> </thead> <tbody id="numeric-alerts-body"></tbody> </table> </div> </div> <template is="dom-if" if="[[!_hasDebuggerNumericAlerts(debuggerNumericAlerts)]]" > <p class="no-numeric-alerts-notification"> No numeric alerts so far. That is likely good. Alerts indicate the presence of NaN or (+/-) Infinity values, which may be concerning. </p> </template> </paper-material> `; @property({type: Object}) renderHierarchy: tf_graph_render.RenderGraphInfo; @property({ type: Array, notify: true, }) debuggerNumericAlerts: any; @property({type: Object}) nodeNamesToHealthPills: any; @property({ type: Number, notify: true, }) healthPillStepIndex: any; // Only relevant if we are in all steps mode, in which case the user may want to view health // pills for a specific step. @property({ type: Number, notify: true, }) specificHealthPillStep: number = 0; // Two-ways @property({ type: String, notify: true, }) selectedNode: any; @property({ type: String, notify: true, }) highlightedNode: any; // The enum value of the include property of the selected node. @property({ type: Number, notify: true, }) selectedNodeInclude: any; // Whether health pills are currently being loaded, in which case we show a spinner (and the // current health pills shown might be out of date). @property({type: Boolean}) areHealthPillsLoading: any; @property({ type: Array, }) healthPillEntries: unknown[] = tf_graph_scene.healthPillEntries; // When all-steps mode is enabled, the user can request health pills for any step. In this // mode, Tensorboard makes a request every time the user drags the slider to a different step. @property({ type: Boolean, notify: true, }) allStepsModeEnabled: any; ready() { super.ready(); var mainContainer = document.getElementById('mainContainer'); var scrollbarContainer = document.querySelector( 'tf-dashboard-layout .scrollbar' ) as HTMLElement | null; if (mainContainer && scrollbarContainer) { // If this component is being used inside of TensorBoard's dashboard layout, it may easily // cause the dashboard layout element to overflow, giving the user 2 scroll bars. Prevent // that by hiding whatever content overflows - the user will have to expand the viewport to // use this debugging card. mainContainer.style.overflow = 'hidden'; scrollbarContainer.style.overflow = 'hidden'; } } _healthPillsAvailable(debuggerDataEnabled: any, nodeNamesToHealthPills: any) { // So long as there is a mapping (even if empty) from node name to health pills, show the // legend and slider. We do that because, even if no health pills exist at the current step, // the user may desire to change steps, and the slider must show for the user to do that. return debuggerDataEnabled && nodeNamesToHealthPills; } _computeTensorCountString( healthPillValuesForSelectedNode: any, valueIndex: any ) { if (!healthPillValuesForSelectedNode) { // No health pill data is available. return ''; } return healthPillValuesForSelectedNode[valueIndex].toFixed(0); } @computed( 'nodeNamesToHealthPills', 'healthPillStepIndex', 'selectedNode', 'allStepsModeEnabled', 'areHealthPillsLoading' ) get healthPillValuesForSelectedNode(): unknown[] | null { var nodeNamesToHealthPills = this.nodeNamesToHealthPills; var healthPillStepIndex = this.healthPillStepIndex; var selectedNode = this.selectedNode; var allStepsModeEnabled = this.allStepsModeEnabled; var areHealthPillsLoading = this.areHealthPillsLoading; if (areHealthPillsLoading) { // Health pills are loading. Do not render data that is out of date. return null; } if (!selectedNode) { // No node is selected. return null; } const healthPills = nodeNamesToHealthPills[selectedNode]; if (!healthPills) { // This node lacks a health pill. return null; } // If all steps mode is enabled, we use the first health pill in the list because the JSON // response from the server is a mapping between node name and a list of 1 health pill. const healthPill = healthPills[allStepsModeEnabled ? 0 : healthPillStepIndex]; if (!healthPill) { // This node lacks a health pill at the current step. return null; } // The health pill count values start at 2. Each health pill contains 6 values. return healthPill.value.slice(2, 8); } @computed( 'nodeNamesToHealthPills', 'healthPillStepIndex', 'allStepsModeEnabled', 'specificHealthPillStep', 'areHealthPillsLoading' ) get _currentStepDisplayValue(): any { var nodeNamesToHealthPills = this.nodeNamesToHealthPills; var healthPillStepIndex = this.healthPillStepIndex; var allStepsModeEnabled = this.allStepsModeEnabled; var specificHealthPillStep = this.specificHealthPillStep; var areHealthPillsLoading = this.areHealthPillsLoading; if (allStepsModeEnabled) { // The user seeks health pills for specific step from the server. return specificHealthPillStep.toFixed(0); } if (areHealthPillsLoading) { // The current step is undefined. return 0; } for (let nodeName in nodeNamesToHealthPills) { // All nodes have the same number of steps stored, so only examine 1 node. We cannot // directly index into the nodeNamesToHealthPills object because we do not have a key. // If all steps mode is enabled, we only have 1 step to show. return nodeNamesToHealthPills[nodeName][healthPillStepIndex].step.toFixed( 0 ); } // The current step could not be computed. return 0; } // The biggest step value ever seen. Used to determine what steps of health pills to let the // user fetch in all steps mode. @computed('nodeNamesToHealthPills') get _biggestStepEverSeen(): number { var nodeNamesToHealthPills = this.nodeNamesToHealthPills; for (let nodeName in nodeNamesToHealthPills) { // All nodes have the same number of steps stored, so only examine 1 node. // The index is 1 less than the count. Tensorboard backend logic guarantees that the length // of the array will be greater than 1. var healthPills = nodeNamesToHealthPills[nodeName]; return Math.max( this._biggestStepEverSeen, healthPills[healthPills.length - 1].step ); } // No steps seen so far. Default to 0. return this._biggestStepEverSeen || 0; } @computed('nodeNamesToHealthPills') get _maxStepIndex(): number { var nodeNamesToHealthPills = this.nodeNamesToHealthPills; for (let nodeName in nodeNamesToHealthPills) { // All nodes have the same number of steps stored, so only examine 1 node. // The index is 1 less than the count. Tensorboard backend logic guarantees that the length // of the array will be greater than 1. return nodeNamesToHealthPills[nodeName].length - 1; } // Return a falsy value. The slider should be hidden. return 0; } _hasDebuggerNumericAlerts(debuggerNumericAlerts: any) { return debuggerNumericAlerts && debuggerNumericAlerts.length; } @observe('debuggerNumericAlerts') _updateAlertsList() { var debuggerNumericAlerts = this.debuggerNumericAlerts; var alertBody = this.$$('#numeric-alerts-body'); if (!alertBody) { return; } (alertBody as HTMLElement).innerText = ''; for (var i = 0; i < debuggerNumericAlerts.length; i++) { var alert = debuggerNumericAlerts[i]; var tableRow = document.createElement('tr'); var timestampTd = document.createElement('td'); timestampTd.innerText = tf_graph_util.computeHumanFriendlyTime( alert.first_timestamp ); timestampTd.classList.add('first-offense-td'); tableRow.appendChild(timestampTd); var tensorDeviceTd = document.createElement('td'); tensorDeviceTd.classList.add('tensor-device-td'); var tensorSection = document.createElement('div'); tensorSection.classList.add('tensor-section-within-table'); tensorSection.innerText = alert.tensor_name; this._addOpExpansionListener(tensorSection, alert.tensor_name); tensorDeviceTd.appendChild(tensorSection); var deviceSection = document.createElement('div'); deviceSection.classList.add('device-section-within-table'); deviceSection.innerText = '(' + alert.device_name + ')'; tensorDeviceTd.appendChild(deviceSection); tableRow.appendChild(tensorDeviceTd); var miniHealthPill = document.createElement('div'); miniHealthPill.classList.add('mini-health-pill'); var miniHealthPillTd = document.createElement('td'); miniHealthPillTd.classList.add('mini-health-pill-td'); miniHealthPillTd.appendChild(miniHealthPill); tableRow.appendChild(miniHealthPillTd); if (alert.neg_inf_event_count) { var negativeInfCountSection = document.createElement('div'); negativeInfCountSection.classList.add( 'negative-inf-mini-health-pill-section' ); negativeInfCountSection.innerText = alert.neg_inf_event_count; negativeInfCountSection.setAttribute( 'title', alert.neg_inf_event_count + ' events with -\u221E' ); miniHealthPill.appendChild(negativeInfCountSection); } if (alert.pos_inf_event_count) { var positiveInfCountSection = document.createElement('div'); positiveInfCountSection.classList.add( 'positive-inf-mini-health-pill-section' ); positiveInfCountSection.innerText = alert.pos_inf_event_count; positiveInfCountSection.setAttribute( 'title', alert.pos_inf_event_count + ' events with +\u221E' ); miniHealthPill.appendChild(positiveInfCountSection); } if (alert.nan_event_count) { var nanCountSection = document.createElement('div'); nanCountSection.classList.add('nan-mini-health-pill-section'); nanCountSection.innerText = alert.nan_event_count; nanCountSection.setAttribute( 'title', alert.nan_event_count + ' events with NaN' ); miniHealthPill.appendChild(nanCountSection); } (PolymerDom.dom(alertBody) as any).appendChild(tableRow); } } // Adds a listener to an element, so that when that element is clicked, the tensor with // tensorName expands. _addOpExpansionListener(clickableElement: any, tensorName: any) { clickableElement.addEventListener('click', () => { // When the user clicks on a tensor name, expand all nodes until the user can see the // associated node. var nameOfNodeToSelect = tf_graph_render.expandUntilNodeIsShown( document.getElementById('scene'), this.renderHierarchy, tensorName ); // Store the current scroll of the graph info card. Node selection alters that scroll, and // we restore the scroll later. var previousScrollFromBottom: any; var graphInfoCard = document.querySelector( 'tf-graph-info#graph-info' ) as any; if (graphInfoCard) { previousScrollFromBottom = graphInfoCard.scrollHeight - graphInfoCard.scrollTop; } // Update the selected node within graph logic. var previousSelectedNode = this.selectedNode; this.set('selectedNode', nameOfNodeToSelect); // Scroll the graph info card back down if necessary so that user can see the alerts section // again. Selecting the node causes the info card to scroll to the top, which may mean the // user no longer sees the list of alerts. var scrollToOriginalLocation = () => { graphInfoCard.scrollTop = graphInfoCard.scrollHeight - previousScrollFromBottom; }; if (graphInfoCard) { // This component is used within an info card. Restore the original scroll. if (previousSelectedNode) { // The card for the selected node has already opened. Immediately restore the scroll. scrollToOriginalLocation(); } else { // Give some time for the DOM of the info card to be created before scrolling down. window.setTimeout(scrollToOriginalLocation, 20); } } }); } }
the_stack
import type { Container } from "./Container"; import { colorToHsl, colorToRgb, Constants, deepExtend, drawConnectLine, drawGrabLine, drawParticle, drawParticlePlugin, drawPlugin, getStyleFromHsl, getStyleFromRgb, gradient, paintBase, } from "../Utils"; import type { Particle } from "./Particle"; import { clear } from "../Utils"; import type { IContainerPlugin, ICoordinates, IDelta, IDimension, IHsl, IParticle, IRgb, IRgba } from "./Interfaces"; /** * Canvas manager * @category Core */ export class Canvas { /** * The particles canvas */ element?: HTMLCanvasElement; /** * The particles canvas dimension */ readonly size: IDimension; resizeFactor?: IDimension; /** * The particles canvas context */ private context: CanvasRenderingContext2D | null; private generatedCanvas; private coverColor?: IRgba; private trailFillColor?: IRgba; private originalStyle?: CSSStyleDeclaration; /** * Constructor of canvas manager * @param container the parent container */ constructor(private readonly container: Container) { this.size = { height: 0, width: 0, }; this.context = null; this.generatedCanvas = false; } /* ---------- tsParticles functions - canvas ------------ */ /** * Initializes the canvas element */ init(): void { this.resize(); this.initStyle(); this.initCover(); this.initTrail(); this.initBackground(); this.paint(); } loadCanvas(canvas: HTMLCanvasElement, generatedCanvas?: boolean): void { if (!canvas.className) { canvas.className = Constants.canvasClass; } if (this.generatedCanvas) { this.element?.remove(); } this.generatedCanvas = generatedCanvas ?? this.generatedCanvas; this.element = canvas; this.originalStyle = deepExtend({}, this.element.style) as CSSStyleDeclaration; this.size.height = canvas.offsetHeight; this.size.width = canvas.offsetWidth; this.context = this.element.getContext("2d"); this.container.retina.init(); this.initBackground(); } destroy(): void { if (this.generatedCanvas) { this.element?.remove(); } this.draw((ctx) => { clear(ctx, this.size); }); } /** * Paints the canvas background */ paint(): void { const options = this.container.actualOptions; this.draw((ctx) => { if (options.backgroundMask.enable && options.backgroundMask.cover && this.coverColor) { clear(ctx, this.size); this.paintBase(getStyleFromRgb(this.coverColor, this.coverColor.a)); } else { this.paintBase(); } }); } /** * Clears the canvas content */ clear(): void { const options = this.container.actualOptions; const trail = options.particles.move.trail; if (options.backgroundMask.enable) { this.paint(); } else if (trail.enable && trail.length > 0 && this.trailFillColor) { this.paintBase(getStyleFromRgb(this.trailFillColor, 1 / trail.length)); } else { this.draw((ctx) => { clear(ctx, this.size); }); } } windowResize(): void { if (!this.element) { return; } const container = this.container; this.resize(); const needsRefresh = container.updateActualOptions(); /* density particles enabled */ container.particles.setDensity(); for (const [, plugin] of container.plugins) { if (plugin.resize !== undefined) { plugin.resize(); } } if (needsRefresh) { container.refresh(); } } /** * Calculates the size of the canvas */ resize(): void { if (!this.element) { return; } const container = this.container; const pxRatio = container.retina.pixelRatio; const size = container.canvas.size; const oldSize = { width: size.width, height: size.height, }; size.width = this.element.offsetWidth * pxRatio; size.height = this.element.offsetHeight * pxRatio; this.element.width = size.width; this.element.height = size.height; if (this.container.started) { this.resizeFactor = { width: size.width / oldSize.width, height: size.height / oldSize.height, }; } } drawConnectLine(p1: IParticle, p2: IParticle): void { this.draw((ctx) => { const lineStyle = this.lineStyle(p1, p2); if (!lineStyle) { return; } const pos1 = p1.getPosition(); const pos2 = p2.getPosition(); drawConnectLine(ctx, p1.retina.linksWidth ?? this.container.retina.linksWidth, lineStyle, pos1, pos2); }); } drawGrabLine(particle: IParticle, lineColor: IRgb, opacity: number, mousePos: ICoordinates): void { const container = this.container; this.draw((ctx) => { const beginPos = particle.getPosition(); drawGrabLine( ctx, particle.retina.linksWidth ?? container.retina.linksWidth, beginPos, mousePos, lineColor, opacity ); }); } drawParticle(particle: Particle, delta: IDelta): void { if (particle.spawning || particle.destroyed) { return; } const pfColor = particle.getFillColor(); const psColor = particle.getStrokeColor() ?? pfColor; if (!pfColor && !psColor) { return; } let [fColor, sColor] = this.getPluginParticleColors(particle); const pOptions = particle.options; const twinkle = pOptions.twinkle.particles; const twinkling = twinkle.enable && Math.random() < twinkle.frequency; if (!fColor || !sColor) { const twinkleRgb = colorToHsl(twinkle.color); if (!fColor) { fColor = twinkling && twinkleRgb !== undefined ? twinkleRgb : pfColor ? pfColor : undefined; } if (!sColor) { sColor = twinkling && twinkleRgb !== undefined ? twinkleRgb : psColor ? psColor : undefined; } } const options = this.container.actualOptions; const zIndexOptions = particle.options.zIndex; const zOpacityFactor = (1 - particle.zIndexFactor) ** zIndexOptions.opacityRate; const radius = particle.getRadius(); const opacity = twinkling ? twinkle.opacity : particle.bubble.opacity ?? particle.opacity?.value ?? 1; const strokeOpacity = particle.stroke?.opacity ?? opacity; const zOpacity = opacity * zOpacityFactor; const fillColorValue = fColor ? getStyleFromHsl(fColor, zOpacity) : undefined; if (!fillColorValue && !sColor) { return; } this.draw((ctx) => { const zSizeFactor = (1 - particle.zIndexFactor) ** zIndexOptions.sizeRate; const zStrokeOpacity = strokeOpacity * zOpacityFactor; const strokeColorValue = sColor ? getStyleFromHsl(sColor, zStrokeOpacity) : fillColorValue; if (radius <= 0) { return; } const container = this.container; for (const updater of container.particles.updaters) { if (updater.beforeDraw) { updater.beforeDraw(particle); } } drawParticle( this.container, ctx, particle, delta, fillColorValue, strokeColorValue, options.backgroundMask.enable, options.backgroundMask.composite, radius * zSizeFactor, zOpacity, particle.options.shadow, particle.gradient ); for (const updater of container.particles.updaters) { if (updater.afterDraw) { updater.afterDraw(particle); } } }); } drawPlugin(plugin: IContainerPlugin, delta: IDelta): void { this.draw((ctx) => { drawPlugin(ctx, plugin, delta); }); } drawParticlePlugin(plugin: IContainerPlugin, particle: Particle, delta: IDelta): void { this.draw((ctx) => { drawParticlePlugin(ctx, plugin, particle, delta); }); } initBackground(): void { const options = this.container.actualOptions; const background = options.background; const element = this.element; const elementStyle = element?.style; if (!elementStyle) { return; } if (background.color) { const color = colorToRgb(background.color); elementStyle.backgroundColor = color ? getStyleFromRgb(color, background.opacity) : ""; } else { elementStyle.backgroundColor = ""; } elementStyle.backgroundImage = background.image || ""; elementStyle.backgroundPosition = background.position || ""; elementStyle.backgroundRepeat = background.repeat || ""; elementStyle.backgroundSize = background.size || ""; } draw<T>(cb: (context: CanvasRenderingContext2D) => T): T | undefined { if (!this.context) { return; } return cb(this.context); } private initCover(): void { const options = this.container.actualOptions; const cover = options.backgroundMask.cover; const color = cover.color; const coverRgb = colorToRgb(color); if (coverRgb) { this.coverColor = { r: coverRgb.r, g: coverRgb.g, b: coverRgb.b, a: cover.opacity, }; } } private initTrail(): void { const options = this.container.actualOptions; const trail = options.particles.move.trail; const fillColor = colorToRgb(trail.fillColor); if (fillColor) { const trail = options.particles.move.trail; this.trailFillColor = { r: fillColor.r, g: fillColor.g, b: fillColor.b, a: 1 / trail.length, }; } } private getPluginParticleColors(particle: Particle): (IHsl | undefined)[] { let fColor: IHsl | undefined; let sColor: IHsl | undefined; for (const [, plugin] of this.container.plugins) { if (!fColor && plugin.particleFillColor) { fColor = colorToHsl(plugin.particleFillColor(particle)); } if (!sColor && plugin.particleStrokeColor) { sColor = colorToHsl(plugin.particleStrokeColor(particle)); } if (fColor && sColor) { break; } } return [fColor, sColor]; } private initStyle(): void { const element = this.element, options = this.container.actualOptions; if (!element) { return; } const originalStyle = this.originalStyle; if (options.fullScreen.enable) { this.originalStyle = deepExtend({}, element.style) as CSSStyleDeclaration; element.style.position = "fixed"; element.style.zIndex = options.fullScreen.zIndex.toString(10); element.style.top = "0"; element.style.left = "0"; element.style.width = "100%"; element.style.height = "100%"; } else if (originalStyle) { element.style.position = originalStyle.position; element.style.zIndex = originalStyle.zIndex; element.style.top = originalStyle.top; element.style.left = originalStyle.left; element.style.width = originalStyle.width; element.style.height = originalStyle.height; } } private paintBase(baseColor?: string): void { this.draw((ctx) => { paintBase(ctx, this.size, baseColor); }); } private lineStyle(p1: IParticle, p2: IParticle): CanvasGradient | undefined { return this.draw((ctx) => { const options = this.container.actualOptions; const connectOptions = options.interactivity.modes.connect; return gradient(ctx, p1, p2, connectOptions.links.opacity); }); } }
the_stack
import EntityConfiguration from './EntityConfiguration'; import { EntityQueryContext } from './EntityQueryContext'; import { getDatabaseFieldForEntityField, transformDatabaseObjectToFields, transformFieldsToDatabaseObject, FieldTransformerMap, } from './internal/EntityFieldTransformationUtils'; interface SingleValueFieldEqualityCondition<TFields, N extends keyof TFields = keyof TFields> { fieldName: N; fieldValue: TFields[N]; } interface MultiValueFieldEqualityCondition<TFields, N extends keyof TFields = keyof TFields> { fieldName: N; fieldValues: readonly TFields[N][]; } export type FieldEqualityCondition<TFields, N extends keyof TFields = keyof TFields> = | SingleValueFieldEqualityCondition<TFields, N> | MultiValueFieldEqualityCondition<TFields, N>; export function isSingleValueFieldEqualityCondition< TFields, N extends keyof TFields = keyof TFields >( condition: FieldEqualityCondition<TFields, N> ): condition is SingleValueFieldEqualityCondition<TFields, N> { return (condition as SingleValueFieldEqualityCondition<TFields, N>).fieldValue !== undefined; } export interface TableFieldSingleValueEqualityCondition { tableField: string; tableValue: any; } export interface TableFieldMultiValueEqualityCondition { tableField: string; tableValues: readonly any[]; } export enum OrderByOrdering { ASCENDING = 'asc', DESCENDING = 'desc', } /** * SQL modifiers that only affect the selection but not the projection. */ export interface QuerySelectionModifiers<TFields> { /** * Order the entities by specified columns and orders. */ orderBy?: { fieldName: keyof TFields; order: OrderByOrdering; }[]; /** * Skip the specified number of entities queried before returning. */ offset?: number; /** * Limit the number of entities returned. */ limit?: number; } export interface TableQuerySelectionModifiers { orderBy: | { columnName: string; order: OrderByOrdering; }[] | undefined; offset: number | undefined; limit: number | undefined; } /** * A database adapter is an interface by which entity objects can be * fetched, inserted, updated, and deleted from a database. This base class * handles all entity field transformation. Subclasses are responsible for * implementing database-specific logic for a type of database. */ export default abstract class EntityDatabaseAdapter<TFields> { private readonly fieldTransformerMap: FieldTransformerMap; constructor(private readonly entityConfiguration: EntityConfiguration<TFields>) { this.fieldTransformerMap = this.getFieldTransformerMap(); } /** * Transformer definitions for field types. Used to modify values as they are read from or written to * the database. Override in concrete subclasses to change transformation behavior. * If a field type is not present in the map, then fields of that type will not be transformed. */ protected abstract getFieldTransformerMap(): FieldTransformerMap; /** * Fetch many objects where fieldName is one of fieldValues. * * @param queryContext - query context with which to perform the fetch * @param fieldName - object field being queried * @param fieldValues - fieldName field values being queried * @returns map from fieldValue to objects that match the query for that fieldValue */ async fetchManyWhereAsync<K extends keyof TFields>( queryContext: EntityQueryContext, field: K, fieldValues: readonly NonNullable<TFields[K]>[] ): Promise<ReadonlyMap<NonNullable<TFields[K]>, readonly Readonly<TFields>[]>> { const fieldColumn = getDatabaseFieldForEntityField(this.entityConfiguration, field); const results = await this.fetchManyWhereInternalAsync( queryContext.getQueryInterface(), this.entityConfiguration.tableName, fieldColumn, fieldValues ); const objects = results.map((result) => transformDatabaseObjectToFields(this.entityConfiguration, this.fieldTransformerMap, result) ); const objectMap = new Map(); for (const fieldValue of fieldValues) { objectMap.set(fieldValue, []); } objects.forEach((object) => { const objectFieldValue = object[field]; objectMap.get(objectFieldValue).push(object); }); return objectMap; } protected abstract fetchManyWhereInternalAsync( queryInterface: any, tableName: string, tableField: string, tableValues: readonly any[] ): Promise<object[]>; /** * Fetch many objects matching the conjunction of where clauses constructed from * specified field equality operands. * * @param queryContext - query context with which to perform the fetch * @param fieldEqualityOperands - list of field equality where clause operand specifications * @param querySelectionModifiers - limit, offset, and orderBy for the query * @returns array of objects matching the query */ async fetchManyByFieldEqualityConjunctionAsync<N extends keyof TFields>( queryContext: EntityQueryContext, fieldEqualityOperands: FieldEqualityCondition<TFields, N>[], querySelectionModifiers: QuerySelectionModifiers<TFields> ): Promise<readonly Readonly<TFields>[]> { const tableFieldSingleValueOperands: TableFieldSingleValueEqualityCondition[] = []; const tableFieldMultipleValueOperands: TableFieldMultiValueEqualityCondition[] = []; for (const operand of fieldEqualityOperands) { if (isSingleValueFieldEqualityCondition(operand)) { tableFieldSingleValueOperands.push({ tableField: getDatabaseFieldForEntityField(this.entityConfiguration, operand.fieldName), tableValue: operand.fieldValue, }); } else { tableFieldMultipleValueOperands.push({ tableField: getDatabaseFieldForEntityField(this.entityConfiguration, operand.fieldName), tableValues: operand.fieldValues, }); } } const results = await this.fetchManyByFieldEqualityConjunctionInternalAsync( queryContext.getQueryInterface(), this.entityConfiguration.tableName, tableFieldSingleValueOperands, tableFieldMultipleValueOperands, this.convertToTableQueryModifiers(querySelectionModifiers) ); return results.map((result) => transformDatabaseObjectToFields(this.entityConfiguration, this.fieldTransformerMap, result) ); } protected abstract fetchManyByFieldEqualityConjunctionInternalAsync( queryInterface: any, tableName: string, tableFieldSingleValueEqualityOperands: TableFieldSingleValueEqualityCondition[], tableFieldMultiValueEqualityOperands: TableFieldMultiValueEqualityCondition[], querySelectionModifiers: TableQuerySelectionModifiers ): Promise<object[]>; /** * Fetch many objects matching the raw WHERE clause. * * @param queryContext - query context with which to perform the fetch * @param rawWhereClause - parameterized SQL WHERE clause with positional binding placeholders or named binding placeholders * @param bindings - array of positional bindings or object of named bindings * @param querySelectionModifiers - limit, offset, and orderBy for the query * @returns array of objects matching the query */ async fetchManyByRawWhereClauseAsync( queryContext: EntityQueryContext, rawWhereClause: string, bindings: any[] | object, querySelectionModifiers: QuerySelectionModifiers<TFields> ): Promise<readonly Readonly<TFields>[]> { const results = await this.fetchManyByRawWhereClauseInternalAsync( queryContext.getQueryInterface(), this.entityConfiguration.tableName, rawWhereClause, bindings, this.convertToTableQueryModifiers(querySelectionModifiers) ); return results.map((result) => transformDatabaseObjectToFields(this.entityConfiguration, this.fieldTransformerMap, result) ); } protected abstract fetchManyByRawWhereClauseInternalAsync( queryInterface: any, tableName: string, rawWhereClause: string, bindings: any[] | object, querySelectionModifiers: TableQuerySelectionModifiers ): Promise<object[]>; /** * Insert an object. * * @param queryContext - query context with which to perform the insert * @param object - the object to insert * @returns the inserted object */ async insertAsync( queryContext: EntityQueryContext, object: Readonly<Partial<TFields>> ): Promise<Readonly<TFields>> { const dbObject = transformFieldsToDatabaseObject( this.entityConfiguration, this.fieldTransformerMap, object ); const results = await this.insertInternalAsync( queryContext.getQueryInterface(), this.entityConfiguration.tableName, dbObject ); if (results.length > 1) { throw new Error( `Excessive results from database adapter insert: ${this.entityConfiguration.tableName}` ); } else if (results.length === 0) { throw new Error( `Empty results from database adapter insert: ${this.entityConfiguration.tableName}` ); } return transformDatabaseObjectToFields( this.entityConfiguration, this.fieldTransformerMap, results[0]! ); } protected abstract insertInternalAsync( queryInterface: any, tableName: string, object: object ): Promise<object[]>; /** * Update an object. * * @param queryContext - query context with which to perform the update * @param idField - the field in the object that is the ID * @param id - the value of the ID field in the object * @param object - the object to update * @returns the updated object */ async updateAsync<K extends keyof TFields>( queryContext: EntityQueryContext, idField: K, id: any, object: Readonly<Partial<TFields>> ): Promise<Readonly<TFields>> { const idColumn = getDatabaseFieldForEntityField(this.entityConfiguration, idField); const dbObject = transformFieldsToDatabaseObject( this.entityConfiguration, this.fieldTransformerMap, object ); const results = await this.updateInternalAsync( queryContext.getQueryInterface(), this.entityConfiguration.tableName, idColumn, id, dbObject ); if (results.length > 1) { throw new Error( `Excessive results from database adapter update: ${this.entityConfiguration.tableName}(id = ${id})` ); } else if (results.length === 0) { throw new Error( `Empty results from database adapter update: ${this.entityConfiguration.tableName}(id = ${id})` ); } return transformDatabaseObjectToFields( this.entityConfiguration, this.fieldTransformerMap, results[0]! ); } protected abstract updateInternalAsync( queryInterface: any, tableName: string, tableIdField: string, id: any, object: object ): Promise<object[]>; /** * Delete an object by ID. * * @param queryContext - query context with which to perform the deletion * @param idField - the field in the object that is the ID * @param id - the value of the ID field in the object */ async deleteAsync<K extends keyof TFields>( queryContext: EntityQueryContext, idField: K, id: any ): Promise<void> { const idColumn = getDatabaseFieldForEntityField(this.entityConfiguration, idField); const numDeleted = await this.deleteInternalAsync( queryContext.getQueryInterface(), this.entityConfiguration.tableName, idColumn, id ); if (numDeleted > 1) { throw new Error( `Excessive deletions from database adapter delete: ${this.entityConfiguration.tableName}(id = ${id})` ); } } protected abstract deleteInternalAsync( queryInterface: any, tableName: string, tableIdField: string, id: any ): Promise<number>; private convertToTableQueryModifiers( querySelectionModifiers: QuerySelectionModifiers<TFields> ): TableQuerySelectionModifiers { const orderBy = querySelectionModifiers.orderBy; return { orderBy: orderBy !== undefined ? orderBy.map((orderBySpecification) => ({ columnName: getDatabaseFieldForEntityField( this.entityConfiguration, orderBySpecification.fieldName ), order: orderBySpecification.order, })) : undefined, offset: querySelectionModifiers.offset, limit: querySelectionModifiers.limit, }; } }
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * UsageDetails * __NOTE__: An instance of this class is automatically created for an * instance of the ConsumptionManagementClient. */ export interface UsageDetails { /** * Lists the usage details for a scope by current billing period. Usage details * are available via this API only for May 1, 2014 or later. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName, properties/instanceId or * tags. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does * not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage details for a scope by current billing period. Usage details * are available via this API only for May 1, 2014 or later. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName, properties/instanceId or * tags. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does * not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; list(callback: ServiceCallback<models.UsageDetailsListResult>): void; list(options: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; /** * Lists the usage details for a scope by billing period. Usage details are * available via this API only for May 1, 2014 or later. * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByBillingPeriodWithHttpOperationResponse(billingPeriodName: string, options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage details for a scope by billing period. Usage details are * available via this API only for May 1, 2014 or later. * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByBillingPeriod(billingPeriodName: string, options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; listByBillingPeriod(billingPeriodName: string, callback: ServiceCallback<models.UsageDetailsListResult>): void; listByBillingPeriod(billingPeriodName: string, options: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; /** * Lists the usage details by billingAccountId for a scope by current billing * period. Usage details are available via this API only for May 1, 2014 or * later. * * @param {string} billingAccountId BillingAccount ID * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName, properties/instanceId or * tags. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does * not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByBillingAccountWithHttpOperationResponse(billingAccountId: string, options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage details by billingAccountId for a scope by current billing * period. Usage details are available via this API only for May 1, 2014 or * later. * * @param {string} billingAccountId BillingAccount ID * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName, properties/instanceId or * tags. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does * not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByBillingAccount(billingAccountId: string, options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; listByBillingAccount(billingAccountId: string, callback: ServiceCallback<models.UsageDetailsListResult>): void; listByBillingAccount(billingAccountId: string, options: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; /** * Lists the usage details based on billingAccountId for a scope by billing * period. Usage details are available via this API only for May 1, 2014 or * later. * * @param {string} billingAccountId BillingAccount ID * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForBillingPeriodByBillingAccountWithHttpOperationResponse(billingAccountId: string, billingPeriodName: string, options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage details based on billingAccountId for a scope by billing * period. Usage details are available via this API only for May 1, 2014 or * later. * * @param {string} billingAccountId BillingAccount ID * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForBillingPeriodByBillingAccount(billingAccountId: string, billingPeriodName: string, options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; listForBillingPeriodByBillingAccount(billingAccountId: string, billingPeriodName: string, callback: ServiceCallback<models.UsageDetailsListResult>): void; listForBillingPeriodByBillingAccount(billingAccountId: string, billingPeriodName: string, options: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; /** * Lists the usage details by departmentId for a scope by current billing * period. Usage details are available via this API only for May 1, 2014 or * later. * * @param {string} departmentId Department ID * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName, properties/instanceId or * tags. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does * not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByDepartmentWithHttpOperationResponse(departmentId: string, options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage details by departmentId for a scope by current billing * period. Usage details are available via this API only for May 1, 2014 or * later. * * @param {string} departmentId Department ID * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName, properties/instanceId or * tags. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does * not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByDepartment(departmentId: string, options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; listByDepartment(departmentId: string, callback: ServiceCallback<models.UsageDetailsListResult>): void; listByDepartment(departmentId: string, options: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; /** * Lists the usage details based on departmentId for a scope by billing period. * Usage details are available via this API only for May 1, 2014 or later. * * @param {string} departmentId Department ID * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForBillingPeriodByDepartmentWithHttpOperationResponse(departmentId: string, billingPeriodName: string, options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage details based on departmentId for a scope by billing period. * Usage details are available via this API only for May 1, 2014 or later. * * @param {string} departmentId Department ID * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForBillingPeriodByDepartment(departmentId: string, billingPeriodName: string, options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; listForBillingPeriodByDepartment(departmentId: string, billingPeriodName: string, callback: ServiceCallback<models.UsageDetailsListResult>): void; listForBillingPeriodByDepartment(departmentId: string, billingPeriodName: string, options: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; /** * Lists the usage details by enrollmentAccountId for a scope by current * billing period. Usage details are available via this API only for May 1, * 2014 or later. * * @param {string} enrollmentAccountId EnrollmentAccount ID * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName, properties/instanceId or * tags. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does * not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByEnrollmentAccountWithHttpOperationResponse(enrollmentAccountId: string, options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage details by enrollmentAccountId for a scope by current * billing period. Usage details are available via this API only for May 1, * 2014 or later. * * @param {string} enrollmentAccountId EnrollmentAccount ID * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName, properties/instanceId or * tags. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does * not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByEnrollmentAccount(enrollmentAccountId: string, options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; listByEnrollmentAccount(enrollmentAccountId: string, callback: ServiceCallback<models.UsageDetailsListResult>): void; listByEnrollmentAccount(enrollmentAccountId: string, options: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; /** * Lists the usage details based on enrollmentAccountId for a scope by billing * period. Usage details are available via this API only for May 1, 2014 or * later. * * @param {string} enrollmentAccountId EnrollmentAccount ID * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForBillingPeriodByEnrollmentAccountWithHttpOperationResponse(enrollmentAccountId: string, billingPeriodName: string, options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage details based on enrollmentAccountId for a scope by billing * period. Usage details are available via this API only for May 1, 2014 or * later. * * @param {string} enrollmentAccountId EnrollmentAccount ID * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForBillingPeriodByEnrollmentAccount(enrollmentAccountId: string, billingPeriodName: string, options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; listForBillingPeriodByEnrollmentAccount(enrollmentAccountId: string, billingPeriodName: string, callback: ServiceCallback<models.UsageDetailsListResult>): void; listForBillingPeriodByEnrollmentAccount(enrollmentAccountId: string, billingPeriodName: string, options: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; /** * Lists the usage detail records for all subscriptions belonging to a * management group scope by current billing period. Usage details are * available via this API only for May 1, 2014 or later. * * @param {string} managementGroupId Azure Management Group ID. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName, properties/instanceId or * tags. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does * not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByManagementGroupWithHttpOperationResponse(managementGroupId: string, options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage detail records for all subscriptions belonging to a * management group scope by current billing period. Usage details are * available via this API only for May 1, 2014 or later. * * @param {string} managementGroupId Azure Management Group ID. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName, properties/instanceId or * tags. The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does * not currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByManagementGroup(managementGroupId: string, options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; listByManagementGroup(managementGroupId: string, callback: ServiceCallback<models.UsageDetailsListResult>): void; listByManagementGroup(managementGroupId: string, options: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; /** * Lists the usage detail records for all subscriptions belonging to a * management group scope by specified billing period. Usage details are * available via this API only for May 1, 2014 or later. * * @param {string} managementGroupId Azure Management Group ID. * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForBillingPeriodByManagementGroupWithHttpOperationResponse(managementGroupId: string, billingPeriodName: string, options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage detail records for all subscriptions belonging to a * management group scope by specified billing period. Usage details are * available via this API only for May 1, 2014 or later. * * @param {string} managementGroupId Azure Management Group ID. * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/additionalProperties or properties/meterDetails within a list of * usage details. By default, these fields are not included when listing usage * details. * * @param {string} [options.filter] May be used to filter usageDetails by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. Tag filter is a key value pair * string where key and value is separated by a colon (:). * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N usageDetails. * * @param {object} [options.queryOptions] Additional parameters for the * operation * * @param {string} [options.queryOptions.apply] OData apply expression to * aggregate usageDetails by tags or (tags and properties/usageStart) * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForBillingPeriodByManagementGroup(managementGroupId: string, billingPeriodName: string, options?: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; listForBillingPeriodByManagementGroup(managementGroupId: string, billingPeriodName: string, callback: ServiceCallback<models.UsageDetailsListResult>): void; listForBillingPeriodByManagementGroup(managementGroupId: string, billingPeriodName: string, options: { expand? : string, filter? : string, skiptoken? : string, top? : number, queryOptions? : models.QueryOptions, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; /** * Lists the usage details for a scope by current billing period. Usage details * are available via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage details for a scope by current billing period. Usage details * are available via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.UsageDetailsListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; /** * Lists the usage details for a scope by billing period. Usage details are * available via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByBillingPeriodNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage details for a scope by billing period. Usage details are * available via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByBillingPeriodNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; listByBillingPeriodNext(nextPageLink: string, callback: ServiceCallback<models.UsageDetailsListResult>): void; listByBillingPeriodNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; /** * Lists the usage details by billingAccountId for a scope by current billing * period. Usage details are available via this API only for May 1, 2014 or * later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByBillingAccountNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage details by billingAccountId for a scope by current billing * period. Usage details are available via this API only for May 1, 2014 or * later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByBillingAccountNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; listByBillingAccountNext(nextPageLink: string, callback: ServiceCallback<models.UsageDetailsListResult>): void; listByBillingAccountNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; /** * Lists the usage details based on billingAccountId for a scope by billing * period. Usage details are available via this API only for May 1, 2014 or * later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForBillingPeriodByBillingAccountNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage details based on billingAccountId for a scope by billing * period. Usage details are available via this API only for May 1, 2014 or * later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForBillingPeriodByBillingAccountNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; listForBillingPeriodByBillingAccountNext(nextPageLink: string, callback: ServiceCallback<models.UsageDetailsListResult>): void; listForBillingPeriodByBillingAccountNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; /** * Lists the usage details by departmentId for a scope by current billing * period. Usage details are available via this API only for May 1, 2014 or * later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByDepartmentNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage details by departmentId for a scope by current billing * period. Usage details are available via this API only for May 1, 2014 or * later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByDepartmentNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; listByDepartmentNext(nextPageLink: string, callback: ServiceCallback<models.UsageDetailsListResult>): void; listByDepartmentNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; /** * Lists the usage details based on departmentId for a scope by billing period. * Usage details are available via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForBillingPeriodByDepartmentNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage details based on departmentId for a scope by billing period. * Usage details are available via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForBillingPeriodByDepartmentNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; listForBillingPeriodByDepartmentNext(nextPageLink: string, callback: ServiceCallback<models.UsageDetailsListResult>): void; listForBillingPeriodByDepartmentNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; /** * Lists the usage details by enrollmentAccountId for a scope by current * billing period. Usage details are available via this API only for May 1, * 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByEnrollmentAccountNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage details by enrollmentAccountId for a scope by current * billing period. Usage details are available via this API only for May 1, * 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByEnrollmentAccountNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; listByEnrollmentAccountNext(nextPageLink: string, callback: ServiceCallback<models.UsageDetailsListResult>): void; listByEnrollmentAccountNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; /** * Lists the usage details based on enrollmentAccountId for a scope by billing * period. Usage details are available via this API only for May 1, 2014 or * later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForBillingPeriodByEnrollmentAccountNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage details based on enrollmentAccountId for a scope by billing * period. Usage details are available via this API only for May 1, 2014 or * later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForBillingPeriodByEnrollmentAccountNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; listForBillingPeriodByEnrollmentAccountNext(nextPageLink: string, callback: ServiceCallback<models.UsageDetailsListResult>): void; listForBillingPeriodByEnrollmentAccountNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; /** * Lists the usage detail records for all subscriptions belonging to a * management group scope by current billing period. Usage details are * available via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByManagementGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage detail records for all subscriptions belonging to a * management group scope by current billing period. Usage details are * available via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByManagementGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; listByManagementGroupNext(nextPageLink: string, callback: ServiceCallback<models.UsageDetailsListResult>): void; listByManagementGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; /** * Lists the usage detail records for all subscriptions belonging to a * management group scope by specified billing period. Usage details are * available via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<UsageDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForBillingPeriodByManagementGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.UsageDetailsListResult>>; /** * Lists the usage detail records for all subscriptions belonging to a * management group scope by specified billing period. Usage details are * available via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {UsageDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {UsageDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link UsageDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForBillingPeriodByManagementGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.UsageDetailsListResult>; listForBillingPeriodByManagementGroupNext(nextPageLink: string, callback: ServiceCallback<models.UsageDetailsListResult>): void; listForBillingPeriodByManagementGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.UsageDetailsListResult>): void; } /** * @class * Marketplaces * __NOTE__: An instance of this class is automatically created for an * instance of the ConsumptionManagementClient. */ export interface Marketplaces { /** * Lists the marketplaces for a scope by subscriptionId and current billing * period. Marketplaces are available via this API only for May 1, 2014 or * later. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplaces for a scope by subscriptionId and current billing * period. Marketplaces are available via this API only for May 1, 2014 or * later. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; list(callback: ServiceCallback<models.MarketplacesListResult>): void; list(options: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; /** * Lists the marketplaces for a scope by billing period and subscripotionId. * Marketplaces are available via this API only for May 1, 2014 or later. * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByBillingPeriodWithHttpOperationResponse(billingPeriodName: string, options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplaces for a scope by billing period and subscripotionId. * Marketplaces are available via this API only for May 1, 2014 or later. * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByBillingPeriod(billingPeriodName: string, options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; listByBillingPeriod(billingPeriodName: string, callback: ServiceCallback<models.MarketplacesListResult>): void; listByBillingPeriod(billingPeriodName: string, options: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; /** * Lists the marketplaces for a scope by billingAccountId and current billing * period. Marketplaces are available via this API only for May 1, 2014 or * later. * * @param {string} billingAccountId BillingAccount ID * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByBillingAccountWithHttpOperationResponse(billingAccountId: string, options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplaces for a scope by billingAccountId and current billing * period. Marketplaces are available via this API only for May 1, 2014 or * later. * * @param {string} billingAccountId BillingAccount ID * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByBillingAccount(billingAccountId: string, options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; listByBillingAccount(billingAccountId: string, callback: ServiceCallback<models.MarketplacesListResult>): void; listByBillingAccount(billingAccountId: string, options: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; /** * Lists the marketplaces for a scope by billing period and billingAccountId. * Marketplaces are available via this API only for May 1, 2014 or later. * * @param {string} billingAccountId BillingAccount ID * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForBillingPeriodByBillingAccountWithHttpOperationResponse(billingAccountId: string, billingPeriodName: string, options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplaces for a scope by billing period and billingAccountId. * Marketplaces are available via this API only for May 1, 2014 or later. * * @param {string} billingAccountId BillingAccount ID * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForBillingPeriodByBillingAccount(billingAccountId: string, billingPeriodName: string, options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; listForBillingPeriodByBillingAccount(billingAccountId: string, billingPeriodName: string, callback: ServiceCallback<models.MarketplacesListResult>): void; listForBillingPeriodByBillingAccount(billingAccountId: string, billingPeriodName: string, options: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; /** * Lists the marketplaces for a scope by departmentId and current billing * period. Marketplaces are available via this API only for May 1, 2014 or * later. * * @param {string} departmentId Department ID * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByDepartmentWithHttpOperationResponse(departmentId: string, options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplaces for a scope by departmentId and current billing * period. Marketplaces are available via this API only for May 1, 2014 or * later. * * @param {string} departmentId Department ID * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByDepartment(departmentId: string, options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; listByDepartment(departmentId: string, callback: ServiceCallback<models.MarketplacesListResult>): void; listByDepartment(departmentId: string, options: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; /** * Lists the marketplaces for a scope by billing period and departmentId. * Marketplaces are available via this API only for May 1, 2014 or later. * * @param {string} departmentId Department ID * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForBillingPeriodByDepartmentWithHttpOperationResponse(departmentId: string, billingPeriodName: string, options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplaces for a scope by billing period and departmentId. * Marketplaces are available via this API only for May 1, 2014 or later. * * @param {string} departmentId Department ID * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForBillingPeriodByDepartment(departmentId: string, billingPeriodName: string, options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; listForBillingPeriodByDepartment(departmentId: string, billingPeriodName: string, callback: ServiceCallback<models.MarketplacesListResult>): void; listForBillingPeriodByDepartment(departmentId: string, billingPeriodName: string, options: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; /** * Lists the marketplaces for a scope by enrollmentAccountId and current * billing period. Marketplaces are available via this API only for May 1, 2014 * or later. * * @param {string} enrollmentAccountId EnrollmentAccount ID * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByEnrollmentAccountWithHttpOperationResponse(enrollmentAccountId: string, options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplaces for a scope by enrollmentAccountId and current * billing period. Marketplaces are available via this API only for May 1, 2014 * or later. * * @param {string} enrollmentAccountId EnrollmentAccount ID * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByEnrollmentAccount(enrollmentAccountId: string, options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; listByEnrollmentAccount(enrollmentAccountId: string, callback: ServiceCallback<models.MarketplacesListResult>): void; listByEnrollmentAccount(enrollmentAccountId: string, options: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; /** * Lists the marketplaces for a scope by billing period and * enrollmentAccountId. Marketplaces are available via this API only for May 1, * 2014 or later. * * @param {string} enrollmentAccountId EnrollmentAccount ID * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForBillingPeriodByEnrollmentAccountWithHttpOperationResponse(enrollmentAccountId: string, billingPeriodName: string, options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplaces for a scope by billing period and * enrollmentAccountId. Marketplaces are available via this API only for May 1, * 2014 or later. * * @param {string} enrollmentAccountId EnrollmentAccount ID * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForBillingPeriodByEnrollmentAccount(enrollmentAccountId: string, billingPeriodName: string, options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; listForBillingPeriodByEnrollmentAccount(enrollmentAccountId: string, billingPeriodName: string, callback: ServiceCallback<models.MarketplacesListResult>): void; listForBillingPeriodByEnrollmentAccount(enrollmentAccountId: string, billingPeriodName: string, options: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; /** * Lists the marketplace records for all subscriptions belonging to a * management group scope by current billing period. Marketplaces are available * via this API only for May 1, 2014 or later. * * @param {string} managementGroupId Azure Management Group ID. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByManagementGroupWithHttpOperationResponse(managementGroupId: string, options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplace records for all subscriptions belonging to a * management group scope by current billing period. Marketplaces are available * via this API only for May 1, 2014 or later. * * @param {string} managementGroupId Azure Management Group ID. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByManagementGroup(managementGroupId: string, options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; listByManagementGroup(managementGroupId: string, callback: ServiceCallback<models.MarketplacesListResult>): void; listByManagementGroup(managementGroupId: string, options: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; /** * Lists the marketplace records for all subscriptions belonging to a * management group scope by specified billing period. Marketplaces are * available via this API only for May 1, 2014 or later. * * @param {string} managementGroupId Azure Management Group ID. * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForBillingPeriodByManagementGroupWithHttpOperationResponse(managementGroupId: string, billingPeriodName: string, options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplace records for all subscriptions belonging to a * management group scope by specified billing period. Marketplaces are * available via this API only for May 1, 2014 or later. * * @param {string} managementGroupId Azure Management Group ID. * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter marketplaces by * properties/usageEnd (Utc time), properties/usageStart (Utc time), * properties/resourceGroup, properties/instanceName or properties/instanceId. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {number} [options.top] May be used to limit the number of results to * the most recent N marketplaces. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForBillingPeriodByManagementGroup(managementGroupId: string, billingPeriodName: string, options?: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; listForBillingPeriodByManagementGroup(managementGroupId: string, billingPeriodName: string, callback: ServiceCallback<models.MarketplacesListResult>): void; listForBillingPeriodByManagementGroup(managementGroupId: string, billingPeriodName: string, options: { filter? : string, top? : number, skiptoken? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; /** * Lists the marketplaces for a scope by subscriptionId and current billing * period. Marketplaces are available via this API only for May 1, 2014 or * later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplaces for a scope by subscriptionId and current billing * period. Marketplaces are available via this API only for May 1, 2014 or * later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.MarketplacesListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; /** * Lists the marketplaces for a scope by billing period and subscripotionId. * Marketplaces are available via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByBillingPeriodNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplaces for a scope by billing period and subscripotionId. * Marketplaces are available via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByBillingPeriodNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; listByBillingPeriodNext(nextPageLink: string, callback: ServiceCallback<models.MarketplacesListResult>): void; listByBillingPeriodNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; /** * Lists the marketplaces for a scope by billingAccountId and current billing * period. Marketplaces are available via this API only for May 1, 2014 or * later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByBillingAccountNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplaces for a scope by billingAccountId and current billing * period. Marketplaces are available via this API only for May 1, 2014 or * later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByBillingAccountNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; listByBillingAccountNext(nextPageLink: string, callback: ServiceCallback<models.MarketplacesListResult>): void; listByBillingAccountNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; /** * Lists the marketplaces for a scope by billing period and billingAccountId. * Marketplaces are available via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForBillingPeriodByBillingAccountNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplaces for a scope by billing period and billingAccountId. * Marketplaces are available via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForBillingPeriodByBillingAccountNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; listForBillingPeriodByBillingAccountNext(nextPageLink: string, callback: ServiceCallback<models.MarketplacesListResult>): void; listForBillingPeriodByBillingAccountNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; /** * Lists the marketplaces for a scope by departmentId and current billing * period. Marketplaces are available via this API only for May 1, 2014 or * later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByDepartmentNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplaces for a scope by departmentId and current billing * period. Marketplaces are available via this API only for May 1, 2014 or * later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByDepartmentNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; listByDepartmentNext(nextPageLink: string, callback: ServiceCallback<models.MarketplacesListResult>): void; listByDepartmentNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; /** * Lists the marketplaces for a scope by billing period and departmentId. * Marketplaces are available via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForBillingPeriodByDepartmentNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplaces for a scope by billing period and departmentId. * Marketplaces are available via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForBillingPeriodByDepartmentNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; listForBillingPeriodByDepartmentNext(nextPageLink: string, callback: ServiceCallback<models.MarketplacesListResult>): void; listForBillingPeriodByDepartmentNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; /** * Lists the marketplaces for a scope by enrollmentAccountId and current * billing period. Marketplaces are available via this API only for May 1, 2014 * or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByEnrollmentAccountNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplaces for a scope by enrollmentAccountId and current * billing period. Marketplaces are available via this API only for May 1, 2014 * or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByEnrollmentAccountNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; listByEnrollmentAccountNext(nextPageLink: string, callback: ServiceCallback<models.MarketplacesListResult>): void; listByEnrollmentAccountNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; /** * Lists the marketplaces for a scope by billing period and * enrollmentAccountId. Marketplaces are available via this API only for May 1, * 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForBillingPeriodByEnrollmentAccountNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplaces for a scope by billing period and * enrollmentAccountId. Marketplaces are available via this API only for May 1, * 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForBillingPeriodByEnrollmentAccountNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; listForBillingPeriodByEnrollmentAccountNext(nextPageLink: string, callback: ServiceCallback<models.MarketplacesListResult>): void; listForBillingPeriodByEnrollmentAccountNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; /** * Lists the marketplace records for all subscriptions belonging to a * management group scope by current billing period. Marketplaces are available * via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByManagementGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplace records for all subscriptions belonging to a * management group scope by current billing period. Marketplaces are available * via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByManagementGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; listByManagementGroupNext(nextPageLink: string, callback: ServiceCallback<models.MarketplacesListResult>): void; listByManagementGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; /** * Lists the marketplace records for all subscriptions belonging to a * management group scope by specified billing period. Marketplaces are * available via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<MarketplacesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForBillingPeriodByManagementGroupNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.MarketplacesListResult>>; /** * Lists the marketplace records for all subscriptions belonging to a * management group scope by specified billing period. Marketplaces are * available via this API only for May 1, 2014 or later. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {MarketplacesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {MarketplacesListResult} [result] - The deserialized result object if an error did not occur. * See {@link MarketplacesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForBillingPeriodByManagementGroupNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.MarketplacesListResult>; listForBillingPeriodByManagementGroupNext(nextPageLink: string, callback: ServiceCallback<models.MarketplacesListResult>): void; listForBillingPeriodByManagementGroupNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.MarketplacesListResult>): void; } /** * @class * Balances * __NOTE__: An instance of this class is automatically created for an * instance of the ConsumptionManagementClient. */ export interface Balances { /** * Gets the balances for a scope by billingAccountId. Balances are available * via this API only for May 1, 2014 or later. * * @param {string} billingAccountId BillingAccount ID * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Balance>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getByBillingAccountWithHttpOperationResponse(billingAccountId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Balance>>; /** * Gets the balances for a scope by billingAccountId. Balances are available * via this API only for May 1, 2014 or later. * * @param {string} billingAccountId BillingAccount ID * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Balance} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Balance} [result] - The deserialized result object if an error did not occur. * See {@link Balance} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getByBillingAccount(billingAccountId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Balance>; getByBillingAccount(billingAccountId: string, callback: ServiceCallback<models.Balance>): void; getByBillingAccount(billingAccountId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Balance>): void; /** * Gets the balances for a scope by billing period and billingAccountId. * Balances are available via this API only for May 1, 2014 or later. * * @param {string} billingAccountId BillingAccount ID * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Balance>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getForBillingPeriodByBillingAccountWithHttpOperationResponse(billingAccountId: string, billingPeriodName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Balance>>; /** * Gets the balances for a scope by billing period and billingAccountId. * Balances are available via this API only for May 1, 2014 or later. * * @param {string} billingAccountId BillingAccount ID * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Balance} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Balance} [result] - The deserialized result object if an error did not occur. * See {@link Balance} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getForBillingPeriodByBillingAccount(billingAccountId: string, billingPeriodName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Balance>; getForBillingPeriodByBillingAccount(billingAccountId: string, billingPeriodName: string, callback: ServiceCallback<models.Balance>): void; getForBillingPeriodByBillingAccount(billingAccountId: string, billingPeriodName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Balance>): void; } /** * @class * ReservationsSummaries * __NOTE__: An instance of this class is automatically created for an * instance of the ConsumptionManagementClient. */ export interface ReservationsSummaries { /** * Lists the reservations summaries for daily or monthly grain. * * @param {string} reservationOrderId Order Id of the reservation * * @param {string} grain Can be daily or monthly. Possible values include: * 'DailyGrain', 'MonthlyGrain' * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] Required only for daily grain. The * properties/UsageDate for start date and end date. The filter supports 'le' * and 'ge' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ReservationSummariesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReservationOrderWithHttpOperationResponse(reservationOrderId: string, grain: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReservationSummariesListResult>>; /** * Lists the reservations summaries for daily or monthly grain. * * @param {string} reservationOrderId Order Id of the reservation * * @param {string} grain Can be daily or monthly. Possible values include: * 'DailyGrain', 'MonthlyGrain' * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] Required only for daily grain. The * properties/UsageDate for start date and end date. The filter supports 'le' * and 'ge' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ReservationSummariesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ReservationSummariesListResult} [result] - The deserialized result object if an error did not occur. * See {@link ReservationSummariesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByReservationOrder(reservationOrderId: string, grain: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ReservationSummariesListResult>; listByReservationOrder(reservationOrderId: string, grain: string, callback: ServiceCallback<models.ReservationSummariesListResult>): void; listByReservationOrder(reservationOrderId: string, grain: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReservationSummariesListResult>): void; /** * Lists the reservations summaries for daily or monthly grain. * * @param {string} reservationOrderId Order Id of the reservation * * @param {string} reservationId Id of the reservation * * @param {string} grain Can be daily or monthly. Possible values include: * 'DailyGrain', 'MonthlyGrain' * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] Required only for daily grain. The * properties/UsageDate for start date and end date. The filter supports 'le' * and 'ge' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ReservationSummariesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReservationOrderAndReservationWithHttpOperationResponse(reservationOrderId: string, reservationId: string, grain: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReservationSummariesListResult>>; /** * Lists the reservations summaries for daily or monthly grain. * * @param {string} reservationOrderId Order Id of the reservation * * @param {string} reservationId Id of the reservation * * @param {string} grain Can be daily or monthly. Possible values include: * 'DailyGrain', 'MonthlyGrain' * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] Required only for daily grain. The * properties/UsageDate for start date and end date. The filter supports 'le' * and 'ge' * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ReservationSummariesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ReservationSummariesListResult} [result] - The deserialized result object if an error did not occur. * See {@link ReservationSummariesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByReservationOrderAndReservation(reservationOrderId: string, reservationId: string, grain: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ReservationSummariesListResult>; listByReservationOrderAndReservation(reservationOrderId: string, reservationId: string, grain: string, callback: ServiceCallback<models.ReservationSummariesListResult>): void; listByReservationOrderAndReservation(reservationOrderId: string, reservationId: string, grain: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReservationSummariesListResult>): void; /** * Lists the reservations summaries for daily or monthly grain. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ReservationSummariesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReservationOrderNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReservationSummariesListResult>>; /** * Lists the reservations summaries for daily or monthly grain. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ReservationSummariesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ReservationSummariesListResult} [result] - The deserialized result object if an error did not occur. * See {@link ReservationSummariesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByReservationOrderNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReservationSummariesListResult>; listByReservationOrderNext(nextPageLink: string, callback: ServiceCallback<models.ReservationSummariesListResult>): void; listByReservationOrderNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReservationSummariesListResult>): void; /** * Lists the reservations summaries for daily or monthly grain. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ReservationSummariesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReservationOrderAndReservationNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReservationSummariesListResult>>; /** * Lists the reservations summaries for daily or monthly grain. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ReservationSummariesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ReservationSummariesListResult} [result] - The deserialized result object if an error did not occur. * See {@link ReservationSummariesListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByReservationOrderAndReservationNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReservationSummariesListResult>; listByReservationOrderAndReservationNext(nextPageLink: string, callback: ServiceCallback<models.ReservationSummariesListResult>): void; listByReservationOrderAndReservationNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReservationSummariesListResult>): void; } /** * @class * ReservationsDetails * __NOTE__: An instance of this class is automatically created for an * instance of the ConsumptionManagementClient. */ export interface ReservationsDetails { /** * Lists the reservations details for provided date range. * * @param {string} reservationOrderId Order Id of the reservation * * @param {string} filter Filter reservation details by date range. The * properties/UsageDate for start date and end date. The filter supports 'le' * and 'ge' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ReservationDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReservationOrderWithHttpOperationResponse(reservationOrderId: string, filter: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReservationDetailsListResult>>; /** * Lists the reservations details for provided date range. * * @param {string} reservationOrderId Order Id of the reservation * * @param {string} filter Filter reservation details by date range. The * properties/UsageDate for start date and end date. The filter supports 'le' * and 'ge' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ReservationDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ReservationDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link ReservationDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByReservationOrder(reservationOrderId: string, filter: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReservationDetailsListResult>; listByReservationOrder(reservationOrderId: string, filter: string, callback: ServiceCallback<models.ReservationDetailsListResult>): void; listByReservationOrder(reservationOrderId: string, filter: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReservationDetailsListResult>): void; /** * Lists the reservations details for provided date range. * * @param {string} reservationOrderId Order Id of the reservation * * @param {string} reservationId Id of the reservation * * @param {string} filter Filter reservation details by date range. The * properties/UsageDate for start date and end date. The filter supports 'le' * and 'ge' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ReservationDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReservationOrderAndReservationWithHttpOperationResponse(reservationOrderId: string, reservationId: string, filter: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReservationDetailsListResult>>; /** * Lists the reservations details for provided date range. * * @param {string} reservationOrderId Order Id of the reservation * * @param {string} reservationId Id of the reservation * * @param {string} filter Filter reservation details by date range. The * properties/UsageDate for start date and end date. The filter supports 'le' * and 'ge' * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ReservationDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ReservationDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link ReservationDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByReservationOrderAndReservation(reservationOrderId: string, reservationId: string, filter: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReservationDetailsListResult>; listByReservationOrderAndReservation(reservationOrderId: string, reservationId: string, filter: string, callback: ServiceCallback<models.ReservationDetailsListResult>): void; listByReservationOrderAndReservation(reservationOrderId: string, reservationId: string, filter: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReservationDetailsListResult>): void; /** * Lists the reservations details for provided date range. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ReservationDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReservationOrderNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReservationDetailsListResult>>; /** * Lists the reservations details for provided date range. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ReservationDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ReservationDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link ReservationDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByReservationOrderNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReservationDetailsListResult>; listByReservationOrderNext(nextPageLink: string, callback: ServiceCallback<models.ReservationDetailsListResult>): void; listByReservationOrderNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReservationDetailsListResult>): void; /** * Lists the reservations details for provided date range. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ReservationDetailsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByReservationOrderAndReservationNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReservationDetailsListResult>>; /** * Lists the reservations details for provided date range. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ReservationDetailsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ReservationDetailsListResult} [result] - The deserialized result object if an error did not occur. * See {@link ReservationDetailsListResult} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByReservationOrderAndReservationNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReservationDetailsListResult>; listByReservationOrderAndReservationNext(nextPageLink: string, callback: ServiceCallback<models.ReservationDetailsListResult>): void; listByReservationOrderAndReservationNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReservationDetailsListResult>): void; } /** * @class * ReservationRecommendations * __NOTE__: An instance of this class is automatically created for an * instance of the ConsumptionManagementClient. */ export interface ReservationRecommendations { /** * List of recomendations for purchasing reserved instances. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter * reservationRecommendations by properties/scope and * properties/lookBackPeriod. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ReservationRecommendationsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReservationRecommendationsListResult>>; /** * List of recomendations for purchasing reserved instances. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter * reservationRecommendations by properties/scope and * properties/lookBackPeriod. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ReservationRecommendationsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ReservationRecommendationsListResult} [result] - The deserialized result object if an error did not occur. * See {@link ReservationRecommendationsListResult} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ReservationRecommendationsListResult>; list(callback: ServiceCallback<models.ReservationRecommendationsListResult>): void; list(options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReservationRecommendationsListResult>): void; /** * List of recomendations for purchasing reserved instances. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ReservationRecommendationsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ReservationRecommendationsListResult>>; /** * List of recomendations for purchasing reserved instances. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ReservationRecommendationsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ReservationRecommendationsListResult} [result] - The deserialized result object if an error did not occur. * See {@link ReservationRecommendationsListResult} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ReservationRecommendationsListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.ReservationRecommendationsListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ReservationRecommendationsListResult>): void; } /** * @class * Budgets * __NOTE__: An instance of this class is automatically created for an * instance of the ConsumptionManagementClient. */ export interface Budgets { /** * Lists all budgets for a subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BudgetsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BudgetsListResult>>; /** * Lists all budgets for a subscription. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BudgetsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BudgetsListResult} [result] - The deserialized result object if an error did not occur. * See {@link BudgetsListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.BudgetsListResult>; list(callback: ServiceCallback<models.BudgetsListResult>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BudgetsListResult>): void; /** * Lists all budgets for a resource group under a subscription. * * @param {string} resourceGroupName Azure Resource Group Name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BudgetsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupNameWithHttpOperationResponse(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BudgetsListResult>>; /** * Lists all budgets for a resource group under a subscription. * * @param {string} resourceGroupName Azure Resource Group Name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BudgetsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BudgetsListResult} [result] - The deserialized result object if an error did not occur. * See {@link BudgetsListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroupName(resourceGroupName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.BudgetsListResult>; listByResourceGroupName(resourceGroupName: string, callback: ServiceCallback<models.BudgetsListResult>): void; listByResourceGroupName(resourceGroupName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BudgetsListResult>): void; /** * Gets the budget for a subscription by budget name. * * @param {string} budgetName Budget Name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Budget>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(budgetName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Budget>>; /** * Gets the budget for a subscription by budget name. * * @param {string} budgetName Budget Name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Budget} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Budget} [result] - The deserialized result object if an error did not occur. * See {@link Budget} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(budgetName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Budget>; get(budgetName: string, callback: ServiceCallback<models.Budget>): void; get(budgetName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Budget>): void; /** * The operation to create or update a budget. Update operation requires latest * eTag to be set in the request mandatorily. You may obtain the latest eTag by * performing a get operation. Create operation does not require eTag. * * @param {string} budgetName Budget Name. * * @param {object} parameters Parameters supplied to the Create Budget * operation. * * @param {string} parameters.category The category of the budget, whether the * budget tracks cost or usage. Possible values include: 'Cost', 'Usage' * * @param {number} parameters.amount The total amount of cost to track with the * budget * * @param {string} parameters.timeGrain The time covered by a budget. Tracking * of the amount will be reset based on the time grain. Possible values * include: 'Monthly', 'Quarterly', 'Annually' * * @param {object} parameters.timePeriod Has start and end date of the budget. * The start date must be first of the month and should be less than the end * date. Budget start date must be on or after June 1, 2017. Future start date * should not be more than three months. Past start date should be selected * within the timegrain preiod. There are no restrictions on the end date. * * @param {date} parameters.timePeriod.startDate The start date for the budget. * * @param {date} [parameters.timePeriod.endDate] The end date for the budget. * If not provided, we default this to 10 years from the start date. * * @param {object} [parameters.filters] May be used to filter budgets by * resource group, resource, or meter. * * @param {array} [parameters.filters.resourceGroups] The list of filters on * resource groups, allowed at subscription level only. * * @param {array} [parameters.filters.resources] The list of filters on * resources. * * @param {array} [parameters.filters.meters] The list of filters on meters * (GUID), mandatory for budgets of usage category. * * @param {object} [parameters.filters.tags] The dictionary of filters on tags. * * @param {object} [parameters.notifications] Dictionary of notifications * associated with the budget. Budget can have up to five notifications. * * @param {string} [parameters.eTag] eTag of the resource. To handle concurrent * update scenarion, this field will be used to determine whether the user is * updating the latest version or not. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Budget>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(budgetName: string, parameters: models.Budget, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Budget>>; /** * The operation to create or update a budget. Update operation requires latest * eTag to be set in the request mandatorily. You may obtain the latest eTag by * performing a get operation. Create operation does not require eTag. * * @param {string} budgetName Budget Name. * * @param {object} parameters Parameters supplied to the Create Budget * operation. * * @param {string} parameters.category The category of the budget, whether the * budget tracks cost or usage. Possible values include: 'Cost', 'Usage' * * @param {number} parameters.amount The total amount of cost to track with the * budget * * @param {string} parameters.timeGrain The time covered by a budget. Tracking * of the amount will be reset based on the time grain. Possible values * include: 'Monthly', 'Quarterly', 'Annually' * * @param {object} parameters.timePeriod Has start and end date of the budget. * The start date must be first of the month and should be less than the end * date. Budget start date must be on or after June 1, 2017. Future start date * should not be more than three months. Past start date should be selected * within the timegrain preiod. There are no restrictions on the end date. * * @param {date} parameters.timePeriod.startDate The start date for the budget. * * @param {date} [parameters.timePeriod.endDate] The end date for the budget. * If not provided, we default this to 10 years from the start date. * * @param {object} [parameters.filters] May be used to filter budgets by * resource group, resource, or meter. * * @param {array} [parameters.filters.resourceGroups] The list of filters on * resource groups, allowed at subscription level only. * * @param {array} [parameters.filters.resources] The list of filters on * resources. * * @param {array} [parameters.filters.meters] The list of filters on meters * (GUID), mandatory for budgets of usage category. * * @param {object} [parameters.filters.tags] The dictionary of filters on tags. * * @param {object} [parameters.notifications] Dictionary of notifications * associated with the budget. Budget can have up to five notifications. * * @param {string} [parameters.eTag] eTag of the resource. To handle concurrent * update scenarion, this field will be used to determine whether the user is * updating the latest version or not. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Budget} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Budget} [result] - The deserialized result object if an error did not occur. * See {@link Budget} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(budgetName: string, parameters: models.Budget, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Budget>; createOrUpdate(budgetName: string, parameters: models.Budget, callback: ServiceCallback<models.Budget>): void; createOrUpdate(budgetName: string, parameters: models.Budget, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Budget>): void; /** * The operation to delete a budget. * * @param {string} budgetName Budget Name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(budgetName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * The operation to delete a budget. * * @param {string} budgetName Budget Name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(budgetName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(budgetName: string, callback: ServiceCallback<void>): void; deleteMethod(budgetName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Gets the budget for a resource group under a subscription by budget name. * * @param {string} resourceGroupName Azure Resource Group Name. * * @param {string} budgetName Budget Name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Budget>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getByResourceGroupNameWithHttpOperationResponse(resourceGroupName: string, budgetName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Budget>>; /** * Gets the budget for a resource group under a subscription by budget name. * * @param {string} resourceGroupName Azure Resource Group Name. * * @param {string} budgetName Budget Name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Budget} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Budget} [result] - The deserialized result object if an error did not occur. * See {@link Budget} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getByResourceGroupName(resourceGroupName: string, budgetName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Budget>; getByResourceGroupName(resourceGroupName: string, budgetName: string, callback: ServiceCallback<models.Budget>): void; getByResourceGroupName(resourceGroupName: string, budgetName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Budget>): void; /** * The operation to create or update a budget. Update operation requires latest * eTag to be set in the request mandatorily. You may obtain the latest eTag by * performing a get operation. Create operation does not require eTag. * * @param {string} resourceGroupName Azure Resource Group Name. * * @param {string} budgetName Budget Name. * * @param {object} parameters Parameters supplied to the Create Budget * operation. * * @param {string} parameters.category The category of the budget, whether the * budget tracks cost or usage. Possible values include: 'Cost', 'Usage' * * @param {number} parameters.amount The total amount of cost to track with the * budget * * @param {string} parameters.timeGrain The time covered by a budget. Tracking * of the amount will be reset based on the time grain. Possible values * include: 'Monthly', 'Quarterly', 'Annually' * * @param {object} parameters.timePeriod Has start and end date of the budget. * The start date must be first of the month and should be less than the end * date. Budget start date must be on or after June 1, 2017. Future start date * should not be more than three months. Past start date should be selected * within the timegrain preiod. There are no restrictions on the end date. * * @param {date} parameters.timePeriod.startDate The start date for the budget. * * @param {date} [parameters.timePeriod.endDate] The end date for the budget. * If not provided, we default this to 10 years from the start date. * * @param {object} [parameters.filters] May be used to filter budgets by * resource group, resource, or meter. * * @param {array} [parameters.filters.resourceGroups] The list of filters on * resource groups, allowed at subscription level only. * * @param {array} [parameters.filters.resources] The list of filters on * resources. * * @param {array} [parameters.filters.meters] The list of filters on meters * (GUID), mandatory for budgets of usage category. * * @param {object} [parameters.filters.tags] The dictionary of filters on tags. * * @param {object} [parameters.notifications] Dictionary of notifications * associated with the budget. Budget can have up to five notifications. * * @param {string} [parameters.eTag] eTag of the resource. To handle concurrent * update scenarion, this field will be used to determine whether the user is * updating the latest version or not. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Budget>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateByResourceGroupNameWithHttpOperationResponse(resourceGroupName: string, budgetName: string, parameters: models.Budget, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Budget>>; /** * The operation to create or update a budget. Update operation requires latest * eTag to be set in the request mandatorily. You may obtain the latest eTag by * performing a get operation. Create operation does not require eTag. * * @param {string} resourceGroupName Azure Resource Group Name. * * @param {string} budgetName Budget Name. * * @param {object} parameters Parameters supplied to the Create Budget * operation. * * @param {string} parameters.category The category of the budget, whether the * budget tracks cost or usage. Possible values include: 'Cost', 'Usage' * * @param {number} parameters.amount The total amount of cost to track with the * budget * * @param {string} parameters.timeGrain The time covered by a budget. Tracking * of the amount will be reset based on the time grain. Possible values * include: 'Monthly', 'Quarterly', 'Annually' * * @param {object} parameters.timePeriod Has start and end date of the budget. * The start date must be first of the month and should be less than the end * date. Budget start date must be on or after June 1, 2017. Future start date * should not be more than three months. Past start date should be selected * within the timegrain preiod. There are no restrictions on the end date. * * @param {date} parameters.timePeriod.startDate The start date for the budget. * * @param {date} [parameters.timePeriod.endDate] The end date for the budget. * If not provided, we default this to 10 years from the start date. * * @param {object} [parameters.filters] May be used to filter budgets by * resource group, resource, or meter. * * @param {array} [parameters.filters.resourceGroups] The list of filters on * resource groups, allowed at subscription level only. * * @param {array} [parameters.filters.resources] The list of filters on * resources. * * @param {array} [parameters.filters.meters] The list of filters on meters * (GUID), mandatory for budgets of usage category. * * @param {object} [parameters.filters.tags] The dictionary of filters on tags. * * @param {object} [parameters.notifications] Dictionary of notifications * associated with the budget. Budget can have up to five notifications. * * @param {string} [parameters.eTag] eTag of the resource. To handle concurrent * update scenarion, this field will be used to determine whether the user is * updating the latest version or not. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Budget} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Budget} [result] - The deserialized result object if an error did not occur. * See {@link Budget} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdateByResourceGroupName(resourceGroupName: string, budgetName: string, parameters: models.Budget, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Budget>; createOrUpdateByResourceGroupName(resourceGroupName: string, budgetName: string, parameters: models.Budget, callback: ServiceCallback<models.Budget>): void; createOrUpdateByResourceGroupName(resourceGroupName: string, budgetName: string, parameters: models.Budget, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Budget>): void; /** * The operation to delete a budget. * * @param {string} resourceGroupName Azure Resource Group Name. * * @param {string} budgetName Budget Name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteByResourceGroupNameWithHttpOperationResponse(resourceGroupName: string, budgetName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * The operation to delete a budget. * * @param {string} resourceGroupName Azure Resource Group Name. * * @param {string} budgetName Budget Name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteByResourceGroupName(resourceGroupName: string, budgetName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteByResourceGroupName(resourceGroupName: string, budgetName: string, callback: ServiceCallback<void>): void; deleteByResourceGroupName(resourceGroupName: string, budgetName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Lists all budgets for a subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BudgetsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BudgetsListResult>>; /** * Lists all budgets for a subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BudgetsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BudgetsListResult} [result] - The deserialized result object if an error did not occur. * See {@link BudgetsListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.BudgetsListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.BudgetsListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BudgetsListResult>): void; /** * Lists all budgets for a resource group under a subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<BudgetsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByResourceGroupNameNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.BudgetsListResult>>; /** * Lists all budgets for a resource group under a subscription. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {BudgetsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {BudgetsListResult} [result] - The deserialized result object if an error did not occur. * See {@link BudgetsListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByResourceGroupNameNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.BudgetsListResult>; listByResourceGroupNameNext(nextPageLink: string, callback: ServiceCallback<models.BudgetsListResult>): void; listByResourceGroupNameNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.BudgetsListResult>): void; } /** * @class * PriceSheet * __NOTE__: An instance of this class is automatically created for an * instance of the ConsumptionManagementClient. */ export interface PriceSheet { /** * Gets the price sheet for a scope by subscriptionId. Price sheet is available * via this API only for May 1, 2014 or later. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/meterDetails within a price sheet. By default, these fields are * not included when returning price sheet. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the top N results. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PriceSheetResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(options?: { expand? : string, skiptoken? : string, top? : number, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PriceSheetResult>>; /** * Gets the price sheet for a scope by subscriptionId. Price sheet is available * via this API only for May 1, 2014 or later. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/meterDetails within a price sheet. By default, these fields are * not included when returning price sheet. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the top N results. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PriceSheetResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PriceSheetResult} [result] - The deserialized result object if an error did not occur. * See {@link PriceSheetResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(options?: { expand? : string, skiptoken? : string, top? : number, customHeaders? : { [headerName: string]: string; } }): Promise<models.PriceSheetResult>; get(callback: ServiceCallback<models.PriceSheetResult>): void; get(options: { expand? : string, skiptoken? : string, top? : number, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PriceSheetResult>): void; /** * Get the price sheet for a scope by subscriptionId and billing period. Price * sheet is available via this API only for May 1, 2014 or later. * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/meterDetails within a price sheet. By default, these fields are * not included when returning price sheet. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the top N results. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<PriceSheetResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getByBillingPeriodWithHttpOperationResponse(billingPeriodName: string, options?: { expand? : string, skiptoken? : string, top? : number, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.PriceSheetResult>>; /** * Get the price sheet for a scope by subscriptionId and billing period. Price * sheet is available via this API only for May 1, 2014 or later. * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.expand] May be used to expand the * properties/meterDetails within a price sheet. By default, these fields are * not included when returning price sheet. * * @param {string} [options.skiptoken] Skiptoken is only used if a previous * operation returned a partial result. If a previous response contains a * nextLink element, the value of the nextLink element will include a skiptoken * parameter that specifies a starting point to use for subsequent calls. * * @param {number} [options.top] May be used to limit the number of results to * the top N results. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {PriceSheetResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {PriceSheetResult} [result] - The deserialized result object if an error did not occur. * See {@link PriceSheetResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getByBillingPeriod(billingPeriodName: string, options?: { expand? : string, skiptoken? : string, top? : number, customHeaders? : { [headerName: string]: string; } }): Promise<models.PriceSheetResult>; getByBillingPeriod(billingPeriodName: string, callback: ServiceCallback<models.PriceSheetResult>): void; getByBillingPeriod(billingPeriodName: string, options: { expand? : string, skiptoken? : string, top? : number, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.PriceSheetResult>): void; } /** * @class * Tags * __NOTE__: An instance of this class is automatically created for an * instance of the ConsumptionManagementClient. */ export interface Tags { /** * Get all available tag keys for a billing account. * * @param {string} billingAccountId BillingAccount ID * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<TagsResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(billingAccountId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.TagsResult>>; /** * Get all available tag keys for a billing account. * * @param {string} billingAccountId BillingAccount ID * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {TagsResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {TagsResult} [result] - The deserialized result object if an error did not occur. * See {@link TagsResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(billingAccountId: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.TagsResult>; get(billingAccountId: string, callback: ServiceCallback<models.TagsResult>): void; get(billingAccountId: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.TagsResult>): void; } /** * @class * Forecasts * __NOTE__: An instance of this class is automatically created for an * instance of the ConsumptionManagementClient. */ export interface Forecasts { /** * Lists the forecast charges by subscriptionId. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter forecasts by * properties/usageDate (Utc time), properties/chargeType or properties/grain. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ForecastsListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ForecastsListResult>>; /** * Lists the forecast charges by subscriptionId. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter forecasts by * properties/usageDate (Utc time), properties/chargeType or properties/grain. * The filter supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not * currently support 'ne', 'or', or 'not'. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ForecastsListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ForecastsListResult} [result] - The deserialized result object if an error did not occur. * See {@link ForecastsListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ForecastsListResult>; list(callback: ServiceCallback<models.ForecastsListResult>): void; list(options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ForecastsListResult>): void; } /** * @class * Operations * __NOTE__: An instance of this class is automatically created for an * instance of the ConsumptionManagementClient. */ export interface Operations { /** * Lists all of the available consumption REST API operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * Lists all of the available consumption REST API operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; list(callback: ServiceCallback<models.OperationListResult>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; /** * Lists all of the available consumption REST API operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationListResult>>; /** * Lists all of the available consumption REST API operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationListResult} [result] - The deserialized result object if an error did not occur. * See {@link OperationListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationListResult>; listNext(nextPageLink: string, callback: ServiceCallback<models.OperationListResult>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationListResult>): void; } /** * @class * AggregatedCost * __NOTE__: An instance of this class is automatically created for an * instance of the ConsumptionManagementClient. */ export interface AggregatedCost { /** * Provides the aggregate cost of a management group and all child management * groups by current billing period. * * @param {string} managementGroupId Azure Management Group ID. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter aggregated cost by * properties/usageStart (Utc time), properties/usageEnd (Utc time). The filter * supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently * support 'ne', 'or', or 'not'. Tag filter is a key value pair string where * key and value is separated by a colon (:). * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ManagementGroupAggregatedCostResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getByManagementGroupWithHttpOperationResponse(managementGroupId: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementGroupAggregatedCostResult>>; /** * Provides the aggregate cost of a management group and all child management * groups by current billing period. * * @param {string} managementGroupId Azure Management Group ID. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter aggregated cost by * properties/usageStart (Utc time), properties/usageEnd (Utc time). The filter * supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently * support 'ne', 'or', or 'not'. Tag filter is a key value pair string where * key and value is separated by a colon (:). * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ManagementGroupAggregatedCostResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ManagementGroupAggregatedCostResult} [result] - The deserialized result object if an error did not occur. * See {@link ManagementGroupAggregatedCostResult} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getByManagementGroup(managementGroupId: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementGroupAggregatedCostResult>; getByManagementGroup(managementGroupId: string, callback: ServiceCallback<models.ManagementGroupAggregatedCostResult>): void; getByManagementGroup(managementGroupId: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementGroupAggregatedCostResult>): void; /** * Provides the aggregate cost of a management group and all child management * groups by specified billing period * * @param {string} managementGroupId Azure Management Group ID. * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ManagementGroupAggregatedCostResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getForBillingPeriodByManagementGroupWithHttpOperationResponse(managementGroupId: string, billingPeriodName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ManagementGroupAggregatedCostResult>>; /** * Provides the aggregate cost of a management group and all child management * groups by specified billing period * * @param {string} managementGroupId Azure Management Group ID. * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ManagementGroupAggregatedCostResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ManagementGroupAggregatedCostResult} [result] - The deserialized result object if an error did not occur. * See {@link ManagementGroupAggregatedCostResult} for * more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getForBillingPeriodByManagementGroup(managementGroupId: string, billingPeriodName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ManagementGroupAggregatedCostResult>; getForBillingPeriodByManagementGroup(managementGroupId: string, billingPeriodName: string, callback: ServiceCallback<models.ManagementGroupAggregatedCostResult>): void; getForBillingPeriodByManagementGroup(managementGroupId: string, billingPeriodName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ManagementGroupAggregatedCostResult>): void; } /** * @class * Charges * __NOTE__: An instance of this class is automatically created for an * instance of the ConsumptionManagementClient. */ export interface Charges { /** * Lists the charges by enrollmentAccountId. * * @param {string} billingAccountId BillingAccount ID * * @param {string} enrollmentAccountId EnrollmentAccount ID * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter charges by * properties/usageEnd (Utc time), properties/usageStart (Utc time). The filter * supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently * support 'ne', 'or', or 'not'. Tag filter is a key value pair string where * key and value is separated by a colon (:). * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ChargesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByEnrollmentAccountWithHttpOperationResponse(billingAccountId: string, enrollmentAccountId: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ChargesListResult>>; /** * Lists the charges by enrollmentAccountId. * * @param {string} billingAccountId BillingAccount ID * * @param {string} enrollmentAccountId EnrollmentAccount ID * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter charges by * properties/usageEnd (Utc time), properties/usageStart (Utc time). The filter * supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently * support 'ne', 'or', or 'not'. Tag filter is a key value pair string where * key and value is separated by a colon (:). * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ChargesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ChargesListResult} [result] - The deserialized result object if an error did not occur. * See {@link ChargesListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByEnrollmentAccount(billingAccountId: string, enrollmentAccountId: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ChargesListResult>; listByEnrollmentAccount(billingAccountId: string, enrollmentAccountId: string, callback: ServiceCallback<models.ChargesListResult>): void; listByEnrollmentAccount(billingAccountId: string, enrollmentAccountId: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ChargesListResult>): void; /** * Lists the charges based on enrollmentAccountId by billing period. * * @param {string} billingAccountId BillingAccount ID * * @param {string} enrollmentAccountId EnrollmentAccount ID * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter charges by * properties/usageEnd (Utc time), properties/usageStart (Utc time). The filter * supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently * support 'ne', 'or', or 'not'. Tag filter is a key value pair string where * key and value is separated by a colon (:). * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ChargeSummary>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForBillingPeriodByEnrollmentAccountWithHttpOperationResponse(billingAccountId: string, enrollmentAccountId: string, billingPeriodName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ChargeSummary>>; /** * Lists the charges based on enrollmentAccountId by billing period. * * @param {string} billingAccountId BillingAccount ID * * @param {string} enrollmentAccountId EnrollmentAccount ID * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter charges by * properties/usageEnd (Utc time), properties/usageStart (Utc time). The filter * supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently * support 'ne', 'or', or 'not'. Tag filter is a key value pair string where * key and value is separated by a colon (:). * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ChargeSummary} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ChargeSummary} [result] - The deserialized result object if an error did not occur. * See {@link ChargeSummary} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForBillingPeriodByEnrollmentAccount(billingAccountId: string, enrollmentAccountId: string, billingPeriodName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ChargeSummary>; listForBillingPeriodByEnrollmentAccount(billingAccountId: string, enrollmentAccountId: string, billingPeriodName: string, callback: ServiceCallback<models.ChargeSummary>): void; listForBillingPeriodByEnrollmentAccount(billingAccountId: string, enrollmentAccountId: string, billingPeriodName: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ChargeSummary>): void; /** * Lists the charges by departmentId. * * @param {string} billingAccountId BillingAccount ID * * @param {string} departmentId Department ID * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter charges by * properties/usageEnd (Utc time), properties/usageStart (Utc time). The filter * supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently * support 'ne', 'or', or 'not'. Tag filter is a key value pair string where * key and value is separated by a colon (:). * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ChargesListResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listByDepartmentWithHttpOperationResponse(billingAccountId: string, departmentId: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ChargesListResult>>; /** * Lists the charges by departmentId. * * @param {string} billingAccountId BillingAccount ID * * @param {string} departmentId Department ID * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter charges by * properties/usageEnd (Utc time), properties/usageStart (Utc time). The filter * supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently * support 'ne', 'or', or 'not'. Tag filter is a key value pair string where * key and value is separated by a colon (:). * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ChargesListResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ChargesListResult} [result] - The deserialized result object if an error did not occur. * See {@link ChargesListResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listByDepartment(billingAccountId: string, departmentId: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ChargesListResult>; listByDepartment(billingAccountId: string, departmentId: string, callback: ServiceCallback<models.ChargesListResult>): void; listByDepartment(billingAccountId: string, departmentId: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ChargesListResult>): void; /** * Lists the charges based on departmentId by billing period. * * @param {string} billingAccountId BillingAccount ID * * @param {string} departmentId Department ID * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter charges by * properties/usageEnd (Utc time), properties/usageStart (Utc time). The filter * supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently * support 'ne', 'or', or 'not'. Tag filter is a key value pair string where * key and value is separated by a colon (:). * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ChargeSummary>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listForBillingPeriodByDepartmentWithHttpOperationResponse(billingAccountId: string, departmentId: string, billingPeriodName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ChargeSummary>>; /** * Lists the charges based on departmentId by billing period. * * @param {string} billingAccountId BillingAccount ID * * @param {string} departmentId Department ID * * @param {string} billingPeriodName Billing Period Name. * * @param {object} [options] Optional Parameters. * * @param {string} [options.filter] May be used to filter charges by * properties/usageEnd (Utc time), properties/usageStart (Utc time). The filter * supports 'eq', 'lt', 'gt', 'le', 'ge', and 'and'. It does not currently * support 'ne', 'or', or 'not'. Tag filter is a key value pair string where * key and value is separated by a colon (:). * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ChargeSummary} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ChargeSummary} [result] - The deserialized result object if an error did not occur. * See {@link ChargeSummary} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listForBillingPeriodByDepartment(billingAccountId: string, departmentId: string, billingPeriodName: string, options?: { filter? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ChargeSummary>; listForBillingPeriodByDepartment(billingAccountId: string, departmentId: string, billingPeriodName: string, callback: ServiceCallback<models.ChargeSummary>): void; listForBillingPeriodByDepartment(billingAccountId: string, departmentId: string, billingPeriodName: string, options: { filter? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ChargeSummary>): void; }
the_stack
import * as jsonMergePatch from 'json-merge-patch'; import * as queryString from 'querystring'; import { BrowserforcePlugin } from '../../../plugin'; import { removeNullValues, semanticallyCleanObject } from '../../utils'; const PATHS = { LIST_VIEW: '_ui/core/portal/CustomerSuccessPortalSetup/d', PORTAL_PROFILE_MEMBERSHIP: '_ui/core/portal/PortalProfileMembershipPage/e' }; const SELECTORS = { SAVE_BUTTON: 'input[name="save"]', LIST_VIEW_PORTAL_LINKS_XPATH: '//div[contains(@class,"pbBody")]//th[contains(@class,"dataCell")]//a[starts-with(@href, "/060")]', PORTAL_DESCRIPTION: '#Description', PORTAL_ID: '#portalId', PORTAL_ADMIN_ID: 'Admin', PORTAL_IS_SELF_REGISTRATION_ACTIVATED_ID: 'IsSelfRegistrationActivated', PORTAL_SELF_REG_USER_DEFAULT_LICENSE_ID: 'SelfRegUserDefaultLicense', PORTAL_SELF_REG_USER_DEFAULT_ROLE_ID: 'SelfRegUserDefaultRole', PORTAL_SELF_REG_USER_DEFAULT_PROFILE_ID: 'SelfRegUserDefaultProfile', PORTAL_PROFILE_MEMBERSHIP_PROFILES: 'th.dataCell', PORTAL_PROFILE_MEMBERSHIP_CHECKBOXES: 'td.dataCell input' }; export type Config = PortalConfig[]; type PortalConfig = { adminUser?: string; description?: string; isSelfRegistrationActivated?: boolean; name: string; oldName?: string; selfRegUserDefaultLicense?: string; selfRegUserDefaultProfile?: string; selfRegUserDefaultRole?: string; portalProfileMemberships?: PortalProfileMembership[]; _id?: string; }; type PortalProfileMembership = { name: string; active: boolean; _id?: string; }; export class CustomerPortalSetup extends BrowserforcePlugin { // eslint-disable-next-line @typescript-eslint/no-unused-vars public async retrieve(definition?: Config): Promise<Config> { const page = await this.browserforce.openPage(PATHS.LIST_VIEW); await page.waitForXPath(SELECTORS.LIST_VIEW_PORTAL_LINKS_XPATH); const customerPortalLinks = await page.$x( SELECTORS.LIST_VIEW_PORTAL_LINKS_XPATH ); const response: Config = await page.evaluate((...links) => { return links.map((a: HTMLAnchorElement) => { return { _id: a.pathname.split('/')[1], name: a.text, portalProfileMemberships: [] }; }); }, ...customerPortalLinks); for (const portal of response) { const portalPage = await this.browserforce.openPage(`${portal._id}/e`); await portalPage.waitForSelector(SELECTORS.PORTAL_DESCRIPTION); portal.description = await portalPage.$eval( SELECTORS.PORTAL_DESCRIPTION, (el: HTMLInputElement) => el.value ); portal.adminUser = await portalPage.$eval( `#${SELECTORS.PORTAL_ADMIN_ID}`, (el: HTMLInputElement) => el.value ); portal.isSelfRegistrationActivated = await portalPage.$eval( `#${SELECTORS.PORTAL_IS_SELF_REGISTRATION_ACTIVATED_ID}`, (el: HTMLInputElement) => el.checked ); portal.selfRegUserDefaultLicense = await portalPage.$eval( `#${SELECTORS.PORTAL_SELF_REG_USER_DEFAULT_LICENSE_ID}`, (el: HTMLSelectElement) => el.selectedOptions[0].text ); portal.selfRegUserDefaultRole = await portalPage.$eval( `#${SELECTORS.PORTAL_SELF_REG_USER_DEFAULT_ROLE_ID}`, (el: HTMLSelectElement) => el.selectedOptions[0].text ); portal.selfRegUserDefaultProfile = await portalPage.$eval( `#${SELECTORS.PORTAL_SELF_REG_USER_DEFAULT_PROFILE_ID}`, (el: HTMLSelectElement) => el.selectedOptions[0].text ); // portalProfileMemberships const portalProfilePage = await this.browserforce.openPage( `${PATHS.PORTAL_PROFILE_MEMBERSHIP}?portalId=${portal._id}&setupid=CustomerSuccessPortalSettings` ); await portalProfilePage.waitForSelector(SELECTORS.PORTAL_ID); const profiles = await portalProfilePage.$$eval( SELECTORS.PORTAL_PROFILE_MEMBERSHIP_PROFILES, (ths: HTMLTableHeaderCellElement[]) => { return ths.map(th => th.innerText.trim()); } ); const checkboxes = await portalProfilePage.$$eval( SELECTORS.PORTAL_PROFILE_MEMBERSHIP_CHECKBOXES, (inputs: HTMLInputElement[]) => { return inputs.map(input => { return { active: input.checked, _id: input.id }; }); } ); const portalProfileMemberships = []; for (let i = 0; i < profiles.length; i++) { portalProfileMemberships.push({ name: profiles[i], active: checkboxes[i].active, _id: checkboxes[i]._id }); } portal.portalProfileMemberships = portalProfileMemberships; } return response; } public diff(source: Config, target: Config): Config { const response = []; if (source && target) { for (const portal of target) { let sourcePortal = source.find(p => p.name === portal.name); if (portal.oldName && !sourcePortal) { // fallback to old name of portal sourcePortal = source.find(p => p.name === portal.oldName); } if (!sourcePortal) { throw new Error( `Portal with name '${portal.name} (oldName: ${portal.oldName})' not found. Setting up new Portals is not yet supported.` ); } delete portal.oldName; if (sourcePortal) { // move id of existing portal to new portal to be retained and used portal._id = sourcePortal._id; delete sourcePortal._id; } if ( sourcePortal.portalProfileMemberships && portal.portalProfileMemberships ) { const membershipResponse = []; for (const member of portal.portalProfileMemberships) { // move id of existing member to new member to be retained and used const sourceMember = sourcePortal.portalProfileMemberships.find( m => m.name === member.name ); if (sourceMember) { member._id = sourceMember._id; delete sourceMember._id; } else { throw new Error( `Could not find portal profile membership for '${member.name}'` ); } const membershipDiff = semanticallyCleanObject( removeNullValues(jsonMergePatch.generate(sourceMember, member)), '_id' ); if (membershipDiff) { membershipResponse.push(membershipDiff); } } delete sourcePortal.portalProfileMemberships; delete portal.portalProfileMemberships; if (membershipResponse.length) { portal.portalProfileMemberships = membershipResponse; } } const diff = semanticallyCleanObject( removeNullValues(jsonMergePatch.generate(sourcePortal, portal)), '_id' ); if (diff) { response.push(diff); } } } return response; } public async apply(config: Config): Promise<void> { for (const portal of config) { if (portal._id) { // everything that can be changed using the url const urlAttributes = {}; if (portal.name) { urlAttributes['Name'] = portal.name; } if (portal.description) { urlAttributes['Description'] = portal.description; } if (portal.adminUser) { urlAttributes[SELECTORS.PORTAL_ADMIN_ID] = portal.adminUser; } if (portal.isSelfRegistrationActivated !== undefined) { urlAttributes[ SELECTORS.PORTAL_IS_SELF_REGISTRATION_ACTIVATED_ID ] = portal.isSelfRegistrationActivated ? 1 : 0; } const page = await this.browserforce.openPage( `${portal._id}/e?${queryString.stringify(urlAttributes)}` ); await page.waitForSelector(SELECTORS.PORTAL_DESCRIPTION); if (portal.selfRegUserDefaultLicense) { const licenseValue = await page.evaluate( (option: HTMLOptionElement) => option.value, ( await page.$x( `//select[@id="${SELECTORS.PORTAL_SELF_REG_USER_DEFAULT_LICENSE_ID}"]//option[text()="${portal.selfRegUserDefaultLicense}"]` ) )[0] ); await page.select( `#${SELECTORS.PORTAL_SELF_REG_USER_DEFAULT_LICENSE_ID}`, licenseValue ); } if (portal.selfRegUserDefaultRole) { const roleValue = await page.evaluate( (option: HTMLOptionElement) => option.value, ( await page.$x( `//select[@id="${SELECTORS.PORTAL_SELF_REG_USER_DEFAULT_ROLE_ID}"]//option[text()="${portal.selfRegUserDefaultRole}"]` ) )[0] ); await page.select( `#${SELECTORS.PORTAL_SELF_REG_USER_DEFAULT_ROLE_ID}`, roleValue ); } if (portal.selfRegUserDefaultProfile) { const profileValue = await page.evaluate( (option: HTMLOptionElement) => option.value, ( await page.$x( `//select[@id="${SELECTORS.PORTAL_SELF_REG_USER_DEFAULT_PROFILE_ID}"]//option[text()="${portal.selfRegUserDefaultProfile}"]` ) )[0] ); await page.select( `#${SELECTORS.PORTAL_SELF_REG_USER_DEFAULT_PROFILE_ID}`, profileValue ); } await page.waitForSelector(SELECTORS.SAVE_BUTTON); await Promise.all([ page.waitForNavigation({ waitUntil: ['load', 'domcontentloaded', 'networkidle0'] }), page.click(SELECTORS.SAVE_BUTTON) ]); if ((await page.url()).includes(portal._id)) { // error handling await page.waitForSelector(SELECTORS.PORTAL_DESCRIPTION); await this.browserforce.throwPageErrors(page); throw new Error(`saving customer portal '${portal._id}' failed`); } // portalProfileMemberships if (portal.portalProfileMemberships) { const membershipUrlAttributes = {}; for (const member of portal.portalProfileMemberships) { membershipUrlAttributes[member._id] = member.active ? 1 : 0; } const portalProfilePage = await this.browserforce.openPage( `${PATHS.PORTAL_PROFILE_MEMBERSHIP}?portalId=${ portal._id }&setupid=CustomerSuccessPortalSettings&${queryString.stringify( membershipUrlAttributes )}` ); await portalProfilePage.waitForSelector(SELECTORS.SAVE_BUTTON); await Promise.all([ portalProfilePage.waitForNavigation(), portalProfilePage.click(SELECTORS.SAVE_BUTTON) ]); } } } } }
the_stack
import { FHIRDefinitions } from './FHIRDefinitions'; import { PackageLoadError, CurrentPackageLoadError } from '../errors'; import fs from 'fs-extra'; import path from 'path'; import os from 'os'; import tar from 'tar'; import axios from 'axios'; import junk from 'junk'; import temp from 'temp'; import { logger, getFilesRecursive } from '../utils'; import { Fhir as FHIRConverter } from 'fhir/fhir'; /** * Loads a dependency from user FHIR cache or from online * @param {string} packageName - The name of the package to load * @param {string} version - The version of the package to load * @param {FHIRDefinitions} FHIRDefs - The FHIRDefinitions to load the dependencies into * @param {string} cachePath - The path to load the package into * @returns {Promise<FHIRDefinitions>} the loaded FHIRDefs * @throws {PackageLoadError} when the desired package can't be loaded */ export async function loadDependency( packageName: string, version: string, FHIRDefs: FHIRDefinitions, cachePath: string = path.join(os.homedir(), '.fhir', 'packages') ): Promise<FHIRDefinitions> { let fullPackageName = `${packageName}#${version}`; const loadPath = path.join(cachePath, fullPackageName, 'package'); let loadedPackage: string; // First, try to load the package from the local cache logger.info(`Checking local cache for ${fullPackageName}...`); loadedPackage = loadFromPath(cachePath, fullPackageName, FHIRDefs); if (loadedPackage) { logger.info(`Found ${fullPackageName} in local cache.`); } else { logger.info(`Did not find ${fullPackageName} in local cache.`); } // When a dev package is not present locally, fall back to using the current version // as described here https://confluence.hl7.org/pages/viewpage.action?pageId=35718627#IGPublisherDocumentation-DependencyList if (version === 'dev' && !loadedPackage) { logger.info( `Falling back to ${packageName}#current since ${fullPackageName} is not locally cached. To avoid this, add ${fullPackageName} to your local FHIR cache by building it locally with the HL7 FHIR IG Publisher.` ); version = 'current'; fullPackageName = `${packageName}#${version}`; loadedPackage = loadFromPath(cachePath, fullPackageName, FHIRDefs); } let packageUrl; if (packageName.startsWith('hl7.fhir.r5.') && version === 'current') { packageUrl = `https://build.fhir.org/${packageName}.tgz`; // TODO: Figure out how to determine if the cached package is current // See: https://chat.fhir.org/#narrow/stream/179252-IG-creation/topic/Registry.20for.20FHIR.20Core.20packages.20.3E.204.2E0.2E1 if (loadedPackage) { logger.info( `Downloading ${fullPackageName} since SUSHI cannot determine if the version in the local cache is the most recent build.` ); } } else if (version === 'current') { // Even if a local current package is loaded, we must still check that the local package date matches // the date on the most recent version on build.fhir.org. If the date does not match, we re-download to the cache const baseUrl = 'https://build.fhir.org/ig'; const res = await axios.get(`${baseUrl}/qas.json`); const qaData: { 'package-id': string; date: string; repo: string }[] = res?.data; // Find matching packages and sort by date to get the most recent let newestPackage; if (qaData?.length > 0) { const matchingPackages = qaData.filter(p => p['package-id'] === packageName); newestPackage = matchingPackages.sort((p1, p2) => { return Date.parse(p2['date']) - Date.parse(p1['date']); })[0]; } if (newestPackage?.repo) { const [org, repo] = newestPackage.repo.split('/'); const igUrl = `${baseUrl}/${org}/${repo}`; // get the package.manifest.json for the newest version of the package on build.fhir.org const manifest = await axios.get(`${igUrl}/package.manifest.json`); let cachedPackageJSON; if (fs.existsSync(path.join(loadPath, 'package.json'))) { cachedPackageJSON = fs.readJSONSync(path.join(loadPath, 'package.json')); } // if the date on the package.manifest.json does not match the date on the cached package // set the packageUrl to trigger a re-download of the package if (manifest?.data?.date !== cachedPackageJSON?.date) { packageUrl = `${igUrl}/package.tgz`; if (cachedPackageJSON) { logger.debug( `Cached package date for ${fullPackageName} (${formatDate( cachedPackageJSON.date )}) does not match last build date on build.fhir.org (${formatDate( manifest?.data?.date )})` ); logger.info( `Cached package ${fullPackageName} is out of date and will be replaced by the more recent version found on build.fhir.org.` ); } } else { logger.debug( `Cached package date for ${fullPackageName} (${formatDate( cachedPackageJSON.date )}) matches last build date on build.fhir.org (${formatDate( manifest?.data?.date )}), so the cached package will be used` ); } } else { throw new CurrentPackageLoadError(fullPackageName); } } else if (!loadedPackage) { packageUrl = `https://packages.fhir.org/${packageName}/${version}`; } // If the packageUrl is set, we must download the package from that url, and extract it to our local cache if (packageUrl) { const doDownload = async (url: string) => { logger.info(`Downloading ${fullPackageName}...`); const res = await axios.get(url, { responseType: 'arraybuffer' }); if (res?.data) { logger.info(`Downloaded ${fullPackageName}`); // Create a temporary file and write the package to there temp.track(); const tempFile = temp.openSync(); fs.writeFileSync(tempFile.path, res.data); // Extract the package to a temporary directory const tempDirectory = temp.mkdirSync(); tar.x({ cwd: tempDirectory, file: tempFile.path, sync: true, strict: true }); cleanCachedPackage(tempDirectory); // Add or replace the package in the FHIR cache const targetDirectory = path.join(cachePath, fullPackageName); if (fs.existsSync(targetDirectory)) { fs.removeSync(targetDirectory); } fs.moveSync(tempDirectory, targetDirectory); // Now try to load again from the path loadedPackage = loadFromPath(cachePath, fullPackageName, FHIRDefs); } else { logger.info(`Unable to download most current version of ${fullPackageName}`); } }; try { await doDownload(packageUrl); } catch (e) { if (packageUrl === `https://packages.fhir.org/${packageName}/${version}`) { // It didn't exist in the normal registry. Fallback to packages2 registry. // See: https://chat.fhir.org/#narrow/stream/179252-IG-creation/topic/Registry.20for.20FHIR.20Core.20packages.20.3E.204.2E0.2E1 // See: https://chat.fhir.org/#narrow/stream/179252-IG-creation/topic/fhir.2Edicom/near/262334652 packageUrl = `https://packages2.fhir.org/packages/${packageName}/${version}`; try { await doDownload(packageUrl); } catch (e) { throw new PackageLoadError(fullPackageName); } } else { throw new PackageLoadError(fullPackageName); } } } if (!loadedPackage) { // If we fail again, then we couldn't get the package locally or from online throw new PackageLoadError(fullPackageName); } logger.info(`Loaded package ${fullPackageName}`); return FHIRDefs; } /** * This function takes a package which contains contents at the same level as the "package" folder, and nests * all that content within the "package" folder. * * A package should have the format described here https://confluence.hl7.org/pages/viewpage.action?pageId=35718629#NPMPackageSpecification-Format * in which all contents are within the "package" folder. Some packages (ex US Core 3.1.0) have an incorrect format in which folders * are not sub-folders of "package", but are instead at the same level. The IG Publisher fixes these packages as described * https://chat.fhir.org/#narrow/stream/215610-shorthand/topic/dev.20dependencies, so SUSHI should as well. * * @param {string} packageDirectory - The directory containing the package */ export function cleanCachedPackage(packageDirectory: string): void { if (fs.existsSync(path.join(packageDirectory, 'package'))) { fs.readdirSync(packageDirectory) .filter(file => file !== 'package') .forEach(file => { fs.renameSync( path.join(packageDirectory, file), path.join(packageDirectory, 'package', file) ); }); } } /** * Loads custom resources defined in resourceDir into FHIRDefs * @param {string} resourceDir - The path to the directory containing the resource subdirs * @param {FHIRDefinitions} defs - The FHIRDefinitions object to load definitions into */ export function loadCustomResources(resourceDir: string, defs: FHIRDefinitions): void { // Similar code for loading custom resources exists in IGExporter.ts addPredefinedResources() const pathEnds = [ 'capabilities', 'extensions', 'models', 'operations', 'profiles', 'resources', 'vocabulary', 'examples' ]; const converter = new FHIRConverter(); let invalidFileCount = 0; for (const pathEnd of pathEnds) { let foundSpreadsheets = false; const dirPath = path.join(resourceDir, pathEnd); if (fs.existsSync(dirPath)) { const files = getFilesRecursive(dirPath); for (const file of files) { let resourceJSON: any; try { if (junk.is(file)) { // Ignore "junk" files created by the OS, like .DS_Store on macOS and Thumbs.db on Windows continue; } else if (file.endsWith('.json')) { resourceJSON = fs.readJSONSync(file); } else if (file.endsWith('-spreadsheet.xml')) { foundSpreadsheets = true; continue; } else if (file.endsWith('xml')) { const xml = fs.readFileSync(file).toString(); if (/<\?mso-application progid="Excel\.Sheet"\?>/m.test(xml)) { foundSpreadsheets = true; continue; } resourceJSON = converter.xmlToObj(xml); } else { invalidFileCount++; continue; } } catch (e) { if (e.message.startsWith('Unknown resource type:')) { // Skip unknown FHIR resource types. When we have instances of Logical Models, // the resourceType will not be recognized as a known FHIR resourceType, but that's okay. continue; } logger.error(`Loading ${file} failed with the following error:\n${e.message}`); continue; } // All resources are added to the predefined map, so that this map can later be used to // access predefined resources in the IG Exporter defs.addPredefinedResource(file, resourceJSON); if (pathEnd !== 'examples') { // add() will only add resources of resourceType: // StructureDefinition, ValueSet, CodeSystem, or ImplementationGuide defs.add(resourceJSON); } } } if (foundSpreadsheets) { logger.info( `Found spreadsheets in directory ${dirPath}. SUSHI does not support spreadsheets, so any resources in the spreadsheets will be ignored.` ); } } if (invalidFileCount > 0) { logger.info( invalidFileCount > 1 ? `Found ${invalidFileCount} files in input/* resource folders that were neither XML nor JSON. These files were not processed as resources by SUSHI.` : `Found ${invalidFileCount} file in an input/* resource folder that was neither XML nor JSON. This file was not processed as a resource by SUSHI.` ); } } /** * Locates the targetPackage within the cachePath and loads the set of JSON files into FHIRDefs * @param {string} cachePath - The path to the directory containing cached packages * @param {string} targetPackage - The name of the package we are trying to load * @param {FHIRDefinitions} FHIRDefs - The FHIRDefinitions object to load defs into * @returns {string} the name of the loaded package if successful */ export function loadFromPath( cachePath: string, targetPackage: string, FHIRDefs: FHIRDefinitions ): string { if (FHIRDefs.packages.indexOf(targetPackage) < 0) { const originalSize = FHIRDefs.size(); const packages = fs.existsSync(cachePath) ? fs.readdirSync(cachePath) : []; const cachedPackage = packages.find(packageName => packageName.toLowerCase() === targetPackage); if (cachedPackage) { const files = fs.readdirSync(path.join(cachePath, cachedPackage, 'package')); for (const file of files) { if (file.endsWith('.json')) { const def = JSON.parse( fs.readFileSync(path.join(cachePath, cachedPackage, 'package', file), 'utf-8').trim() ); FHIRDefs.add(def); if (file === 'package.json') { FHIRDefs.addPackageJson(targetPackage, def); } } } } // If we did successfully load definitions, mark this package as loaded if (FHIRDefs.size() > originalSize) { FHIRDefs.packages.push(targetPackage); return targetPackage; } } else { // If the package has already been loaded, just return the targetPackage string return targetPackage; } } /** * Loads a "supplemental" FHIR package other than the primary FHIR version being used. This is * needed to support extensions for converting between versions (e.g., "implied" extensions). * The definitions from the supplemental FHIR package are not loaded into the main set of * definitions, but rather, are loaded into their own private FHIRDefinitions instance accessible * within the primary FHIRDefinitions instance passed into this function. * @param fhirPackage - the FHIR package to load in the format {packageId}#{version} * @param defs - the FHIRDefinitions object to load the supplemental FHIR defs into * @returns Promise<void> promise that always resolves successfully (even if there is an error) */ export async function loadSupplementalFHIRPackage( fhirPackage: string, defs: FHIRDefinitions ): Promise<void> { const supplementalDefs = new FHIRDefinitions(true); const [fhirPackageId, fhirPackageVersion] = fhirPackage.split('#'); // Testing Hack: Use exports.loadDependency instead of loadDependency so that this function // calls the mocked loadDependency in unit tests. In normal (non-test) use, this should // have no negative effects. return exports .loadDependency(fhirPackageId, fhirPackageVersion, supplementalDefs) .then((def: FHIRDefinitions) => defs.addSupplementalFHIRDefinitions(fhirPackage, def)) .catch((e: Error) => { logger.error(`Failed to load supplemental FHIR package ${fhirPackage}: ${e.message}`); }); } /** * Takes a date in format YYYYMMDDHHmmss and converts to YYYY-MM-DDTHH:mm:ss * @param {string} date - The date to format * @returns {string} the formatted date */ function formatDate(date: string): string { return date ? date.replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/, '$1-$2-$3T$4:$5:$6') : ''; }
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type InboxTestsQueryVariables = {}; export type InboxTestsQueryResponse = { readonly me: { readonly " $fragmentRefs": FragmentRefs<"Inbox_me">; } | null; }; export type InboxTestsQuery = { readonly response: InboxTestsQueryResponse; readonly variables: InboxTestsQueryVariables; }; /* query InboxTestsQuery { me { ...Inbox_me id } } fragment ActiveLotStanding_saleArtwork on SaleArtwork { ...Lot_saleArtwork isHighestBidder sale { status liveStartAt endAt id } lotState { bidCount reserveStatus soldStatus sellingPrice { display } } artwork { internalID href slug id } currentBid { display } estimate } fragment ClosedLotStanding_saleArtwork on SaleArtwork { ...Lot_saleArtwork isHighestBidder estimate artwork { internalID href slug id } lotState { soldStatus sellingPrice { display } } sale { endAt status id } } fragment ConversationSnippet_conversation on Conversation { internalID to { name id } lastMessage lastMessageAt unread items { item { __typename ... on Artwork { date title artistNames image { url } } ... on Show { fair { name id } name coverImage { url } } ... on Node { __isNode: __typename id } } } } fragment Conversations_me on Me { conversations: conversationsConnection(first: 10, after: "") { pageInfo { endCursor hasNextPage } edges { node { internalID last_message: lastMessage ...ConversationSnippet_conversation items { item { __typename ... on Artwork { internalID partner { internalID id } } ... on Node { __isNode: __typename id } } } id __typename } cursor } totalUnreadCount } } fragment Inbox_me on Me { ...Conversations_me ...MyBids_me } fragment LotStatusListItem_saleArtwork on SaleArtwork { ...ClosedLotStanding_saleArtwork ...ActiveLotStanding_saleArtwork ...WatchedLot_saleArtwork isWatching lotState { soldStatus } } fragment Lot_saleArtwork on SaleArtwork { lotLabel artwork { artistNames image { url(version: "medium") } id } } fragment MyBids_me on Me { ...SaleCard_me myBids { active { sale { ...SaleCard_sale internalID registrationStatus { qualifiedForBidding id } id } saleArtworks { ...LotStatusListItem_saleArtwork internalID id } } closed { sale { ...SaleCard_sale internalID registrationStatus { qualifiedForBidding id } id } saleArtworks { ...LotStatusListItem_saleArtwork internalID id } } } } fragment SaleCard_me on Me { identityVerified pendingIdentityVerification { internalID id } } fragment SaleCard_sale on Sale { internalID href slug name liveStartAt endAt coverImage { url } partner { name id } registrationStatus { qualifiedForBidding id } requireIdentityVerification } fragment WatchedLot_saleArtwork on SaleArtwork { ...Lot_saleArtwork lotState { bidCount sellingPrice { display } } artwork { internalID href slug id } currentBid { display } estimate } */ const node: ConcreteRequest = (function(){ var v0 = [ { "kind": "Literal", "name": "after", "value": "" }, { "kind": "Literal", "name": "first", "value": 10 } ], v1 = { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, v2 = { "alias": null, "args": null, "kind": "ScalarField", "name": "name", "storageKey": null }, v3 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v4 = [ (v2/*: any*/), (v3/*: any*/) ], v5 = { "alias": null, "args": null, "kind": "ScalarField", "name": "__typename", "storageKey": null }, v6 = { "alias": null, "args": null, "kind": "ScalarField", "name": "artistNames", "storageKey": null }, v7 = [ { "alias": null, "args": null, "kind": "ScalarField", "name": "url", "storageKey": null } ], v8 = [ (v1/*: any*/), (v3/*: any*/) ], v9 = { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "coverImage", "plural": false, "selections": (v7/*: any*/), "storageKey": null }, v10 = { "alias": null, "args": null, "kind": "ScalarField", "name": "href", "storageKey": null }, v11 = { "alias": null, "args": null, "kind": "ScalarField", "name": "slug", "storageKey": null }, v12 = { "alias": null, "args": null, "kind": "ScalarField", "name": "liveStartAt", "storageKey": null }, v13 = { "alias": null, "args": null, "kind": "ScalarField", "name": "endAt", "storageKey": null }, v14 = [ { "alias": null, "args": null, "kind": "ScalarField", "name": "display", "storageKey": null } ], v15 = [ { "alias": null, "args": null, "concreteType": "Sale", "kind": "LinkedField", "name": "sale", "plural": false, "selections": [ (v1/*: any*/), (v10/*: any*/), (v11/*: any*/), (v2/*: any*/), (v12/*: any*/), (v13/*: any*/), (v9/*: any*/), { "alias": null, "args": null, "concreteType": "Partner", "kind": "LinkedField", "name": "partner", "plural": false, "selections": (v4/*: any*/), "storageKey": null }, { "alias": null, "args": null, "concreteType": "Bidder", "kind": "LinkedField", "name": "registrationStatus", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "qualifiedForBidding", "storageKey": null }, (v3/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "requireIdentityVerification", "storageKey": null }, (v3/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "SaleArtwork", "kind": "LinkedField", "name": "saleArtworks", "plural": true, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "lotLabel", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Artwork", "kind": "LinkedField", "name": "artwork", "plural": false, "selections": [ (v6/*: any*/), { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "image", "plural": false, "selections": [ { "alias": null, "args": [ { "kind": "Literal", "name": "version", "value": "medium" } ], "kind": "ScalarField", "name": "url", "storageKey": "url(version:\"medium\")" } ], "storageKey": null }, (v3/*: any*/), (v1/*: any*/), (v10/*: any*/), (v11/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "isHighestBidder", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "estimate", "storageKey": null }, { "alias": null, "args": null, "concreteType": "CausalityLotState", "kind": "LinkedField", "name": "lotState", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "soldStatus", "storageKey": null }, { "alias": null, "args": null, "concreteType": "Money", "kind": "LinkedField", "name": "sellingPrice", "plural": false, "selections": (v14/*: any*/), "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "bidCount", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "reserveStatus", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "Sale", "kind": "LinkedField", "name": "sale", "plural": false, "selections": [ (v13/*: any*/), { "alias": null, "args": null, "kind": "ScalarField", "name": "status", "storageKey": null }, (v3/*: any*/), (v12/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "SaleArtworkCurrentBid", "kind": "LinkedField", "name": "currentBid", "plural": false, "selections": (v14/*: any*/), "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "isWatching", "storageKey": null }, (v1/*: any*/), (v3/*: any*/) ], "storageKey": null } ], v16 = { "enumValues": null, "nullable": false, "plural": false, "type": "String" }, v17 = { "enumValues": null, "nullable": false, "plural": false, "type": "ID" }, v18 = { "enumValues": null, "nullable": true, "plural": false, "type": "String" }, v19 = { "enumValues": null, "nullable": true, "plural": false, "type": "Image" }, v20 = { "enumValues": null, "nullable": true, "plural": false, "type": "Partner" }, v21 = { "enumValues": null, "nullable": true, "plural": false, "type": "Boolean" }, v22 = { "enumValues": null, "nullable": true, "plural": false, "type": "Int" }, v23 = { "enumValues": null, "nullable": true, "plural": true, "type": "MyBid" }, v24 = { "enumValues": null, "nullable": true, "plural": false, "type": "Sale" }, v25 = { "enumValues": null, "nullable": true, "plural": false, "type": "Bidder" }, v26 = { "enumValues": null, "nullable": true, "plural": true, "type": "SaleArtwork" }, v27 = { "enumValues": null, "nullable": true, "plural": false, "type": "Artwork" }, v28 = { "enumValues": null, "nullable": true, "plural": false, "type": "SaleArtworkCurrentBid" }, v29 = { "enumValues": null, "nullable": true, "plural": false, "type": "CausalityLotState" }, v30 = { "enumValues": null, "nullable": true, "plural": false, "type": "Money" }; return { "fragment": { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "InboxTestsQuery", "selections": [ { "alias": null, "args": null, "concreteType": "Me", "kind": "LinkedField", "name": "me", "plural": false, "selections": [ { "args": null, "kind": "FragmentSpread", "name": "Inbox_me" } ], "storageKey": null } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": [], "kind": "Operation", "name": "InboxTestsQuery", "selections": [ { "alias": null, "args": null, "concreteType": "Me", "kind": "LinkedField", "name": "me", "plural": false, "selections": [ { "alias": "conversations", "args": (v0/*: any*/), "concreteType": "ConversationConnection", "kind": "LinkedField", "name": "conversationsConnection", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "PageInfo", "kind": "LinkedField", "name": "pageInfo", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "endCursor", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "hasNextPage", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "concreteType": "ConversationEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "Conversation", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ (v1/*: any*/), { "alias": "last_message", "args": null, "kind": "ScalarField", "name": "lastMessage", "storageKey": null }, { "alias": null, "args": null, "concreteType": "ConversationResponder", "kind": "LinkedField", "name": "to", "plural": false, "selections": (v4/*: any*/), "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "lastMessage", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "lastMessageAt", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "unread", "storageKey": null }, { "alias": null, "args": null, "concreteType": "ConversationItem", "kind": "LinkedField", "name": "items", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": null, "kind": "LinkedField", "name": "item", "plural": false, "selections": [ (v5/*: any*/), { "kind": "InlineFragment", "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "date", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "title", "storageKey": null }, (v6/*: any*/), { "alias": null, "args": null, "concreteType": "Image", "kind": "LinkedField", "name": "image", "plural": false, "selections": (v7/*: any*/), "storageKey": null }, (v1/*: any*/), { "alias": null, "args": null, "concreteType": "Partner", "kind": "LinkedField", "name": "partner", "plural": false, "selections": (v8/*: any*/), "storageKey": null } ], "type": "Artwork", "abstractKey": null }, { "kind": "InlineFragment", "selections": [ { "alias": null, "args": null, "concreteType": "Fair", "kind": "LinkedField", "name": "fair", "plural": false, "selections": (v4/*: any*/), "storageKey": null }, (v2/*: any*/), (v9/*: any*/) ], "type": "Show", "abstractKey": null }, { "kind": "InlineFragment", "selections": [ (v3/*: any*/) ], "type": "Node", "abstractKey": "__isNode" } ], "storageKey": null } ], "storageKey": null }, (v3/*: any*/), (v5/*: any*/) ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "cursor", "storageKey": null } ], "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "totalUnreadCount", "storageKey": null } ], "storageKey": "conversationsConnection(after:\"\",first:10)" }, { "alias": "conversations", "args": (v0/*: any*/), "filters": null, "handle": "connection", "key": "Conversations_conversations", "kind": "LinkedHandle", "name": "conversationsConnection" }, { "alias": null, "args": null, "kind": "ScalarField", "name": "identityVerified", "storageKey": null }, { "alias": null, "args": null, "concreteType": "IdentityVerification", "kind": "LinkedField", "name": "pendingIdentityVerification", "plural": false, "selections": (v8/*: any*/), "storageKey": null }, { "alias": null, "args": null, "concreteType": "MyBids", "kind": "LinkedField", "name": "myBids", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "MyBid", "kind": "LinkedField", "name": "active", "plural": true, "selections": (v15/*: any*/), "storageKey": null }, { "alias": null, "args": null, "concreteType": "MyBid", "kind": "LinkedField", "name": "closed", "plural": true, "selections": (v15/*: any*/), "storageKey": null } ], "storageKey": null }, (v3/*: any*/) ], "storageKey": null } ] }, "params": { "id": "cefa2c2884b877d40378eadc7babb5d7", "metadata": { "relayTestingSelectionTypeInfo": { "me": { "enumValues": null, "nullable": true, "plural": false, "type": "Me" }, "me.conversations": { "enumValues": null, "nullable": true, "plural": false, "type": "ConversationConnection" }, "me.conversations.edges": { "enumValues": null, "nullable": true, "plural": true, "type": "ConversationEdge" }, "me.conversations.edges.cursor": (v16/*: any*/), "me.conversations.edges.node": { "enumValues": null, "nullable": true, "plural": false, "type": "Conversation" }, "me.conversations.edges.node.__typename": (v16/*: any*/), "me.conversations.edges.node.id": (v17/*: any*/), "me.conversations.edges.node.internalID": { "enumValues": null, "nullable": true, "plural": false, "type": "ID" }, "me.conversations.edges.node.items": { "enumValues": null, "nullable": true, "plural": true, "type": "ConversationItem" }, "me.conversations.edges.node.items.item": { "enumValues": null, "nullable": true, "plural": false, "type": "ConversationItemType" }, "me.conversations.edges.node.items.item.__isNode": (v16/*: any*/), "me.conversations.edges.node.items.item.__typename": (v16/*: any*/), "me.conversations.edges.node.items.item.artistNames": (v18/*: any*/), "me.conversations.edges.node.items.item.coverImage": (v19/*: any*/), "me.conversations.edges.node.items.item.coverImage.url": (v18/*: any*/), "me.conversations.edges.node.items.item.date": (v18/*: any*/), "me.conversations.edges.node.items.item.fair": { "enumValues": null, "nullable": true, "plural": false, "type": "Fair" }, "me.conversations.edges.node.items.item.fair.id": (v17/*: any*/), "me.conversations.edges.node.items.item.fair.name": (v18/*: any*/), "me.conversations.edges.node.items.item.id": (v17/*: any*/), "me.conversations.edges.node.items.item.image": (v19/*: any*/), "me.conversations.edges.node.items.item.image.url": (v18/*: any*/), "me.conversations.edges.node.items.item.internalID": (v17/*: any*/), "me.conversations.edges.node.items.item.name": (v18/*: any*/), "me.conversations.edges.node.items.item.partner": (v20/*: any*/), "me.conversations.edges.node.items.item.partner.id": (v17/*: any*/), "me.conversations.edges.node.items.item.partner.internalID": (v17/*: any*/), "me.conversations.edges.node.items.item.title": (v18/*: any*/), "me.conversations.edges.node.lastMessage": (v18/*: any*/), "me.conversations.edges.node.lastMessageAt": (v18/*: any*/), "me.conversations.edges.node.last_message": (v18/*: any*/), "me.conversations.edges.node.to": { "enumValues": null, "nullable": false, "plural": false, "type": "ConversationResponder" }, "me.conversations.edges.node.to.id": (v17/*: any*/), "me.conversations.edges.node.to.name": (v16/*: any*/), "me.conversations.edges.node.unread": (v21/*: any*/), "me.conversations.pageInfo": { "enumValues": null, "nullable": false, "plural": false, "type": "PageInfo" }, "me.conversations.pageInfo.endCursor": (v18/*: any*/), "me.conversations.pageInfo.hasNextPage": { "enumValues": null, "nullable": false, "plural": false, "type": "Boolean" }, "me.conversations.totalUnreadCount": (v22/*: any*/), "me.id": (v17/*: any*/), "me.identityVerified": (v21/*: any*/), "me.myBids": { "enumValues": null, "nullable": true, "plural": false, "type": "MyBids" }, "me.myBids.active": (v23/*: any*/), "me.myBids.active.sale": (v24/*: any*/), "me.myBids.active.sale.coverImage": (v19/*: any*/), "me.myBids.active.sale.coverImage.url": (v18/*: any*/), "me.myBids.active.sale.endAt": (v18/*: any*/), "me.myBids.active.sale.href": (v18/*: any*/), "me.myBids.active.sale.id": (v17/*: any*/), "me.myBids.active.sale.internalID": (v17/*: any*/), "me.myBids.active.sale.liveStartAt": (v18/*: any*/), "me.myBids.active.sale.name": (v18/*: any*/), "me.myBids.active.sale.partner": (v20/*: any*/), "me.myBids.active.sale.partner.id": (v17/*: any*/), "me.myBids.active.sale.partner.name": (v18/*: any*/), "me.myBids.active.sale.registrationStatus": (v25/*: any*/), "me.myBids.active.sale.registrationStatus.id": (v17/*: any*/), "me.myBids.active.sale.registrationStatus.qualifiedForBidding": (v21/*: any*/), "me.myBids.active.sale.requireIdentityVerification": (v21/*: any*/), "me.myBids.active.sale.slug": (v17/*: any*/), "me.myBids.active.saleArtworks": (v26/*: any*/), "me.myBids.active.saleArtworks.artwork": (v27/*: any*/), "me.myBids.active.saleArtworks.artwork.artistNames": (v18/*: any*/), "me.myBids.active.saleArtworks.artwork.href": (v18/*: any*/), "me.myBids.active.saleArtworks.artwork.id": (v17/*: any*/), "me.myBids.active.saleArtworks.artwork.image": (v19/*: any*/), "me.myBids.active.saleArtworks.artwork.image.url": (v18/*: any*/), "me.myBids.active.saleArtworks.artwork.internalID": (v17/*: any*/), "me.myBids.active.saleArtworks.artwork.slug": (v17/*: any*/), "me.myBids.active.saleArtworks.currentBid": (v28/*: any*/), "me.myBids.active.saleArtworks.currentBid.display": (v18/*: any*/), "me.myBids.active.saleArtworks.estimate": (v18/*: any*/), "me.myBids.active.saleArtworks.id": (v17/*: any*/), "me.myBids.active.saleArtworks.internalID": (v17/*: any*/), "me.myBids.active.saleArtworks.isHighestBidder": (v21/*: any*/), "me.myBids.active.saleArtworks.isWatching": (v21/*: any*/), "me.myBids.active.saleArtworks.lotLabel": (v18/*: any*/), "me.myBids.active.saleArtworks.lotState": (v29/*: any*/), "me.myBids.active.saleArtworks.lotState.bidCount": (v22/*: any*/), "me.myBids.active.saleArtworks.lotState.reserveStatus": (v18/*: any*/), "me.myBids.active.saleArtworks.lotState.sellingPrice": (v30/*: any*/), "me.myBids.active.saleArtworks.lotState.sellingPrice.display": (v18/*: any*/), "me.myBids.active.saleArtworks.lotState.soldStatus": (v18/*: any*/), "me.myBids.active.saleArtworks.sale": (v24/*: any*/), "me.myBids.active.saleArtworks.sale.endAt": (v18/*: any*/), "me.myBids.active.saleArtworks.sale.id": (v17/*: any*/), "me.myBids.active.saleArtworks.sale.liveStartAt": (v18/*: any*/), "me.myBids.active.saleArtworks.sale.status": (v18/*: any*/), "me.myBids.closed": (v23/*: any*/), "me.myBids.closed.sale": (v24/*: any*/), "me.myBids.closed.sale.coverImage": (v19/*: any*/), "me.myBids.closed.sale.coverImage.url": (v18/*: any*/), "me.myBids.closed.sale.endAt": (v18/*: any*/), "me.myBids.closed.sale.href": (v18/*: any*/), "me.myBids.closed.sale.id": (v17/*: any*/), "me.myBids.closed.sale.internalID": (v17/*: any*/), "me.myBids.closed.sale.liveStartAt": (v18/*: any*/), "me.myBids.closed.sale.name": (v18/*: any*/), "me.myBids.closed.sale.partner": (v20/*: any*/), "me.myBids.closed.sale.partner.id": (v17/*: any*/), "me.myBids.closed.sale.partner.name": (v18/*: any*/), "me.myBids.closed.sale.registrationStatus": (v25/*: any*/), "me.myBids.closed.sale.registrationStatus.id": (v17/*: any*/), "me.myBids.closed.sale.registrationStatus.qualifiedForBidding": (v21/*: any*/), "me.myBids.closed.sale.requireIdentityVerification": (v21/*: any*/), "me.myBids.closed.sale.slug": (v17/*: any*/), "me.myBids.closed.saleArtworks": (v26/*: any*/), "me.myBids.closed.saleArtworks.artwork": (v27/*: any*/), "me.myBids.closed.saleArtworks.artwork.artistNames": (v18/*: any*/), "me.myBids.closed.saleArtworks.artwork.href": (v18/*: any*/), "me.myBids.closed.saleArtworks.artwork.id": (v17/*: any*/), "me.myBids.closed.saleArtworks.artwork.image": (v19/*: any*/), "me.myBids.closed.saleArtworks.artwork.image.url": (v18/*: any*/), "me.myBids.closed.saleArtworks.artwork.internalID": (v17/*: any*/), "me.myBids.closed.saleArtworks.artwork.slug": (v17/*: any*/), "me.myBids.closed.saleArtworks.currentBid": (v28/*: any*/), "me.myBids.closed.saleArtworks.currentBid.display": (v18/*: any*/), "me.myBids.closed.saleArtworks.estimate": (v18/*: any*/), "me.myBids.closed.saleArtworks.id": (v17/*: any*/), "me.myBids.closed.saleArtworks.internalID": (v17/*: any*/), "me.myBids.closed.saleArtworks.isHighestBidder": (v21/*: any*/), "me.myBids.closed.saleArtworks.isWatching": (v21/*: any*/), "me.myBids.closed.saleArtworks.lotLabel": (v18/*: any*/), "me.myBids.closed.saleArtworks.lotState": (v29/*: any*/), "me.myBids.closed.saleArtworks.lotState.bidCount": (v22/*: any*/), "me.myBids.closed.saleArtworks.lotState.reserveStatus": (v18/*: any*/), "me.myBids.closed.saleArtworks.lotState.sellingPrice": (v30/*: any*/), "me.myBids.closed.saleArtworks.lotState.sellingPrice.display": (v18/*: any*/), "me.myBids.closed.saleArtworks.lotState.soldStatus": (v18/*: any*/), "me.myBids.closed.saleArtworks.sale": (v24/*: any*/), "me.myBids.closed.saleArtworks.sale.endAt": (v18/*: any*/), "me.myBids.closed.saleArtworks.sale.id": (v17/*: any*/), "me.myBids.closed.saleArtworks.sale.liveStartAt": (v18/*: any*/), "me.myBids.closed.saleArtworks.sale.status": (v18/*: any*/), "me.pendingIdentityVerification": { "enumValues": null, "nullable": true, "plural": false, "type": "IdentityVerification" }, "me.pendingIdentityVerification.id": (v17/*: any*/), "me.pendingIdentityVerification.internalID": (v17/*: any*/) } }, "name": "InboxTestsQuery", "operationKind": "query", "text": null } }; })(); (node as any).hash = '0664d6807c9c2d53864ad6240891c43f'; export default node;
the_stack
import { MockRelayClass } from "../__mocks__/relay"; import { MOCK_ADDERESS, MOCK_SIGNED_TX, MOCK_TX, MOCK_TYPED_DATA, } from "../fixtures/provider"; import { ScopedLocalStorage } from "../lib/ScopedLocalStorage"; import { LOCAL_STORAGE_ADDRESSES_KEY } from "../relay/WalletSDKRelayAbstract"; import { WalletSDKRelayEventManager } from "../relay/WalletSDKRelayEventManager"; import { Web3Method } from "../relay/Web3Method"; import { CoinbaseWalletProvider, CoinbaseWalletProviderOptions, } from "./CoinbaseWalletProvider"; const storage = new ScopedLocalStorage("CoinbaseWalletProvider"); const setupCoinbaseWalletProvider = ( options: Partial<CoinbaseWalletProviderOptions> = {}, ) => { return new CoinbaseWalletProvider({ chainId: 1, jsonRpcUrl: "http://test.ethnode.com", qrUrl: null, overrideIsCoinbaseWallet: true, overrideIsCoinbaseBrowser: false, overrideIsMetaMask: false, relayEventManager: new WalletSDKRelayEventManager(), relayProvider: async () => Promise.resolve(new MockRelayClass()), storage, ...options, }); }; const mockSuccessfulFetchResponse = () => { global.fetch = jest.fn().mockImplementationOnce(() => { return new Promise(resolve => { resolve({ ok: true, json: () => ({ jsonrpc: "2.0", id: 1, method: "eth_blockNumber", result: "0x1", }), }); }); }); }; describe("CoinbaseWalletProvider", () => { afterEach(() => { storage.clear(); }); it("instantiates", () => { const provider = setupCoinbaseWalletProvider(); expect(provider).toBeInstanceOf(CoinbaseWalletProvider); }); it("gives provider info", () => { const provider = setupCoinbaseWalletProvider(); expect(provider.selectedAddress).toBe(undefined); expect(provider.networkVersion).toBe("1"); expect(provider.chainId).toBe("0x1"); expect(provider.isWalletLink).toBe(true); expect(provider.isCoinbaseWallet).toBe(true); expect(provider.isCoinbaseBrowser).toBe(false); expect(provider.isMetaMask).toBe(false); expect(provider.host).toBe("http://test.ethnode.com"); expect(provider.connected).toBe(true); expect(provider.isConnected()).toBe(true); }); it("handles setting provider info", () => { const url = "https://new.jsonRpcUrl.com"; const provider = setupCoinbaseWalletProvider(); provider.setProviderInfo(url); expect(provider.host).toBe(url); }); it("handles setting the app info", () => { const provider = setupCoinbaseWalletProvider(); provider.setAppInfo("Test Dapp", null); expect(provider.host).toBe("http://test.ethnode.com"); }); it("handles subscriptions", () => { const provider = setupCoinbaseWalletProvider(); expect(provider.supportsSubscriptions()).toBe(false); expect(() => { provider.subscribe(); }).toThrowError("Subscriptions are not supported"); expect(() => { provider.unsubscribe(); }).toThrowError("Subscriptions are not supported"); }); it("handles enabling the provider successfully", async () => { const provider = setupCoinbaseWalletProvider(); const response = await provider.enable(); expect(response[0]).toBe(MOCK_ADDERESS.toLowerCase()); }); it("handles close", async () => { const spy = jest.spyOn(MockRelayClass.prototype, "resetAndReload"); const relay = new MockRelayClass(); const provider = setupCoinbaseWalletProvider({ relayProvider: async () => Promise.resolve(relay), }); await provider.close(); expect(spy).toHaveBeenCalled(); }); it("handles disconnect", () => { const provider = setupCoinbaseWalletProvider(); expect(provider.disconnect()).toBe(true); }); it("handles making generic requests successfully", async () => { const provider = setupCoinbaseWalletProvider(); const data = { from: MOCK_ADDERESS, to: MOCK_ADDERESS, }; const action = "cbSignAndSubmit"; const response = await provider.genericRequest(data, action); expect(response).toBe("Success"); }); it("handles making a send with a string param", async () => { const provider = setupCoinbaseWalletProvider(); const response = await provider.send("eth_requestAccounts"); expect(response[0]).toBe(MOCK_ADDERESS.toLowerCase()); }); it("handles making a rpc request", async () => { const provider = setupCoinbaseWalletProvider(); const response = await provider.request<string[]>({ method: "eth_requestAccounts", }); expect(response[0]).toBe(MOCK_ADDERESS.toLowerCase()); }); it("handles making a send with a rpc request", async () => { const mockCallback = jest.fn(); const provider = setupCoinbaseWalletProvider(); await provider.send( { jsonrpc: "2.0", method: "eth_requestAccounts", params: [], id: 1, }, mockCallback, ); expect(mockCallback).toHaveBeenCalledWith( null, expect.objectContaining({ result: [MOCK_ADDERESS.toLowerCase()], }), ); }); it("handles making a send with a string param", async () => { const provider = setupCoinbaseWalletProvider(); const mockCallback = jest.fn(); await provider.sendAsync( { jsonrpc: "2.0", method: "eth_requestAccounts", params: [], id: 1, }, mockCallback, ); expect(mockCallback).toHaveBeenCalledWith( null, expect.objectContaining({ result: [MOCK_ADDERESS.toLowerCase()], }), ); }); it("handles generic requests successfully", async () => { const relay = new MockRelayClass(); jest.spyOn(relay, "genericRequest").mockReturnValue({ cancel: () => {}, promise: Promise.resolve({ method: Web3Method.generic, result: "Success", }), }); const provider = setupCoinbaseWalletProvider({ relayProvider: async () => { return Promise.resolve(relay); }, }); const data = { from: MOCK_ADDERESS, to: MOCK_ADDERESS, }; const action = "cbSignAndSubmit"; const result = await provider.genericRequest(data, action); expect(result).toBe("Success"); }); it("handles error responses with generic requests", async () => { const relay = new MockRelayClass(); jest.spyOn(relay, "genericRequest").mockReturnValue({ cancel: () => {}, // @ts-expect-error result should be a string promise: Promise.resolve({ method: Web3Method.generic, result: { foo: "bar" }, }), }); const provider = setupCoinbaseWalletProvider({ relayProvider: async () => { return Promise.resolve(relay); }, }); const data = { from: MOCK_ADDERESS, to: MOCK_ADDERESS, }; const action = "cbSignAndSubmit"; await expect(() => provider.genericRequest(data, action), ).rejects.toThrowError("result was not a string"); }); it("handles user rejecting enable call", async () => { const relay = new MockRelayClass(); jest.spyOn(relay, "requestEthereumAccounts").mockReturnValue({ cancel: () => {}, promise: Promise.reject(new Error("rejected")), }); const provider = setupCoinbaseWalletProvider({ storage: new ScopedLocalStorage("reject-info"), relayProvider: async () => { return Promise.resolve(relay); }, }); await expect(() => provider.enable()).rejects.toThrowError( "User denied account authorization", ); }); it("handles user rejecting enable call with unknown error", async () => { const relay = new MockRelayClass(); jest.spyOn(relay, "requestEthereumAccounts").mockReturnValue({ cancel: () => {}, promise: Promise.reject(new Error("Unknown")), }); const provider = setupCoinbaseWalletProvider({ storage: new ScopedLocalStorage("unknown-error"), relayProvider: async () => { return Promise.resolve(relay); }, }); await expect(() => provider.enable()).rejects.toThrowError("Unknown"); }); it("returns the users address on future eth_requestAccounts calls", async () => { const provider = setupCoinbaseWalletProvider(); // Set the account on the first request const response1 = await provider.request<string[]>({ method: "eth_requestAccounts", }); expect(response1[0]).toBe(MOCK_ADDERESS.toLowerCase()); // @ts-expect-error accessing private value for test expect(provider._addresses).toEqual([MOCK_ADDERESS.toLowerCase()]); // Set the account on the first request const response2 = await provider.request<string[]>({ method: "eth_requestAccounts", }); expect(response2[0]).toBe(MOCK_ADDERESS.toLowerCase()); }); it("gets the users address from storage on init", async () => { const localStorage = new ScopedLocalStorage("test"); localStorage.setItem( LOCAL_STORAGE_ADDRESSES_KEY, MOCK_ADDERESS.toLowerCase(), ); const provider = setupCoinbaseWalletProvider({ storage: localStorage, }); // @ts-expect-error accessing private value for test expect(provider._addresses).toEqual([MOCK_ADDERESS.toLowerCase()]); // Set the account on the first request const response = await provider.request<string[]>({ method: "eth_requestAccounts", }); expect(response[0]).toBe(MOCK_ADDERESS.toLowerCase()); }); it("handles scanning QR code with bad response", async () => { const relay = new MockRelayClass(); jest.spyOn(relay, "scanQRCode").mockReturnValue({ cancel: () => {}, // @ts-expect-error result should be a string promise: Promise.resolve({ method: Web3Method.scanQRCode, result: { foo: "bar" }, }), }); const provider = setupCoinbaseWalletProvider({ relayProvider: async () => Promise.resolve(relay), }); await expect(() => provider.scanQRCode(new RegExp("cbwallet://cool")), ).rejects.toThrowError("result was not a string"); }); it("handles scanning QR code", async () => { const relay = new MockRelayClass(); jest.spyOn(relay, "scanQRCode").mockReturnValue({ cancel: () => {}, promise: Promise.resolve({ method: Web3Method.scanQRCode, result: "cbwallet://result", }), }); const provider = setupCoinbaseWalletProvider({ relayProvider: async () => Promise.resolve(relay), }); const result = await provider.scanQRCode(new RegExp("cbwallet://cool")); expect(result).toBe("cbwallet://result"); }); describe("RPC Methods", () => { let provider: CoinbaseWalletProvider | null = null; let localStorage: ScopedLocalStorage; beforeEach(() => { localStorage = new ScopedLocalStorage("test"); localStorage.setItem( LOCAL_STORAGE_ADDRESSES_KEY, MOCK_ADDERESS.toLowerCase(), ); provider = setupCoinbaseWalletProvider({ storage: localStorage, }); }); afterEach(() => { provider = null; localStorage?.clear(); }); test("eth_accounts", async () => { const response = await provider?.request({ method: "eth_accounts", }); expect(response).toEqual([MOCK_ADDERESS.toLowerCase()]); }); test("eth_coinbase", async () => { const response = await provider?.request({ method: "eth_coinbase", }); expect(response).toBe(MOCK_ADDERESS.toLowerCase()); }); test("net_version", async () => { const response = await provider?.request({ method: "net_version", }); expect(response).toEqual("1"); }); test("eth_chainId", async () => { const response = await provider?.request<string>({ method: "eth_chainId", }); expect(response).toEqual("0x1"); }); test("eth_uninstallFilter", async () => { const response = await provider?.request<boolean>({ method: "eth_uninstallFilter", params: ["0xb"], }); expect(response).toBe(true); }); test("eth_requestAccounts", async () => { const response = await provider?.request({ method: "eth_requestAccounts", }); expect(response).toEqual([MOCK_ADDERESS.toLowerCase()]); }); test("eth_sign success", async () => { const response = await provider?.request({ method: "eth_sign", params: [MOCK_ADDERESS.toLowerCase(), "Super safe message"], }); expect(response).toBe("0x"); }); test("eth_sign fail bad address", async () => { await expect(() => provider?.request({ method: "eth_sign", params: ["0x123456789abcdef", "Super safe message"], }), ).rejects.toThrowError("Invalid Ethereum address: 0x123456789abcdef"); }); test("eth_sign fail bad message format", async () => { await expect(() => provider?.request({ method: "eth_sign", params: [MOCK_ADDERESS.toLowerCase(), 123456789], }), ).rejects.toThrowError("Not binary data: 123456789"); }); test("eth_ecRecover", async () => { const response = await provider?.request({ method: "eth_ecRecover", params: ["Super safe message", "0x"], }); expect(response).toBe(MOCK_ADDERESS); }); test("personal_sign success", async () => { const response = await provider?.request({ method: "personal_sign", params: ["My secret message", MOCK_ADDERESS.toLowerCase()], }); expect(response).toBe("0x"); }); test("personal_sign fail", async () => { await expect(() => provider?.request({ method: "personal_sign", params: ["0x123456789abcdef", "Super safe message"], }), ).rejects.toThrowError("Invalid Ethereum address: Super safe message"); }); test("personal_ecRecover", async () => { const response = await provider?.request({ method: "personal_ecRecover", params: ["Super safe message", "0x"], }); expect(response).toBe(MOCK_ADDERESS); }); test("eth_signTransaction", async () => { const response = await provider?.request({ method: "eth_signTransaction", params: [ { from: MOCK_ADDERESS, to: MOCK_ADDERESS, gasPrice: "21000", maxFeePerGas: "10000000000", maxPriorityFeePerGas: "10000000000", gas: "10000000000", value: "10000000000", data: "0xA0", nonce: 1, }, ], }); expect(response).toBe(MOCK_TX); }); test("eth_sendRawTransaction", async () => { const response = await provider?.request({ method: "eth_sendRawTransaction", params: [MOCK_SIGNED_TX], }); expect(response).toBe(MOCK_TX); }); test("eth_sendTransaction", async () => { const response = await provider?.request({ method: "eth_sendTransaction", params: [ { from: MOCK_ADDERESS, to: MOCK_ADDERESS, gasPrice: "21000", maxFeePerGas: "10000000000", maxPriorityFeePerGas: "10000000000", gas: "10000000000", value: "10000000000", data: "0xA0", nonce: 1, }, ], }); expect(response).toBe(MOCK_TX); }); test.skip("eth_signTypedData_v1", async () => { const response = await provider?.request({ method: "eth_signTypedData_v1", params: [[MOCK_TYPED_DATA], MOCK_ADDERESS], }); expect(response).toBe("0x"); }); test("eth_signTypedData_v2", async () => { await expect(() => provider?.request({ method: "eth_signTypedData_v2", params: [], }), ).rejects.toThrowError( "The requested method is not supported by this Ethereum provider", ); }); test("eth_signTypedData_v3", async () => { const response = await provider?.request({ method: "eth_signTypedData_v3", params: [MOCK_ADDERESS, MOCK_TYPED_DATA], }); expect(response).toBe("0x"); }); test("eth_signTypedData_v4", async () => { const response = await provider?.request({ method: "eth_signTypedData_v4", params: [MOCK_ADDERESS, MOCK_TYPED_DATA], }); expect(response).toBe("0x"); }); test("eth_signTypedData", async () => { const response = await provider?.request({ method: "eth_signTypedData", params: [MOCK_ADDERESS, MOCK_TYPED_DATA], }); expect(response).toBe("0x"); }); test("wallet_addEthereumChain success", async () => { const response = await provider?.request({ method: "wallet_addEthereumChain", params: [ { chainId: "0x0539", chainName: "Leet Chain", nativeCurrency: "LEET", rpcUrls: ["https://node.ethchain.com"], blockExplorerUrls: ["https://leetscan.com"], iconUrls: ["https://leetchain.com/icon.svg"], }, ], }); expect(response).toBeNull(); }); test("wallet_addEthereumChain missing RPC urls", async () => { const response = await provider?.request({ method: "wallet_addEthereumChain", params: [ { rpcUrls: [], }, ], }); expect(response).toBeUndefined(); }); test("wallet_addEthereumChain missing chainName", async () => { await expect(() => { return provider?.request({ method: "wallet_addEthereumChain", params: [{}], }); }).rejects.toThrowError( '"code" must be an integer such that: 1000 <= code <= 4999', ); }); test("wallet_addEthereumChain native currency", async () => { await expect(() => { return provider?.request({ method: "wallet_addEthereumChain", params: [ { chainId: "0x0539", chainName: "Leet Chain", }, ], }); }).rejects.toThrowError( '"code" must be an integer such that: 1000 <= code <= 4999', ); }); test("wallet_switchEthereumChain", async () => { const response = await provider?.request({ method: "wallet_switchEthereumChain", params: [ { chainId: "0x0539", }, ], }); expect(response).toBeNull(); }); test("wallet_switchEthereumChain w/ error code", async () => { const relay = new MockRelayClass(); jest.spyOn(relay, "switchEthereumChain").mockReturnValue({ cancel: () => {}, promise: Promise.resolve({ method: Web3Method.switchEthereumChain, errorCode: 4092, }), }); const localProvider = setupCoinbaseWalletProvider({ relayProvider: () => Promise.resolve(relay), }); await expect(() => { return localProvider.request({ method: "wallet_switchEthereumChain", params: [ { chainId: "0x0539", }, ], }); }).rejects.toThrowError(); }); test("wallet_watchAsset", async () => { const response = await provider?.request({ method: "wallet_watchAsset", params: [ { type: "ERC20", options: { address: "0xAdD4e55", }, }, ], }); expect(response).toBe(true); }); test("wallet_watchAsset w/o valid asset type", async () => { await expect(() => provider?.request({ method: "wallet_watchAsset", params: [{}], }), ).rejects.toThrowError("Type is required"); }); test("wallet_watchAsset w/o valid asset type", async () => { await expect(() => provider?.request({ method: "wallet_watchAsset", params: [ { type: "ERC721", }, ], }), ).rejects.toThrowError("Asset of type 'ERC721' is not supported"); }); test("wallet_watchAsset", async () => { await expect(() => provider?.request({ method: "wallet_watchAsset", params: [ { type: "ERC20", }, ], }), ).rejects.toThrowError("Options are required"); }); test("wallet_watchAsset", async () => { await expect(() => provider?.request({ method: "wallet_watchAsset", params: [ { type: "ERC20", options: {}, }, ], }), ).rejects.toThrowError("Address is required"); }); test("eth_newFilter", async () => { mockSuccessfulFetchResponse(); const response = await provider?.request({ method: "eth_newFilter", params: [ { fromBlock: "0xa", toBlock: "0xc", address: MOCK_ADDERESS, }, ], }); expect(response).toBe("0x2"); }); test("eth_newBlockFilter", async () => { mockSuccessfulFetchResponse(); const response = await provider?.request({ method: "eth_newBlockFilter", }); expect(response).toBe("0x2"); }); test("eth_newPendingTransactionFilter", async () => { mockSuccessfulFetchResponse(); const response = await provider?.request({ method: "eth_newPendingTransactionFilter", }); expect(response).toBe("0x2"); }); test("eth_getFilterChanges", async () => { mockSuccessfulFetchResponse(); await provider?.request({ method: "eth_newFilter", params: [ { fromBlock: "0xa", toBlock: "0xc", address: MOCK_ADDERESS, }, ], }); mockSuccessfulFetchResponse(); const response = await provider?.request({ method: "eth_getFilterChanges", params: ["0x2"], }); expect(response).toEqual([]); // expect empty result }); test("eth_getFilterLogs", async () => { mockSuccessfulFetchResponse(); await provider?.request({ method: "eth_newFilter", params: [ { fromBlock: "0xa", toBlock: "0xc", address: MOCK_ADDERESS, }, ], }); mockSuccessfulFetchResponse(); const response = await provider?.request({ method: "eth_getFilterLogs", params: ["0x2"], }); expect(response).toEqual("0x1"); }); }); });
the_stack
import { setCookie } from "./common-defer"; import { SkinViewer, createOrbitControls } from "skinview3d"; import tippy from "tippy.js"; import("./elements/inventory-view"); const favoriteElement = document.querySelector(".favorite") as HTMLButtonElement; if ("share" in navigator) { // eslint-disable-next-line deprecation/deprecation const platform = navigator.platform ?? navigator.userAgentData?.platform ?? "unknown"; const shareIcon = platform.match(/(Mac|iPhone|iPod|iPad)/i) ? /*mdiExportVariant*/ "M12,1L8,5H11V14H13V5H16M18,23H6C4.89,23 4,22.1 4,21V9A2,2 0 0,1 6,7H9V9H6V21H18V9H15V7H18A2,2 0 0,1 20,9V21A2,2 0 0,1 18,23Z" : /*mdiShareVariant*/ "M18,16.08C17.24,16.08 16.56,16.38 16.04,16.85L8.91,12.7C8.96,12.47 9,12.24 9,12C9,11.76 8.96,11.53 8.91,11.3L15.96,7.19C16.5,7.69 17.21,8 18,8A3,3 0 0,0 21,5A3,3 0 0,0 18,2A3,3 0 0,0 15,5C15,5.24 15.04,5.47 15.09,5.7L8.04,9.81C7.5,9.31 6.79,9 6,9A3,3 0 0,0 3,12A3,3 0 0,0 6,15C6.79,15 7.5,14.69 8.04,14.19L15.16,18.34C15.11,18.55 15.08,18.77 15.08,19C15.08,20.61 16.39,21.91 18,21.91C19.61,21.91 20.92,20.61 20.92,19A2.92,2.92 0 0,0 18,16.08Z"; favoriteElement.insertAdjacentHTML( "afterend", /*html*/ ` <button class="additional-player-stat svg-icon"> <svg viewBox="0 0 24 24"> <title>share</title> <path fill="white" d="${shareIcon}" /> </svg> </button> ` ); favoriteElement.nextElementSibling?.addEventListener("click", () => { navigator.share({ text: `Check out ${calculated.display_name} on SkyCrypt`, url: location.href.split("#")[0], }); }); } function getCookie(c_name: string) { if (document.cookie.length > 0) { let c_start = document.cookie.indexOf(c_name + "="); if (c_start != -1) { c_start = c_start + c_name.length + 1; let c_end = document.cookie.indexOf(";", c_start); if (c_end == -1) { c_end = document.cookie.length; } return unescape(document.cookie.substring(c_start, c_end)); } } return ""; } tippy("*[data-tippy-content]:not(.interactive-tooltip)", { trigger: "mouseenter click", }); const playerModel = document.getElementById("player_model") as HTMLElement; let skinViewer: SkinViewer | undefined; if (calculated.skin_data) { skinViewer = new SkinViewer({ width: playerModel.offsetWidth, height: playerModel.offsetHeight, model: calculated.skin_data.model, skin: "/texture/" + calculated.skin_data.skinurl.split("/").pop(), cape: calculated.skin_data.capeurl != undefined ? "/texture/" + calculated.skin_data.capeurl.split("/").pop() : "/cape/" + calculated.display_name, }); playerModel.appendChild(skinViewer.canvas); skinViewer.camera.position.set(-18, -3, 58); const controls = createOrbitControls(skinViewer); skinViewer.canvas.removeAttribute("tabindex"); controls.enableZoom = false; controls.enablePan = false; /** * the average Z rotation of the arms */ const basicArmRotationZ = Math.PI * 0.02; /** * the average X rotation of the cape */ const basicCapeRotationX = Math.PI * 0.06; if (!window.matchMedia("(prefers-reduced-motion: reduce)").matches) { skinViewer.animations.add((player, time) => { // Multiply by animation's natural speed time *= 2; // Arm swing const armRotation = Math.cos(time) * 0.03 + basicArmRotationZ; player.skin.leftArm.rotation.z = armRotation; player.skin.rightArm.rotation.z = armRotation * -1; // Cape wave player.cape.rotation.x = Math.sin(time) * 0.01 + basicCapeRotationX; }); } else { skinViewer.playerObject.skin.leftArm.rotation.z = basicArmRotationZ; skinViewer.playerObject.skin.rightArm.rotation.z = basicArmRotationZ * -1; skinViewer.playerObject.cape.rotation.x = basicCapeRotationX; } } tippy(".interactive-tooltip", { trigger: "mouseenter click", interactive: true, appendTo: () => document.body, onTrigger(instance: unknown, event: Event) { if (event.type == "click") { dimmer.classList.add("show-dimmer"); } }, onHide() { dimmer.classList.remove("show-dimmer"); }, }); export const allItems = new Map( [ items.armor, items.inventory, items.enderchest, items.talisman_bag, items.fishing_bag, items.quiver, items.potion_bag, items.personal_vault, items.wardrobe_inventory, items.storage, items.hotm, ] .flat() .flatMap((item) => { if ("containsItems" in item) { return [item, ...item.containsItems]; } else { return item; } }) .map((item) => [item.itemId, item]) ); const dimmer = document.querySelector("#dimmer") as HTMLElement; const url = new URL(location.href); url.searchParams.delete("__cf_chl_jschl_tk__"); url.searchParams.delete("__cf_chl_captcha_tk__"); if (calculated.profile.cute_name == "Deleted") { url.pathname = `/stats/${calculated.display_name}/${calculated.profile.profile_id}`; } else { url.pathname = `/stats/${calculated.display_name}/${calculated.profile.cute_name}`; } history.replaceState({}, document.title, url.href); export function isEnchanted(item: Item): boolean { // heads if ([397].includes(item.id)) { return false; } // enchanted book, bottle o' enchanting, nether star if ([403, 384, 399].includes(item.id)) { return true; } //potions with actual effects (not water bottles) if (item.id === 373 && item.Damage !== 0) { return true; } if ("tag" in item && Array.isArray(item.tag.ench)) { return true; } if (item.glowing) { return true; } return false; } type colorCode = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "0" | "a" | "b" | "c" | "d" | "e" | "f"; type formatCode = "k" | "l" | "m" | "n" | "o"; function renderLore(text: string) { let output = ""; let color: colorCode | null = null; const formats = new Set<formatCode>(); for (let part of text.match(/(§[0-9a-fk-or])*[^§]*/g) ?? []) { while (part.charAt(0) === "§") { const code = part.charAt(1); if (/[0-9a-f]/.test(code)) { color = code as colorCode; } else if (/[k-o]/.test(code)) { formats.add(code as formatCode); } else if (code === "r") { color = null; formats.clear(); } part = part.substring(2); } if (part.length === 0) continue; output += "<span"; if (color !== null) { output += ` style='color: var(--§${color});'`; } if (formats.size > 0) { output += ` class='${Array.from(formats, (x) => "§" + x).join(" ")}'`; } output += `>${part}</span>`; } const matchingEnchants = constants.special_enchants.filter((a) => output.includes(a)); for (const enchantment of matchingEnchants) { if (enchantment == "Power 6" || (enchantment == "Power 7" && text.startsWith("§8Breaking"))) { continue; } output = output.replace(enchantment, `<span style='color: var(--§6)'>${enchantment}</span>`); } return output; } export function isSlotItem(item: ItemSlot): item is Item { return "id" in item; } function switchInventory(type: string, backpack?: Backpack) { backpack; const inventoryView = document.querySelector<HTMLElement>(".stat-inventory inventory-view"); if (!inventoryView) { return; } inventoryView.setAttribute("inventory-type", type); if (type === "backpack" && backpack) { inventoryView.setAttribute("backpack-id", backpack.itemId); } setTimeout(() => { const rect = (document.querySelector("#inventory_container") as HTMLElement).getBoundingClientRect(); if (rect.top > 100 && rect.bottom > window.innerHeight) { let top; if (rect.height > window.innerHeight - 100) { top = rect.top - 100; } else { top = rect.bottom - window.innerHeight; } window.scrollBy({ top, behavior: "smooth" }); scrollMemory.isSmoothScrolling = true; } }); } export function isItem(item: ItemSlot | DisplayItem): item is Item { return "Count" in item && "Damage" in item && "id" in item; } export function isBackpack(item: DisplayItem): item is Backpack { return "containsItems" in item; } export function showBackpack(item: Backpack): void { const activeInventory = document.querySelector(".inventory-tab.active-inventory"); if (activeInventory) { activeInventory.classList.remove("active-inventory"); } switchInventory("backpack", item); closeLore(); } function fillLore(element: HTMLElement) { let item: DisplayItem | Item | Pet | undefined = undefined; if (element.hasAttribute("data-item-id")) { const itemId = element.getAttribute("data-item-id") as string; item = allItems.get(itemId) as Item; } else if (element.hasAttribute("data-pet-index")) { item = calculated.pets[parseInt(element.getAttribute("data-pet-index") as string)]; } else if (element.hasAttribute("data-missing-pet-index")) { item = calculated.missingPets[parseInt(element.getAttribute("data-missing-pet-index") as string)]; } else if (element.hasAttribute("data-missing-talisman-index")) { item = calculated.missingTalismans.missing[parseInt(element.getAttribute("data-missing-talisman-index") as string)]; } else if (element.hasAttribute("data-upgrade-talisman-index")) { item = calculated.missingTalismans.upgrades[parseInt(element.getAttribute("data-upgrade-talisman-index") as string)]; } if (item == undefined) { return; } itemName.className = `item-name piece-${item.rarity || "common"}-bg nice-colors-dark`; itemNameContent.innerHTML = item.display_name_print || item.display_name || "null"; if (element.hasAttribute("data-pet-index")) { itemNameContent.innerHTML = `[Lvl ${(item as Pet).level.level}] ${item.display_name_print || item.display_name}`; } if (item.texture_path) { itemIcon.style.backgroundImage = 'url("' + item.texture_path + '")'; itemIcon.className = "stats-piece-icon item-icon custom-icon"; } else if ("id" in item) { itemIcon.removeAttribute("style"); itemIcon.classList.remove("custom-icon"); const idClass = `icon-${item.id}_${item.Damage}` + " " + (item.Damage != 0 ? `icon-${item.id}_0` : ""); itemIcon.className = "stats-piece-icon item-icon " + idClass; } else { throw new Error("item mush have either an id and a damage or a texture_path"); } if ("id" in item && isEnchanted(item)) { itemIcon.classList.add("is-enchanted"); } if ("lore" in item) { itemLore.innerHTML = item.lore; } else if ("tag" in item && Array.isArray(item.tag.display?.Lore)) { itemLore.innerHTML = item.tag.display.Lore.map( (line: string) => '<span class="lore-row">' + renderLore(line) + "</span>" ).join(""); } else { itemLore.innerHTML = ""; } if ("texture_pack" in item && item.texture_pack != undefined) { const packContent = document.createElement("a"); packContent.setAttribute("href", item.texture_pack.url); packContent.setAttribute("target", "_blank"); packContent.setAttribute("rel", "noreferrer"); packContent.classList.add("pack-credit"); const packIcon = document.createElement("img"); packIcon.setAttribute("src", item.texture_pack.base_path + "/pack.png"); packIcon.classList.add("icon"); const packName = document.createElement("div"); packName.classList.add("name"); packName.innerHTML = item.texture_pack.name; const packAuthor = document.createElement("div"); packAuthor.classList.add("author"); packAuthor.innerHTML = `by <span>${item.texture_pack.author}</span>`; packContent.appendChild(packIcon); packContent.appendChild(packName); packContent.appendChild(packAuthor); itemLore.appendChild(packContent); } if (isBackpack(item)) { backpackContents.classList.add("contains-backpack"); backpackContents.setAttribute("backpack-id", item.itemId); backpackContents.setAttribute("inventory-type", "backpack"); } else { backpackContents.classList.remove("contains-backpack"); } } function showLore(element: HTMLElement, _resize?: boolean) { statsContent.classList.add("sticky-stats"); element.classList.add("sticky-stats"); dimmer.classList.add("show-dimmer"); if (_resize != false) { resize(); } } function closeLore() { const shownLore = document.querySelector<HTMLElement>("#stats_content.show-stats, #stats_content.sticky-stats"); if (shownLore != null) { dimmer.classList.remove("show-dimmer"); const stickyStatsPiece = document.querySelector<HTMLElement>(".rich-item.sticky-stats"); if (stickyStatsPiece != null) { stickyStatsPiece.blur(); stickyStatsPiece.classList.remove("sticky-stats"); } statsContent.classList.remove("sticky-stats", "show-stats"); } } let playerModelIsMobile = false; const navBar = document.querySelector("#nav_bar") as HTMLElement; const navBarLinks = navBar.querySelectorAll<HTMLAnchorElement>(".nav-item"); let navBarHeight: number; function resize() { if (window.innerWidth <= 1590 && !playerModelIsMobile) { playerModelIsMobile = true; document.getElementById("skin_display_mobile")?.appendChild(playerModel); } else if (window.innerWidth > 1590 && playerModelIsMobile) { playerModelIsMobile = false; document.getElementById("skin_display")?.appendChild(playerModel); } tippy("*[data-tippy-content]"); if (playerModel && skinViewer) { if (playerModel.offsetWidth / playerModel.offsetHeight < 0.6) { skinViewer.setSize(playerModel.offsetWidth, playerModel.offsetWidth * 2); } else { skinViewer.setSize(playerModel.offsetHeight / 2, playerModel.offsetHeight); } } navBarHeight = parseFloat(getComputedStyle(navBar).top); const element = document.querySelector<HTMLElement>(".rich-item.sticky-stats"); if (element == null) { return; } const maxTop = window.innerHeight - statsContent.offsetHeight - 20; const rect = element.getBoundingClientRect(); if (rect.x) { statsContent.style.left = rect.x - statsContent.offsetWidth - 10 + "px"; } if (rect.y) { statsContent.style.top = Math.max(70, Math.min(maxTop, rect.y + element.offsetHeight / 2 - statsContent.offsetHeight / 2)) + "px"; } } document.querySelectorAll(".extender").forEach((element) => { element.addEventListener("click", () => element.setAttribute("aria-expanded", (element.getAttribute("aria-expanded") != "true").toString()) ); }); function flashForUpdate(element: HTMLElement) { element.classList.add("updated"); element.addEventListener("animationend", () => { element.classList.remove("updated"); }); } for (const element of document.querySelectorAll<HTMLElement>(".stat-weapons .select-weapon")) { const parent = element.parentElement as HTMLElement; const itemId = parent.getAttribute("data-item-id") as string; const item = allItems.get(itemId) as Item; const weaponStats = calculated.weapon_stats[itemId]; let stats; element.addEventListener("mousedown", (event) => { event.preventDefault(); }); const activeWeaponElement = document.querySelector(".stat-active-weapon") as HTMLElement; element.addEventListener("click", (event) => { event.stopPropagation(); if (parent.classList.contains("piece-selected")) { parent.classList.remove("piece-selected"); stats = calculated.stats; activeWeaponElement.className = "stat-value stat-active-weapon piece-common-fg"; activeWeaponElement.innerHTML = "None"; } else { for (const _element of document.querySelectorAll(".stat-weapons .piece")) { _element.classList.remove("piece-selected"); } parent.classList.add("piece-selected"); activeWeaponElement.className = "stat-value stat-active-weapon piece-" + item.rarity + "-fg"; activeWeaponElement.innerHTML = item.display_name_print || item.display_name; stats = weaponStats; } flashForUpdate(activeWeaponElement); for (const stat in stats) { if (stat != "sea_creature_chance") { updateStat(stat as StatName, stats[stat as StatName]); } } }); } for (const element of document.querySelectorAll<HTMLElement>(".stat-fishing .select-rod")) { const parent = element.parentElement as HTMLElement; const itemId = parent.getAttribute("data-item-id") as string; const item = allItems.get(itemId) as Item; const weaponStats = calculated.weapon_stats[itemId]; let stats; element.addEventListener("mousedown", (event) => { event.preventDefault(); }); const activeRodElement = document.querySelector(".stat-active-rod") as HTMLElement; element.addEventListener("click", (event) => { event.stopPropagation(); if (parent.classList.contains("piece-selected")) { parent.classList.remove("piece-selected"); stats = calculated.stats; activeRodElement.className = "stat-value stat-active-rod piece-common-fg"; activeRodElement.innerHTML = "None"; } else { for (const _element of document.querySelectorAll(".stat-fishing .piece")) { _element.classList.remove("piece-selected"); } parent.classList.add("piece-selected"); activeRodElement.className = "stat-value stat-active-rod piece-" + item.rarity + "-fg"; activeRodElement.innerHTML = item.display_name_print || item.display_name; stats = weaponStats; } flashForUpdate(activeRodElement); updateStat("sea_creature_chance", stats.sea_creature_chance); }); } function updateStat(stat: StatName, newValue: number) { const elements = document.querySelectorAll<HTMLElement>(".basic-stat[data-stat=" + stat + "] .stat-value"); for (const element of elements) { const currentValue = parseFloat(element.innerHTML.replaceAll(",", "")); if (newValue != currentValue) { element.innerHTML = newValue.toLocaleString(); flashForUpdate(element); } } } for (const element of document.querySelectorAll(".inventory-tab")) { const type = element.getAttribute("data-inventory-type") as string; element.addEventListener("click", () => { if (element.classList.contains("active-inventory")) { return; } const activeInventory = document.querySelector<HTMLElement>(".inventory-tab.active-inventory"); if (activeInventory) { activeInventory.classList.remove("active-inventory"); } element.classList.add("active-inventory"); switchInventory(type); }); } const statsContent = document.querySelector("#stats_content") as HTMLElement; const itemName = statsContent.querySelector(".item-name") as HTMLElement; const itemIcon = itemName.querySelector("div:first-child") as HTMLDivElement; const itemNameContent = itemName.querySelector("span") as HTMLSpanElement; const itemLore = statsContent.querySelector(".item-lore") as HTMLElement; const backpackContents = statsContent.querySelector(".backpack-contents") as HTMLElement; export function mouseenterLoreListener(event: MouseEvent): void { const element = event.target as HTMLElement; fillLore(element); statsContent.classList.add("show-stats"); } export function mouseleaveLoreListener(): void { statsContent.classList.remove("show-stats"); } export function mousemoveLoreListener(event: MouseEvent): void { const element = event.target as HTMLElement; if (statsContent.classList.contains("sticky-stats")) { return; } const maxTop = window.innerHeight - statsContent.offsetHeight - 20; const rect = element.getBoundingClientRect(); let left = rect.x - statsContent.offsetWidth - 10; if (left < 10) { left = rect.x + 90; } if (rect.x) { statsContent.style.left = left + "px"; } const top = Math.max(70, Math.min(maxTop, event.clientY - statsContent.offsetHeight / 2)); statsContent.style.top = top + "px"; } export function clickLoreListener(event: MouseEvent): void { const element = event.target as HTMLElement; if (statsContent.classList.contains("sticky-stats")) { closeLore(); } else { showLore(element, false); } } for (const element of document.querySelectorAll<HTMLElement>(".rich-item")) { element.addEventListener("mouseenter", mouseenterLoreListener); element.addEventListener("mouseleave", mouseleaveLoreListener); element.addEventListener("mousemove", mousemoveLoreListener); element.addEventListener("click", clickLoreListener); } const enableApiPlayer = document.querySelector("#enable_api") as HTMLVideoElement; for (const element of document.querySelectorAll(".enable-api")) { element.addEventListener("click", (event) => { event.preventDefault(); dimmer.classList.add("show-dimmer"); enableApiPlayer.classList.add("show"); enableApiPlayer.currentTime = 0; enableApiPlayer.play(); }); } enableApiPlayer.addEventListener("click", (event) => { event.stopPropagation(); if (enableApiPlayer.paused) { enableApiPlayer.play(); } else { enableApiPlayer.pause(); } }); dimmer.addEventListener("click", () => { dimmer.classList.remove("show-dimmer"); enableApiPlayer.classList.remove("show"); closeLore(); }); for (const element of document.querySelectorAll<HTMLElement>(".close-lore")) { element.addEventListener("click", closeLore); } for (const element of document.querySelectorAll<HTMLElement>(".copy-text")) { const copyNotification = tippy(element, { content: "Copied to clipboard!", trigger: "manual", }); element.addEventListener("click", () => { const text = element.getAttribute("data-copy-text"); if (text != null) { navigator.clipboard.writeText(text).then(() => { copyNotification.show(); setTimeout(() => { copyNotification.hide(); }, 1500); }); } }); } function parseFavorites(cookie: string) { return cookie?.split(",").filter((uuid) => /^[0-9a-f]{32}$/.test(uuid)) || []; } function checkFavorite() { const favorited = parseFavorites(getCookie("favorite")).includes( favoriteElement.getAttribute("data-username") as string ); favoriteElement.setAttribute("aria-checked", favorited.toString()); return favorited; } checkFavorite(); const favoriteNotification = tippy(favoriteElement, { trigger: "manual", }); favoriteElement.addEventListener("click", () => { const uuid = favoriteElement.getAttribute("data-username") as string; if (uuid == "0c0b857f415943248f772164bf76795c") { favoriteNotification.setContent("No"); } else { const cookieArray = parseFavorites(getCookie("favorite")); if (cookieArray.includes(uuid)) { cookieArray.splice(cookieArray.indexOf(uuid), 1); favoriteNotification.setContent("Removed favorite!"); } else if (cookieArray.length >= constants.max_favorites) { favoriteNotification.setContent(`You can only have ${constants.max_favorites} favorites!`); } else { cookieArray.push(uuid); favoriteNotification.setContent("Added favorite!"); } setCookie("favorite", cookieArray.join(","), 365); checkFavorite(); } favoriteNotification.show(); setTimeout(() => { favoriteNotification.hide(); }, 1500); }); let socialsShown = false; const revealSocials = document.querySelector("#reveal_socials") as HTMLElement; const additionalSocials = document.querySelector("#additional_socials") as HTMLElement; if (revealSocials) { revealSocials.addEventListener("click", () => { if (socialsShown) { socialsShown = false; additionalSocials.classList.remove("socials-shown"); revealSocials.classList.remove("socials-shown"); } else { socialsShown = true; additionalSocials.classList.add("socials-shown"); revealSocials.classList.add("socials-shown"); } }); } class ScrollMemory { _isSmoothScrolling = false; _scrollTimeout = -1; _loaded = false; constructor() { window.addEventListener( "load", () => { this._loaded = true; this.isSmoothScrolling = true; }, { once: true } ); window.addEventListener("hashchange", () => { this.isSmoothScrolling = true; }); document.addEventListener("focusin", () => { this.isSmoothScrolling = true; }); } /** wether the document currently has a smooth scroll taking place */ get isSmoothScrolling() { return this._isSmoothScrolling || !this._loaded; } set isSmoothScrolling(value) { if (this._isSmoothScrolling !== value) { this._isSmoothScrolling = value; if (value) { window.addEventListener("scroll", this._onScroll, { passive: true }); this._onScroll(); } else { window.removeEventListener("scroll", this._onScroll); scrollToTab(); } } } _onScroll = () => { clearTimeout(this._scrollTimeout); this._scrollTimeout = window.setTimeout(() => { this.isSmoothScrolling = false; }, 500); }; } const scrollMemory = new ScrollMemory(); const intersectingElements = new Map(); const sectionObserver = new IntersectionObserver( (entries) => { for (const entry of entries) { intersectingElements.set(entry.target, entry.isIntersecting); } for (const [element, isIntersecting] of intersectingElements) { if (isIntersecting) { let newHash; if (element !== playerProfileElement) { newHash = "#" + element.parentElement.querySelector("a[id]").id; history.replaceState({}, document.title, newHash); } else { history.replaceState({}, document.title, location.href.split("#")[0]); } for (const link of navBarLinks) { if (link.hash === newHash) { link.setAttribute("aria-current", "true"); if (!scrollMemory.isSmoothScrolling) { scrollToTab(true, link); } } else { link.removeAttribute("aria-current"); } } break; } } }, { rootMargin: "-100px 0px -25% 0px" } ); function scrollToTab(smooth = true, element?: HTMLElement) { const link = element ?? document.querySelector<HTMLAnchorElement>(`[href="${location.hash}"]`); if (link == null) { throw new Error("could not find tab to scroll to"); } const behavior = smooth ? "smooth" : "auto"; const left = link.offsetLeft + link.getBoundingClientRect().width / 2 - (link.parentElement as HTMLElement).getBoundingClientRect().width / 2; (link.parentElement as HTMLElement).scrollTo({ left, behavior }); } scrollToTab(false); const playerProfileElement = document.querySelector("#player_profile") as HTMLElement; sectionObserver.observe(playerProfileElement); document.querySelectorAll(".stat-header").forEach((element) => { sectionObserver.observe(element); }); const statsContainer = document.querySelector<HTMLElement>("#base_stats_container"); const showStats = document.querySelector<HTMLElement>("#show_stats"); if (showStats != null) { showStats.addEventListener("click", () => { if ((statsContainer as HTMLElement).classList.contains("show-stats")) { (statsContainer as HTMLElement).classList.remove("show-stats"); (showStats as HTMLElement).innerHTML = "Show Stats"; } else { (statsContainer as HTMLElement).classList.add("show-stats"); (showStats as HTMLElement).innerHTML = "Hide Stats"; } }); } for (const element of document.querySelectorAll(".xp-skill")) { const skillProgressText = element.querySelector<HTMLElement>(".skill-progress-text"); if (skillProgressText === null) { break; } const originalText = skillProgressText.innerHTML; element.addEventListener("mouseenter", () => { skillProgressText.innerHTML = skillProgressText.getAttribute("data-hover-text") as string; }); element.addEventListener("mouseleave", () => { skillProgressText.innerHTML = originalText; }); } for (const element of document.querySelectorAll(".kills-deaths-container .show-all.enabled")) { const parent = element.parentElement as HTMLElement; const kills = calculated[element.getAttribute("data-type") as "kills" | "deaths"]; element.addEventListener("click", () => { parent.style.maxHeight = parent.offsetHeight + "px"; parent.classList.add("all-shown"); element.remove(); kills.slice(10).forEach((kill, index) => { const killElement = document.createElement("div"); const killRank = document.createElement("div"); const killEntity = document.createElement("div"); const killAmount = document.createElement("div"); const statSeparator = document.createElement("div"); killElement.className = "kill-stat"; killRank.className = "kill-rank"; killEntity.className = "kill-entity"; killAmount.className = "kill-amount"; statSeparator.className = "stat-separator"; killRank.innerHTML = "#" + (index + 11) + "&nbsp;"; killEntity.innerHTML = kill.entityName; killAmount.innerHTML = kill.amount.toLocaleString(); statSeparator.innerHTML = ":&nbsp;"; killElement.appendChild(killRank); killElement.appendChild(killEntity); killElement.appendChild(statSeparator); killElement.appendChild(killAmount); parent.appendChild(killElement); }); }); } window.addEventListener("keydown", (event) => { const selectedPiece = document.querySelector<HTMLElement>(".rich-item:focus"); if (selectedPiece !== null && event.key === "Enter") { fillLore(selectedPiece); showLore(selectedPiece); } if (event.key === "Escape") { dimmer.classList.remove("show-dimmer"); enableApiPlayer.classList.remove("show"); if (document.querySelector("#stats_content.sticky-stats") != null) { closeLore(); } } if (document.querySelector(".rich-item.sticky-stats") != null && event.key === "Tab") { event.preventDefault(); } }); resize(); window.addEventListener("resize", resize); function onScroll() { if (navBar.getBoundingClientRect().top <= navBarHeight) { navBar.classList.add("stuck"); } else { navBar.classList.remove("stuck"); } } onScroll(); window.addEventListener("scroll", onScroll, { passive: true }); setTimeout(resize, 1000);
the_stack
import { Diablo2Level, Diablo2LevelNpcSuper, Diablo2MpqData } from '@diablo2/data'; import { Diablo2MpqLoader } from '@diablo2/bintools'; import { toHex } from 'binparse'; import { ChildProcess, spawn } from 'child_process'; import { promises as fs } from 'fs'; import { EventEmitter } from 'events'; import PLimit from 'p-limit'; import { createInterface } from 'readline'; import { Log, LogType } from '../logger.js'; import { run } from './child.process.js'; import { LruCache } from './lru.js'; import { Diablo2MapGenMessage, MapGenMessageInfo, MapGenMessageMap } from './map.js'; import { F_OK } from 'constants'; export const MapCommand = ['./bin/d2-map.exe', '../bin/d2-map.exe']; export const Diablo2Path = '/app/game'; export const RegistryPath = '/app/d2.install.reg'; export const WineCommand = 'wine'; /** Wait at most 10 seconds for things to work */ const ProcessTimeout = 30_000; /** Attempt to generate the map 3 times */ const MaxAttempts = 3; const MaxMapsToGenerate = 5000; interface LogMessage { time: number; level: number; msg: string; id?: string; } export function isLogMessage(x: unknown): x is LogMessage { if (typeof x !== 'object') return false; if (x == null) return false; if ('time' in x) return true; return false; } async function timeOut(message: string, timeout: number): Promise<void> { return new Promise((resolve, reject) => { const timer = setTimeout(() => reject(`${message} Timeout after ${timeout}ms`), timeout); timer.unref(); }); } function getJson<T>(s: string): T | null { try { return JSON.parse(s); } catch (e) { return null; } } function fileExists(f: string): Promise<boolean> { return fs .access(f, F_OK) .then(() => true) .catch(() => false); } let ProcId = 0; const MapCache: LruCache<Diablo2Level[]> = new LruCache(100); // Disable wine debug logging const cwd = process.cwd(); export class Diablo2MapProcess { process: ChildProcess | null; /** Number of maps generated by this process */ generatedCount = 0; events: EventEmitter = new EventEmitter(); mpq: Diablo2MpqData; mapCommand: string; id: number; constructor(mpq: Diablo2MpqData, mapCommand: string) { this.mpq = mpq; this.mapCommand = mapCommand; this.id = ProcId++; } /** * Limit the map generation to a single thread * TODO having a pool of these map processes would be quite nice */ q = PLimit(1); /** Get the version of WINE that is being used */ async version(log: LogType): Promise<string> { const versionResponse = await run(WineCommand, ['--version']); const version = versionResponse.stdout; log.info({ version, command: WineCommand }, 'MapProcess:WineVersion'); return version; } get isRunning(): boolean { return this.process != null; } /** Start the map process waiting for the `init` event before allowing anything to continue */ async start(log: LogType): Promise<void> { if (this.isRunning) return; this.generatedCount = 0; const args = [this.mapCommand, Diablo2Path]; log.info({ proc: this.id, wineArgs: args }, 'MapProcess:Starting'); return new Promise(async (resolve) => { const proc = spawn(WineCommand, args, { cwd, env: { WINEPREFIX: process.env['WINEPREFIX'], WINEDEBUG: '-all' } }); if (proc == null || proc.stdout == null) throw new Error('Failed to start command'); this.process = proc; proc.stderr.on('data', (data) => { const line = data.toString().trim(); if (line.includes('FS volume label and serial are not available')) return; Log.debug({ proc: this.id, data: line }, 'MapProcess:stderr'); if (line.includes('We got a big Error here')) this.stop(log); }); proc.on('error', (error) => { log.fatal({ proc: this.id, error }, 'MapProcess:Died'); inter.close(); this.process = null; }); proc.on('close', (exitCode) => { inter.close(); this.process = null; this.events.emit('close'); if (exitCode == null) return; if (exitCode > 0) log.fatal({ proc: this.id, exitCode }, 'MapProcess:Closed'); }); log.info({ proc: this.id, processId: this.process.pid }, 'MapProcess:Started'); const inter = createInterface(proc.stdout).on('line', (line): unknown => { const json = getJson<Diablo2MapGenMessage | LogMessage>(line); if (json == null) return; if (isLogMessage(json)) return this.events.emit('log', json); if (json.type) return this.events.emit(json.type, json); return; }); await this.once('init'); resolve(); }); } async once<T extends Diablo2MapGenMessage>(e: T['type'], cb?: () => void): Promise<T> { return Promise.race([ new Promise((resolve) => { this.events.once(e, (data) => resolve(data)); cb?.(); }), timeOut(`Event: ${e}`, ProcessTimeout), ]) as Promise<T>; } async stop(log: LogType): Promise<void> { if (this.process == null) return; log.info({ proc: this.id, processId: this.process.pid }, 'MapProcess:Stop'); this.process.kill('SIGKILL'); this.process = null; } async command(cmd: 'seed' | 'difficulty' | 'act', value: number, log: LogType): Promise<void> { const startTime = Date.now(); if (this.process == null) await this.start(log); const command = `$${cmd} ${value}\n`; const res = await this.once<MapGenMessageInfo>('info', () => this.process?.stdin?.write(command)); if (res[cmd] !== value) { throw new Error(`Failed to set ${cmd}=${value} (output: ${JSON.stringify(res)}: ${command})`); } log.trace({ cmd, value, duration: Date.now() - startTime }, 'MapProcess:Command'); } map(seed: number, difficulty: number, actId: number, log: LogType): Promise<Diablo2Level[]> { const mapKey = `${seed}_${difficulty}_${actId}`; const cacheData = MapCache.get(mapKey); if (cacheData != null) return Promise.resolve(cacheData); return this.q(async () => { const mapResult = await this.getMaps(seed, difficulty, actId, log); MapCache.set(mapKey, mapResult); return mapResult; }); } private async getMaps( seed: number, difficulty: number, actId: number, log: LogType, attempt = 0, ): Promise<Diablo2Level[]> { if (this.generatedCount > MaxMapsToGenerate) { log.warn('GenerateMap:Restart'); this.generatedCount = 0; await this.stop(log); await this.start(log); } if (!this.isRunning) await this.start(log); await this.command('seed', seed, log); await this.command('difficulty', difficulty, log); if (actId > -1) await this.command('act', actId, log); this.generatedCount++; log.info({ proc: this.id, seed: toHex(seed, 8), difficulty, generated: this.generatedCount }, 'GenerateMap:Start'); const maps: Map<number, Diablo2Level> = new Map(); const newMap = (msg: MapGenMessageMap): void => { log?.trace({ proc: this.id, mapId: msg.id }, 'GenerateMap:GotMap'); maps.set(msg.id, this.fixMap(msg)); }; return await new Promise((resolve, reject) => { const errorHandle = (err: unknown): void => { this.events.off('map', newMap); log.info({ proc: this.id, seed: toHex(seed, 8), difficulty, attempt, err }, 'GenerateMap:Error'); if (attempt < MaxAttempts) { this.getMaps(seed, difficulty, actId, log, attempt + 1) .then(resolve) .catch(reject); } else { console.log('Reject', { attempt, MaxAttempts }); reject(err); } }; const logLine = (json: LogMessage): void => { if (json.level < 30) return; log.info({ proc: this.id, ...json, log: json.msg }, 'MapProcess:Log'); }; this.events.once('close', errorHandle); this.events.on('map', newMap); this.events.on('log', logLine); this.events.once('done', () => { this.events.off('map', newMap); this.events.off('close', errorHandle); this.events.off('log', logLine); log?.trace({ proc: this.id, count: Object.keys(maps).length }, 'GenerateMap:Generated'); resolve([...maps.values()]); }); this.process?.stdin?.write(`$map\n`); }); } /** Correct the names of npcs and objects */ fixMap(map: MapGenMessageMap): MapGenMessageMap { map.name = this.mpq.levels.get(map.id)?.name.trim() ?? map.name; for (const obj of map.objects) { if (obj.type === 'npc') { if (obj.id >= this.mpq.monsters.size) { const superId = obj.id - this.mpq.monsters.size; if (superId < this.mpq.monsters.superUniques.length) { obj.name = this.mpq.monsters.superUniqueName(superId); (obj as Diablo2LevelNpcSuper).isSuperUnique = true; (obj as Diablo2LevelNpcSuper).superId = superId; } } else { obj.name = this.mpq.monsters.name(obj.id)?.trim(); } } // Force lowercase all the sub types if (obj.type === 'object') { obj.name = this.mpq.objects.get(obj.id)?.name.trim(); } if (obj.type === 'exit') { obj.name = this.mpq.levels.get(obj.id)?.name.trim(); } } return map; } } async function findD2MapExe(): Promise<string | null> { for (const mc of MapCommand) { if (await fileExists(mc)) return mc; } return null; } export class MapCluster { static ProcessCount = 1; static instance: Promise<MapCluster>; static async get(log: LogType): Promise<MapCluster> { if (this.instance != null) return this.instance; this.instance = this.create(log); return this.instance; } static async create(log: LogType): Promise<MapCluster> { const mpq = await Diablo2MpqLoader.load(Diablo2Path); const mapCommand = await findD2MapExe(); if (mapCommand == null) throw new Error('MapProcess:MissingMapExe'); log.info({ exe: mapCommand }, 'MapProcess:ExeFound'); if (await fileExists(RegistryPath)) { const res = await run(WineCommand, ['regedit', RegistryPath]); log.info({ data: res.stdout }, 'MapProcess:Registry:Update'); } return new MapCluster(mpq, mapCommand); } static async map(seed: number, difficulty: number, actId: number, log: LogType): Promise<Diablo2Level[]> { const cluster = await MapCluster.get(log); const process = cluster.process; if (!process.isRunning) await process.start(log); return process.map(seed, difficulty, actId, log); } processes: Diablo2MapProcess[] = []; currentIndex = 0; constructor(mpq: Diablo2MpqData, mapCommand: string) { for (let i = 0; i < MapCluster.ProcessCount; i++) { this.processes.push(new Diablo2MapProcess(mpq, mapCommand)); } } get process(): Diablo2MapProcess { const currentIndex = this.currentIndex; this.currentIndex = (currentIndex + 1) % this.processes.length; return this.processes[currentIndex]; } }
the_stack
var sceneShapes: oc.TopoDS_Shape[]; /** The dictionary that stores all of your imported STEP and IGES files. Push to sceneShapes to render in the view! * @example```sceneShapes.push(externalShapes['myStep.step']);``` */ var externalShapes: { [filename: string]: oc.TopoDS_Shape }; /** Type definition for Int */ type integer = number; /** Starts sketching a 2D shape which can contain lines, arcs, bezier splines, and fillets. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let sketch = new Sketch([0,0]).LineTo([100,0]).Fillet(20).LineTo([100,100]).End(true).Face();```*/ class Sketch { constructor(startingPoint: number[]); faces : oc.TopoDS_Face[]; wires : oc.TopoDS_Wire[]; firstPoint : oc.gp_Pnt; lastPoint : oc.gp_Pnt; wireBuilder : oc.BRepBuilderAPI_MakeWire; Start (startingPoint : number[] ) : Sketch; End (closed ?: boolean , reversed?:boolean) : Sketch; AddWire (wire : oc. TopoDS_Wire) : Sketch; LineTo (nextPoint : number[] ) : Sketch; ArcTo (pointOnArc : number[], arcEnd : number[]) : Sketch; BezierTo(bezierControlPoints : number[][]): Sketch; BSplineTo(bsplinePoints : number[][]): Sketch; /** Adds a 2D Fillet of specified radius at this vertex. Only applies to Faces! * If a Wire is needed, use ForEachWire() to get the Wire from the resulting Face! */ Fillet (radius : number ) : Sketch; Face (reversed ?:boolean) : oc.TopoDS_Face; Wire (reversed ?:boolean) : oc.TopoDS_Wire; /** Punches a circular hole in the existing face (may need to use reversed) */ Circle (center ?:number[], radius:number, reversed?:boolean) : Sketch; } /** Creates a solid box with dimensions x, y, and, z and adds it to `sceneShapes` for rendering. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let myBox = Box(10, 20, 30);```*/ function Box(x: number, y: number, z: number, centered?: boolean): oc.TopoDS_Shape; /** Creates a solid sphere of specified radius and adds it to `sceneShapes` for rendering. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let mySphere = Sphere(40);```*/ function Sphere(radius: number): oc.TopoDS_Shape; /** Creates a solid cylinder of specified radius and height and adds it to `sceneShapes` for rendering. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let myCylinder = Cylinder(30, 50);```*/ function Cylinder(radius: number, height: number, centered?: boolean): oc.TopoDS_Shape; /** Creates a solid cone of specified bottom radius, top radius, and height and adds it to `sceneShapes` for rendering. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let myCone = Cone(30, 50);```*/ function Cone(radius1: number, radius2: number, height: number): oc.TopoDS_Shape; /** Creates a polygon from a list of 3-component lists (points) and adds it to `sceneShapes` for rendering. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let triangle = Polygon([[0, 0, 0], [50, 0, 0], [25, 50, 0]]);```*/ function Polygon(points: number[][], wire?: boolean): oc.TopoDS_Shape; /** Creates a circle from a radius and adds it to `sceneShapes` for rendering. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let circle = Circle(50);```*/ function Circle(radius:number, wire?:boolean) : oc.TopoDS_Shape; /** Creates a bspline from a list of 3-component lists (points). * This can be converted into a face via the respective oc.BRepBuilderAPI functions. * Or used directly with BRepPrimAPI_MakeRevolution() * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let bspline = BSpline([[0,0,0], [40, 0, 50], [50, 0, 50]], true);```*/ function BSpline(points:number[][], closed?:boolean) : oc.TopoDS_Shape; /** Creates set of glyph solids from a string and a font-file and adds it to sceneShapes. * Note that all the characters share a singular face. * * Defaults: size:36, height:0.15, fontName: 'Roboto' * * Try 'Roboto' or 'Papyrus' for an alternative typeface. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let myText = Text3D("Hello!");```*/ function Text3D(text?: string = "Hi!", size?: number = "36", height?: number = 0.15, fontURL?: string = "Roboto") : oc.TopoDS_Shape; /** Joins a list of shapes into a single solid. * The original shapes are removed unless `keepObjects` is true. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let sharpSphere = Union([Sphere(38), Box(50, 50, 50, true)]);```*/ function Union(objectsToJoin: oc.TopoDS_Shape[], keepObjects?: boolean, fuzzValue?:number, keepEdges?: boolean): oc.TopoDS_Shape; /** Subtracts a list of shapes from mainBody. * The original shapes are removed unless `keepObjects` is true. Returns a Compound Shape unless onlyFirstSolid is true. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let floatingCorners = Difference(Box(50, 50, 50, true), [Sphere(38)]);```*/ function Difference(mainBody: oc.TopoDS_Shape, objectsToSubtract: oc.TopoDS_Shape[], keepObjects?: boolean | boolean[], fuzzValue?:number, keepEdges?: boolean): oc.TopoDS_Shape; /** Takes only the intersection of a list of shapes. * The original shapes are removed unless `keepObjects` is true. * `keepObjects` can also be a list [keepMainBody: boolean, keepObjectsToSubtract: boolean] * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let roundedBox = Intersection([Box(50, 50, 50, true), Sphere(38)]);```*/ function Intersection(objectsToIntersect: oc.TopoDS_Shape[], keepObjects?: boolean, fuzzValue?: number, keepEdges?: boolean): oc.TopoDS_Shape; /** Removes internal, unused edges from the insides of faces on this shape. Keeps the model clean. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let cleanPart = RemoveInternalEdges(part);```*/ function RemoveInternalEdges(shape: oc.TopoDS_Shape, keepShape?: boolean) : oc.TopoDS_Shape; /** Extrudes a shape along direction, a 3-component vector. Edges form faces, Wires form shells, Faces form solids, etc. * The original face is removed unless `keepFace` is true. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let tallTriangle = Extrude(Polygon([[0, 0, 0], [50, 0, 0], [25, 50, 0]]), [0, 0, 50]);```*/ function Extrude(face: oc.TopoDS_Shape, direction: number[], keepFace?: boolean) : oc.TopoDS_Shape; /** Extrudes and twists a flat *wire* upwards along the z-axis (see the optional argument for Polygon). * The original wire is removed unless `keepWire` is true. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let twistyTriangle = RotatedExtrude(Polygon([[-25, -15, 0], [25, -15, 0], [0, 35, 0]], true), 50, 90);```*/ function RotatedExtrude(wire: oc.TopoDS_Shape, height: number, rotation: number, keepWire?: boolean) : oc.TopoDS_Shape; /** Lofts a solid through the sections defined by an array of 2 or more closed wires. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) */ function Loft(wireSections: oc.TopoDS_Shape[], keepWires?: boolean): oc.TopoDS_Shape; /** Revolves this shape "degrees" about "axis" (a 3-component array). Edges form faces, Wires form shells, Faces form solids, etc. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let cone = Revolve(Polygon([[0, 0, 0], [0, 0, 50], [50, 0, 0]]));```*/ function Revolve(shape: oc.TopoDS_Shape, degrees?: number, axis?: number[], keepShape?: boolean, copy?: boolean): oc.TopoDS_Shape; /** Sweeps this shape along a path wire. * The original shapes are removed unless `keepObjects` is true. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let pipe = Pipe(Circle(20), BSpline([[0,0,0],[0,0,50],[20,0,100]], false, true));```*/ function Pipe(shape: oc.TopoDS_Shape, wirePath: oc.TopoDS_Shape, keepInputs?: boolean): oc.TopoDS_Shape; /** Offsets the faces of a shape by offsetDistance * The original shape is removed unless `keepShape` is true. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let roundedCube = Offset(Box(10,10,10), 10);```*/ function Offset(shape: oc.TopoDS_Shape, offsetDistance: number, tolerance?: number, keepShape?: boolean) : oc.TopoDS_Shape; /** Creates a labeled slider with specified defaults, mins, and max ranges. * @example```let currentSliderValue = Slider("Radius", 30 , 20 , 40);``` * `name` needs to be unique! * * `callback` triggers whenever the mouse is let go, and `realTime` will cause the slider to update every frame that there is movement (but it's buggy!) * * @param step controls the amount that the keyboard arrow keys will increment or decrement a value. Defaults to 1/100 (0.01). * @param precision controls how many decimal places the slider can have (i.e. "0" is integers, "1" includes tenths, etc.). Defaults to 2 decimal places (0.00). * * @example```let currentSliderValue = Slider("Radius", 30 , 20 , 40, false);``` * @example```let currentSliderValue = Slider("Radius", 30 , 20 , 40, false, 0.01);``` * @example```let currentSliderValue = Slider("Radius", 30 , 20 , 40, false, 0.01, 2);``` */ function Slider(name: string, defaultValue: number, min: number, max: number, realTime?: boolean, step?: number, precision?: integer): number; /** @deprecated Callbacks can no longer be triggered from the CAD Worker Thread. * Creates a button ~~that will trigger `callback` when clicked.~~ * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```Button("Yell", ()=>{ console.log("Help! I've been clicked!"); });```*/ function Button(name: string) : void; /** Creates a checkbox that returns true or false. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let currentCheckboxValue = Checkbox("Check?", true);``` * * `callback` triggers when the button is clicked.*/ function Checkbox(name: string, defaultValue: boolean): boolean; /** Creates a text box input element that returns a string * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let text = TextInput("Banner", "Hello!", false);``` */ function TextInput(name: string, defaultValue: string, realTime?: boolean): string; /** Creates a dropdown list element that returns the value of the selected item * * @param options Object with a list of key and value pairs to display in dropdown * @example```let position = Dropdown("Position", 0, { top: 0, center: 5, bottom: 10 }, false);``` * @example```let iconSelection = Dropdown("Icon", "heart", { Heart: "heart", Key: "key", Cog: "cog" }, false);``` */ function Dropdown(name: string, defaultValue: string, options: { [key: string]: string }, realTime?: boolean): string; function Dropdown(name: string, defaultValue: number, options: { [key: string]: number }, realTime?: boolean): number; /** BETA: Transform a shape using an in-view transformation gizmo. * * Shortcuts: `T` - Translate, `R` - Rotate, `S` - Scale, `W`/`L` - Toggle World/Local Space * * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let transformedSphere = Transform(Sphere(50));```*/ function Transform(shape: oc.TopoDS_Shape): oc.TopoDS_Shape; /** BETA: Transform a shape using an in-view transformation gizmo. * * Shortcuts: `T` - Translate, `R` - Rotate, `S` - Scale, `W`/`L` - Toggle World/Local * * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let transformedSphere = Transform(Sphere(50));```*/ function Transform(translation: number[], rotation: (number|number[])[], scale: number, shape: oc.TopoDS_Shape, keepOriginal?: boolean): oc.TopoDS_Shape; /** Translate a shape along the x, y, and z axes (using an array of 3 numbers). * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let upwardSphere = Translate([0, 0, 50], Sphere(50));```*/ function Translate(offset: number[], shape: oc.TopoDS_Shape, keepOriginal?: boolean): oc.TopoDS_Shape; /** Rotate a shape degrees about a 3-coordinate axis. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let leaningCylinder = Rotate([0, 1, 0], 45, Cylinder(25, 50));```*/ function Rotate(axis: number[], degrees: number, shape: oc.TopoDS_Shape, keepOriginal?: boolean): oc.TopoDS_Shape; /** Scale a shape to be `scale` times its current size. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let scaledCylinder = Scale(50, Cylinder(0.5, 1));```*/ function Scale(scale: number, shape: oc.TopoDS_Shape, keepOriginal?: boolean): oc.TopoDS_Shape; /** Iterate over all the solids in this shape, calling `callback` on each one. */ function ForEachSolid(shape: oc.TopoDS_Shape, callback: (index: Number, shell: oc.TopoDS_Solid) => void): void; /** Gets the indexth solid from this compound shape. */ function GetSolidFromCompound(shape: oc.TopoDS_Shape, index?:number, keepOriginal?:boolean): oc.TopoDS_Solid; /** Gets the indexth wire from this face (or above) shape. */ function GetWire(shape: oc.TopoDS_Face, index?:number, keepOriginal?:boolean): oc.TopoDS_Wire; /** Iterate over all the shells in this shape, calling `callback` on each one. */ function ForEachShell(shape: oc.TopoDS_Shape, callback: (index: Number, shell: oc.TopoDS_Shell) => void): void; /** Iterate over all the faces in this shape, calling `callback` on each one. */ function ForEachFace(shape: oc.TopoDS_Shape, callback: (index: number, face: oc.TopoDS_Face) => void): void; /** Iterate over all the wires in this shape, calling `callback` on each one. */ function ForEachWire(shape: oc.TopoDS_Shape, callback: (wire: oc.TopoDS_Wire) => void): void; /** Iterate over all the UNIQUE indices and edges in this shape, calling `callback` on each one. */ function ForEachEdge(shape: oc.TopoDS_Shape, callback: (index: number, edge: oc.TopoDS_Edge) => void): {[edgeHash:number] : Number}[]; /** Iterate over all the vertices in this shape, calling `callback` on each one. */ function ForEachVertex(shape: oc.TopoDS_Shape, callback: (vertex: oc.TopoDS_Vertex) => void): void; /** Attempt to Fillet all selected edge indices in "edgeList" with a radius. * Hover over the edges you'd like to select and use those indices as in the example. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```FilletEdges(shape, 1, [0,1,2,7]);``` */ function FilletEdges(shape: oc.TopoDS_Shape, radius: number, edgeList: number[], keepOriginal?:boolean): oc.TopoDS_Shape; /** Attempt to Chamfer all selected edge indices in "edgeList" symmetrically by distance. * Hover over the edges you'd like to select and use those indices in the edgeList array. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```ChamferEdges(shape, 1, [0,1,2,7]);``` */ function ChamferEdges(shape: oc.TopoDS_Shape, distance: number, edgeList: number[], keepOriginal?:boolean): oc.TopoDS_Shape; /** Download this file URL through the browser. Use this to export information from the CAD engine. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```SaveFile("myInfo.txt", URL.createObjectURL( new Blob(["Hello, Harddrive!"], { type: 'text/plain' }) ));``` */ function SaveFile(filename: string, fileURL: string): void; /** Explicitly Cache the result of this operation so that it can return instantly next time it is called with the same arguments. * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let box = CacheOp(arguments, () => { return new oc.BRepPrimAPI_MakeBox(x, y, z).Shape(); });``` */ function CacheOp(arguments: IArguments, cacheMiss: () => oc.TopoDS_Shape): oc.TopoDS_Shape; /** Remove this object from this array. Useful for preventing objects being added to `sceneShapes` (in cached functions). * [Source](https://github.com/zalo/CascadeStudio/blob/master/js/CADWorker/CascadeStudioStandardLibrary.js) * @example```let box = CacheOp(arguments, () => { let box = Box(x,y,z); sceneShapes = Remove(sceneShapes, box); return box; });``` */ function Remove(array: any[], toRemove: any): any[];
the_stack
import * as fs from 'fs'; import * as XmlStream from 'xml-stream'; import { BoundingBox, Character, Document, Element, Font, Image, Page, Word, } from '../../types/DocumentRepresentation'; import { Color } from '../../types/DocumentRepresentation/Color'; import { SvgLine } from '../../types/DocumentRepresentation/SvgLine'; import { PdfminerFigure } from '../../types/PdfminerFigure'; import { PdfminerPage } from '../../types/PdfminerPage'; import { PdfminerShape } from '../../types/PdfminerShape'; import { PdfminerText } from '../../types/PdfminerText'; import { isPerimeterLine, isPixelLine } from '../../utils'; import * as CommandExecuter from '../../utils/CommandExecuter'; import logger from '../../utils/Logger'; /** * Executes the pdfminer extraction function, reading an input pdf file and extracting a document representation. * This function involves recovering page contents like words, bounding boxes, fonts and other information that * the pdfminer tool's output provides. This function spawns the externally existing pdfminer tool. * * @param pdfInputFile The path including the name of the pdf file for input. * @returns The promise of a valid document (in the format DocumentRepresentation). */ export function extractPages( pdfInputFile: string, pages: string, rotationDegrees: number = 0, ): Promise<string> { return new Promise<string>((resolveXml, rejectXml) => { const startTime: number = Date.now(); CommandExecuter.pdfMinerExtract(pdfInputFile, pages, rotationDegrees) .then(xmlOutputPath => { logger.info(`PdfMiner xml: ${(Date.now() - startTime) / 1000}s`); try { resolveXml(xmlOutputPath); } catch (err) { rejectXml(`PdfMiner xml parser failed: ${err}`); } }) .catch(({ error }) => { rejectXml(`PdfMiner pdf2txt.py error: ${error}`); }); }); } const pushElement = (element, array, index = null) => { if (index != null) { array[index] = array[index] || []; array[index].push(element); } else { array = array || []; array.push(element); } }; export function extractDrawingsFromXML(xmlPath: string): Promise<any> { const startTime: number = Date.now(); const fileStream = fs.createReadStream(xmlPath); const xml = new XmlStream(fileStream); let shapes = []; const allPages = []; return new Promise((resolve, reject) => { xml.on('endElement: rect', rect => { pushElement({ _attr: rect.$, type: 'rect' }, shapes); }); // for now, curves are treated as polygons xml.on('endElement: curve', poly => { pushElement({ _attr: poly.$, type: 'poly' }, shapes); }); xml.on('endElement: line', line => { pushElement({ _attr: line.$, type: 'line' }, shapes); }); xml.on('updateElement: page', pageElement => { pushElement({ _attr: pageElement.$, shapes }, allPages); shapes = []; }); xml.on('end', () => { logger.info(`SVGs extraction time: ${(Date.now() - startTime) / 1000}s`); resolve({ pages: { page: allPages } }); }); xml.on('error', message => { logger.info(`XML Parsing error: ${message}`); reject(message); }); }); } export function xmlParser(xmlPath: string): Promise<any> { const startTime: number = Date.now(); return new Promise<any>((resolve, _reject) => { const fileStream = fs.createReadStream(xmlPath); const xml = new XmlStream(fileStream); const allPages: any[] = []; let textBoxes: any[] = []; let textLines: any[] = []; let texts: any[] = []; let figures: Figure[] = []; type Figure = { _attr: {}; image: any[]; text: any[]; figure: Figure[]; }; let currentFigure: Figure = null; const figuresStack: Figure[] = []; const pushWord = (word, array, index = null) => { let element = {}; if (word.$text != null && word.$ != null) { element = { _: word.$text.toString(), _attr: word.$ }; } else if (word.$ != null) { element = { _attr: word.$ }; } pushElement(element, array, index); }; xml.on('endElement: page > textbox > textline > text', word => { pushWord(word, texts); }); xml.on('endElement: page > textbox > textline', line => { pushElement({ _attr: line.$, text: texts }, textLines); texts = []; }); xml.on('endElement: page > textbox', line => { pushElement({ _attr: line.$, textline: textLines }, textBoxes); textLines = []; }); xml.on('startElement: figure', figFigure => { const f: Figure = { _attr: figFigure.$, figure: [], image: [], text: [] }; if (figuresStack.length === 0) { figures.push(f); } else { currentFigure.figure.push(f); } figuresStack.push(f); currentFigure = f; }); xml.on('startElement: image', figImage => { currentFigure.image.push({ _attr: figImage.$ }); }); xml.on('endElement: figure text', figText => { pushWord(figText, currentFigure.text); }); xml.on('endElement: figure', _figure => { figuresStack.pop(); currentFigure = figuresStack[figuresStack.length - 1]; }); xml.on('updateElement: page', pageElement => { pushElement({ _attr: pageElement.$, textbox: textBoxes, figure: figures }, allPages); textBoxes = []; figures = []; }); xml.on('end', () => { logger.info(`Xml to Js: ${(Date.now() - startTime) / 1000}s`); resolve({ pages: { page: allPages } }); }); xml.on('error', message => { logger.info(`XML Parsing error: ${message}`); }); }); } export function jsParser(json: any): Document { const startTime: number = Date.now(); const doc: Document = new Document(getPages(json)); logger.info(`Js to Document: ${(Date.now() - startTime) / 1000}s`); return doc; } function getPages(jsonObj: any): Page[] { const docPages: Page[] = []; if (Array.isArray(jsonObj.pages.page)) { jsonObj.pages.page.forEach(pageObj => docPages.push(getPage(new PdfminerPage(pageObj)))); } else if (jsonObj.pages != null) { docPages.push(getPage(new PdfminerPage(jsonObj.pages.page))); } return docPages; } function getPage(pageObj: PdfminerPage): Page { const boxValues: number[] = pageObj._attr.bbox.split(',').map(v => parseFloat(v)); const pageBBox: BoundingBox = new BoundingBox( boxValues[0], boxValues[1], boxValues[2], boxValues[3], ); let elements: Element[] = []; // treat paragraphs if (pageObj.textbox !== undefined) { pageObj.textbox.forEach(para => { para.textline.map(line => { elements = [ ...elements, ...breakLineIntoWords(line.text, ',', pageBBox.height, 1, para._attr.wmode), ]; }); }); } // treat figures if (pageObj.figure !== undefined) { pageObj.figure.forEach(fig => { if (hasImages(fig)) { elements = [...elements, ...interpretImages(fig, pageBBox.height)]; } if (hasTexts(fig)) { elements = [ ...elements, ...breakLineIntoWords(allTextsInFigure(fig), ',', pageBBox.height), ]; } }); } // treat svg lines and rectangles if (pageObj.shapes !== undefined) { pageObj.shapes.forEach(shape => { const shapes = pdfminerShapeToSvgShapes(shape, pageBBox.height) .filter(l => !isPerimeterLine(l, pageBBox) && !isPixelLine(l)); elements.push(...shapes); }); } return new Page(parseFloat(pageObj._attr.id), elements, pageBBox); } function pdfminerShapeToSvgShapes(shape: PdfminerShape, pageHeight: number): SvgLine[] { const drawingBox: BoundingBox = getBoundingBox(shape._attr.bbox, ',', pageHeight); const thickness = parseFloat(shape._attr.linewidth) || 1; const drawingContent: SvgLine[] = []; if (shape.type === 'rect') { drawingContent.push( new SvgLine( drawingBox, thickness, drawingBox.left, drawingBox.top, drawingBox.right, drawingBox.top, ), new SvgLine( drawingBox, thickness, drawingBox.right, drawingBox.top, drawingBox.right, drawingBox.bottom, ), new SvgLine( drawingBox, thickness, drawingBox.right, drawingBox.bottom, drawingBox.left, drawingBox.bottom, ), new SvgLine( drawingBox, thickness, drawingBox.left, drawingBox.bottom, drawingBox.left, drawingBox.top, ), ); } if (shape.type === 'line') { drawingContent.push( new SvgLine( drawingBox, thickness, drawingBox.left, drawingBox.top, drawingBox.right, drawingBox.bottom, ), ); } if (shape.type === 'poly') { const pts = shape._attr.pts.split(',').map(v => parseFloat(v)); for (let i = 0; i < pts.length; i += 2) { const x1 = pts[i]; const y1 = pageHeight - pts[i + 1]; const x2 = pts[i + 2]; const y2 = pageHeight - pts[i + 3]; if ([x1, x2, y1, y2].every(num => typeof num === 'number')) { drawingContent.push(new SvgLine(drawingBox, thickness, x1, y1, x2, y2)); } } const firstFromX = pts[0]; const firstFromY = pageHeight - pts[1]; const lastToX = pts[pts.length - 2]; const lastToY = pageHeight - pts[pts.length - 1]; if (firstFromX !== lastToX || firstFromY !== lastToY) { drawingContent.push( new SvgLine(drawingBox, thickness, lastToX, lastToY, firstFromX, firstFromY), ); } } return drawingContent; } function hasTexts(figure: PdfminerFigure): boolean { if (figure.text !== undefined) { return true; } if (figure.figure !== undefined) { return figure.figure.map(fig => hasTexts(fig)).reduce((a, b) => a || b); } return false; } function hasImages(figure: PdfminerFigure): boolean { if (figure.image !== undefined) { return true; } if (figure.figure !== undefined) { return figure.figure.map(fig => hasImages(fig)).reduce((a, b) => a || b); } return false; } // Pdfminer's bboxes are of the format: x0, y0, x1, y1. Our BoundingBox dims are as: left, top, width, height function getBoundingBox( bbox: string, splitter: string = ',', pageHeight: number = 0, scalingFactor: number = 1, ): BoundingBox { const values: number[] = bbox.split(splitter).map(v => parseFloat(v) * scalingFactor); const width: number = Math.abs(values[2] - values[0]); // right - left = width const height: number = Math.abs(values[1] - values[3]); // top - bottom = height const left: number = values[0]; const top: number = Math.abs(pageHeight - values[1]) - height; // invert x direction (pdfminer's (0,0) // is on the bottom left) return new BoundingBox(left, top, width, height); } function getMostCommonFont(theFonts: Font[]): Font { const fonts: Font[] = theFonts.reduce((a, b) => a.concat(b), []); const baskets: Font[][] = []; fonts.forEach((font: Font) => { let basketFound: boolean = false; baskets.forEach((basket: Font[]) => { if (basket.length > 0 && basket[0].isEqual(font)) { basket.push(font); basketFound = true; } }); if (!basketFound) { baskets.push([font]); } }); baskets.sort((a, b) => { return b.length - a.length; }); if (baskets.length > 0 && baskets[0].length > 0) { return baskets[0][0]; } else { return Font.undefinedFont; } } /** * Fetches the character a particular pdfminer's textual output represents * TODO: This placeholder will accommodate the solution at https://github.com/aarohijohal/pdfminer.six/issues/1 ... * TODO: ... For now, it returns a '?' when a (cid:) is encountered * @param character the character value outputted by pdfminer * @param font the font associated with the character -- TODO to be taken into consideration here */ function getValidCharacter(character: string): string { return RegExp(/\(cid:/gm).test(character) ? '?' : character; } function allTextsInFigure(figure: PdfminerFigure): PdfminerText[] { if (figure.figure) { return figure.figure.map(allTextsInFigure).reduce((a, b) => a.concat(b)); } if (figure.text) { return figure.text; } return []; } function interpretImages( figure: PdfminerFigure, pageHeight: number, scalingFactor: number = 1, parentFigure: string = '', ): Image[] { if (figure.figure) { return figure.figure .map(fig => interpretImages(fig, pageHeight, scalingFactor, parentFigure + figure._attr.name + '.'), ) .reduce((a, b) => a.concat(b)); } if (figure.image) { return figure.image.map(_img => { return new Image( getBoundingBox(figure._attr.bbox, ',', pageHeight, scalingFactor), '', // TODO: to be filled with the location of the image once resolved parentFigure + figure._attr.name, ); }); } return []; } function addMissingSpaces(char: PdfminerText, index: number, array: PdfminerText[]): PdfminerText[] { const nextChar = array[index + 1]; if (nextChar && nextChar._attr && char && char._attr && !charsAreSideBySide(char, nextChar)) { return [char, new PdfminerText({ _: undefined, _attr: char._attr })]; } return [char]; } function charsAreSideBySide(char: PdfminerText, nextChar: PdfminerText): boolean { const charBBox = getBoundingBox(char._attr.bbox); const nextCharBBox = getBoundingBox(nextChar._attr.bbox); return Math.abs(charBBox.bottom - nextCharBBox.bottom) < 2 && charBBox.left < nextCharBBox.left; } function breakLineIntoWords( texts: PdfminerText[], wordSeparator: string = ' ', pageHeight: number, scalingFactor: number = 1, wMode: string = null, ): Word[] { const notAllowedChars = ['\u200B']; // &#8203 Zero Width Space const words: Word[] = []; const fakeSpaces = thereAreFakeSpaces(texts); const filteredTexts = texts .filter(char => !notAllowedChars.includes(char._) && !isFakeChar(char, fakeSpaces)) .map(addMissingSpaces) .reduce((acc, val) => acc.concat(val), []); const chars: Character[] = filteredTexts .map(char => { if (char._ === undefined) { return undefined; } else { const font: Font = new Font(char._attr.font, parseFloat(char._attr.size), { weight: RegExp(/bold/gim).test(char._attr.font) ? 'bold' : 'medium', isItalic: RegExp(/italic/gim).test(char._attr.font) ? true : false, isUnderline: RegExp(/underline/gim).test(char._attr.font) ? true : false, color: ncolourToHex(char._attr.ncolour), }); const charContent: string = getValidCharacter(char._); return new Character( getBoundingBox(char._attr.bbox, ',', pageHeight, scalingFactor), charContent, font, ); } }); if (chars[0] === undefined || chars[0].content === wordSeparator) { chars.splice(0, 1); } if (chars[chars.length - 1] === undefined || chars[chars.length - 1].content === wordSeparator) { chars.splice(chars.length - 1, chars.length); } if (chars.length === 0 || (chars.length === 1 && chars[0] === undefined)) { return words; } if ( chars .filter(c => c !== undefined) .map(c => c.content.length) .filter(l => l > 1).length > 0 ) { logger.debug(`pdfminer returned some characters of size > 1`); } const sepLocs: number[] = chars .map((c, i) => { if (c === undefined) { return i; } else { return undefined; } }) .filter(l => l !== undefined) .filter(l => l !== 0) .filter(l => l !== chars.length); let charSelection: Character[] = []; if (sepLocs.length === 0) { charSelection = chars.filter(c => c !== undefined); words.push( new Word( BoundingBox.merge(charSelection.map(c => c.box)), charSelection, getMostCommonFont(charSelection.map(c => c.font)), ), ); } else { charSelection = chars.slice(0, sepLocs[0]).filter(c => c !== undefined); if (charSelection.length > 0) { words.push( new Word( BoundingBox.merge(charSelection.map(c => c.box)), charSelection, getMostCommonFont(charSelection.map(c => c.font)), ), ); } for (let i = 0; i !== sepLocs.length; ++i) { let from: number; let to: number; from = sepLocs[i] + 1; if (i !== sepLocs.length - 1) { to = sepLocs[i + 1]; } else { to = chars.length; } charSelection = chars.slice(from, to).filter(c => c !== undefined); if (charSelection.length > 0) { words.push( new Word( BoundingBox.merge(charSelection.map(c => c.box)), charSelection, getMostCommonFont(charSelection.map(c => c.font)), ), ); } } } return wMode ? words.map(w => { w.properties.writeMode = wMode; return w; }) : words; } function thereAreFakeSpaces(texts: PdfminerText[]): boolean { // Will remove all <text> </text> only if in line we found // <text> </text> followed by empty <text> but with attributes // <text font="W" bbox="W" colourspace="X" ncolour="Y" size="Z"> </text> const emptyWithAttr = texts .map((word, index) => { return { text: word, pos: index }; }) .filter(word => word.text._ === undefined && word.text._attr !== undefined) .map(word => word.pos); const emptyWithNoAttr = texts .map((word, index) => { return { text: word, pos: index }; }) .filter(word => word.text._ === undefined && word.text._attr === undefined) .map(word => word.pos); let fakeSpaces = false; emptyWithNoAttr.forEach(pos => { if (emptyWithAttr.includes(pos + 1)) { fakeSpaces = true; } }); return fakeSpaces; } function isFakeChar(word: PdfminerText, fakeSpacesInLine: boolean): boolean { if (fakeSpacesInLine && word._ === undefined && word._attr === undefined) { return true; } return false; } function ncolourToHex(color: string): Color { let finalColor: string = '#000000'; if (color === undefined) { return finalColor; } const rgbToHex = (r, g, b) => '#' + [r, g, b] .map(x => { const hex = Math.ceil(x * 255).toString(16); return hex.length === 1 ? '0' + hex : hex; }) .join(''); const cmykToRGB = (c: number, m: number, y: number, k: number) => { return { r: (1 - c) * (1 - k), g: (1 - m) * (1 - k), b: (1 - y) * (1 - k), }; }; const colors = color.replace(/[()[\]\s]/g, '').split(','); if (colors.length === 3) { finalColor = rgbToHex(colors[0], colors[1], colors[2]); } else if (colors.length === 4) { const { r, g, b } = cmykToRGB(+colors[0], +colors[1], +colors[2], +colors[3]); finalColor = rgbToHex(r, g, b); } else { finalColor = '#000000'; } return finalColor; }
the_stack
import React, {useState, useEffect, useContext} from "react"; import {Form, Input, Icon, Radio, AutoComplete, Popover} from "antd"; import axios from "axios"; import styles from "./create-edit-step.module.scss"; import "./create-edit-step.scss"; import {UserContext} from "../../../util/user-context"; import {NewMapTooltips, NewMatchTooltips, NewMergeTooltips, CommonStepTooltips} from "../../../config/tooltips.config"; import {MLButton, MLTooltip, MLAlert} from "@marklogic/design-system"; import {StepType} from "../../../types/curation-types"; import {CurationContext} from "../../../util/curation-context"; type Props = { tabKey: string; openStepSettings: boolean; setOpenStepSettings: any; isEditing: boolean; stepType: StepType; editStepArtifactObject: any; targetEntityType: string; canReadWrite: boolean; canReadOnly: boolean; createStepArtifact: (stepArtifact: any) => void; updateStepArtifact: (stepArtifact: any) => void; currentTab: string; setIsValid: any; resetTabs: any; setHasChanged: any; setPayload: any; onCancel: any; } const formItemLayout = { labelCol: { xs: {span: 24}, sm: {span: 7}, }, wrapperCol: { xs: {span: 24}, sm: {span: 15}, }, }; const srcTypeOptions = [ {label: "Collection", value: "collection"}, {label: "Query", value: "query"} ]; const {TextArea} = Input; const CreateEditStep: React.FC<Props> = (props) => { // TODO use steps.config.ts for default values const {handleError} = useContext(UserContext); const {curationOptions, setActiveStepWarning, validateCalled, setValidateMatchCalled, setValidateMergeCalled, validateMerge} = useContext(CurationContext); const [stepName, setStepName] = useState(""); const [description, setDescription] = useState(""); const [collections, setCollections] = useState(""); const [collectionOptions, setCollectionOptions] = useState(["a", "b"]); const [selectedSource, setSelectedSource] = useState(props.editStepArtifactObject.selectedSource ? props.editStepArtifactObject.selectedSource : "collection"); const [srcQuery, setSrcQuery] = useState(""); const [timestamp, setTimestamp] = useState(""); //To check submit validity const [isStepNameTouched, setStepNameTouched] = useState(false); const [isDescriptionTouched, setDescriptionTouched] = useState(false); const [isCollectionsTouched, setCollectionsTouched] = useState(false); const [isSrcQueryTouched, setSrcQueryTouched] = useState(false); const [isSelectedSourceTouched, setSelectedSourceTouched] = useState(false); const [isTimestampTouched, setTimestampTouched] = useState(false); const [invalidChars, setInvalidChars] = useState(false); const [isValid, setIsValid] = useState(false); // eslint-disable-line @typescript-eslint/no-unused-vars const [isSubmit, setIsSubmit] = useState(false); const [tobeDisabled, setTobeDisabled] = useState(false); const initStep = () => { setStepName(props.editStepArtifactObject.name); setDescription(props.editStepArtifactObject.description); setSrcQuery(props.editStepArtifactObject.sourceQuery); setSelectedSource(props.editStepArtifactObject.selectedSource); if (props.editStepArtifactObject.selectedSource === "collection") { let srcCollection = props.editStepArtifactObject.sourceQuery.substring( props.editStepArtifactObject.sourceQuery.lastIndexOf("[") + 2, props.editStepArtifactObject.sourceQuery.lastIndexOf("]") - 1 ); setCollections(srcCollection); } if (props.stepType === StepType.Merging) { setTimestamp(props.editStepArtifactObject.timestamp); } resetTouchedValues(); setIsValid(true); setTobeDisabled(true); setActiveStepWarning([]); setValidateMatchCalled(false); setValidateMergeCalled(false); props.setIsValid(true); }; useEffect(() => { // Edit Step Artifact if (props.isEditing) { initStep(); } else { // New Step Artifact reset(); props.setIsValid(false); } }, [props.openStepSettings]); useEffect(() => { if (isSubmit && curationOptions.activeStep.hasWarnings.length === 0 && props.stepType === StepType.Matching && validateCalled) { props.setOpenStepSettings(false); props.resetTabs(); } if (isSubmit && curationOptions.activeStep.hasWarnings.length === 0 && (props.stepType === StepType.Merging) && validateMerge) { props.setOpenStepSettings(false); props.resetTabs(); } }, [curationOptions.activeStep.hasWarnings.length, validateCalled, validateMerge]); const reset = () => { setStepName(""); setDescription(""); setSelectedSource("collection"); setTobeDisabled(false); setCollections(""); setSrcQuery(""); if (props.stepType === StepType.Merging) { setTimestamp(""); } resetTouchedValues(); setValidateMatchCalled(false); setValidateMergeCalled(false); setActiveStepWarning([]); setIsSubmit(false); }; const resetTouchedValues = () => { setSelectedSourceTouched(false); setCollectionsTouched(false); setSrcQueryTouched(false); setStepNameTouched(false); setDescriptionTouched(false); if (props.stepType === StepType.Merging) { setTimestampTouched(false); } }; const onCancel = () => { // Parent checks changes across tabs props.onCancel(); }; /* sends payload to steps.tsx */ const sendPayload = () => { props.setHasChanged(hasFormChanged()); props.setPayload(getPayload()); }; const hasFormChanged = () => { if (!isStepNameTouched && !isDescriptionTouched && !isSelectedSourceTouched && !isCollectionsTouched && !isSrcQueryTouched && !isTimestampTouched ) { return false; } else { return true; } }; const getPayload = () => { let result, sQuery; if (selectedSource === "collection") { sQuery = collections ? `cts.collectionQuery(['${collections}'])` : props.editStepArtifactObject.sourceQuery; result = { name: stepName, targetEntityType: props.targetEntityType, description: description, collection: collections, selectedSource: selectedSource, sourceQuery: sQuery }; } else { sQuery = srcQuery ? srcQuery : props.editStepArtifactObject.sourceQuery; result = { name: stepName, targetEntityType: props.targetEntityType, description: description, selectedSource: selectedSource, sourceQuery: sQuery }; } if (props.stepType === StepType.Merging) { result["timestamp"] = timestamp; } return result; }; const collectionQueryInfo = <div className={styles.collectionQueryInfo}>{CommonStepTooltips.radioCollection}</div>; const handleSubmit = async (event: { preventDefault: () => void; }) => { if (!stepName) { // missing name setStepNameTouched(true); } if (!collections && selectedSource === "collection") { // missing collection (if collection is selected) setCollectionsTouched(true); } if (!srcQuery && selectedSource !== "collection") { // missing query (if query is selected) setSrcQueryTouched(true); } if (!stepName || invalidChars || (!collections && selectedSource === "collection") || (!srcQuery && selectedSource !== "collection")) { // if missing flags are set, do not submit handle event.preventDefault(); return; } // else: all required fields are set if (event) event.preventDefault(); setIsValid(true); if (!props.isEditing) { props.createStepArtifact(getPayload()); } else { props.updateStepArtifact(getPayload()); } ((props.stepType === StepType.Matching) || (props.stepType === StepType.Merging))? setIsSubmit(true):setIsSubmit(false); if (props.stepType !== StepType.Matching && props.stepType !== StepType.Merging) { props.setOpenStepSettings(false); props.resetTabs(); } }; const handleSearch = async (value: any) => { let database: string = ""; if (!props.isEditing && props.stepType === StepType.Matching || props.stepType === StepType.Merging) { database = "final"; } else if (!props.isEditing && props.stepType === StepType.Mapping) { database = "staging"; } else if (props.isEditing) { database = props.editStepArtifactObject["sourceDatabase"] === "data-hub-FINAL" ? "final" : "staging"; } if (value && value.length > 2) { try { let data = { "referenceType": "collection", "entityTypeId": " ", "propertyPath": " ", "limit": 10, "dataType": "string", "pattern": value, }; const response = await axios.post(`/api/entitySearch/facet-values?database=${database}`, data); if (response.status === 200) { setCollectionOptions(response.data); } } catch (error) { console.error(error); handleError(error); } } else { setCollectionOptions([]); } }; const handleFocus = () => { setCollectionOptions([]); }; const handleTypeaheadChange = (data: any) => { if (data === " ") { setCollectionsTouched(false); } else { setCollectionsTouched(true); setCollections(data); if (props.isEditing && props.editStepArtifactObject.collection) { if (props.editStepArtifactObject.collection === data) { setCollectionsTouched(false); } } if (data.length > 0) { if (stepName) { setIsValid(true); props.setIsValid(true); } } else { setIsValid(false); props.setIsValid(false); } } }; const handleChange = (event) => { if (event.target.id === "name") { let isSpecialChars = false; if (event.target.value === " ") { setStepNameTouched(false); } else { setStepNameTouched(true); setStepName(event.target.value); //check value does not contain special chars and leads with a letter if (event.target.value !== "" && !(/^[a-zA-Z][a-zA-Z0-9\-_]*$/g.test(event.target.value))) { setInvalidChars(true); isSpecialChars = true; } else { setInvalidChars(false); } if (event.target.value.length > 0 && !isSpecialChars) { if (collections || srcQuery) { setIsValid(true); props.setIsValid(true); } } else { setIsValid(false); props.setIsValid(false); } } } if (event.target.id === "description") { if (event.target.value === " ") { setDescriptionTouched(false); } else { setDescriptionTouched(true); setDescription(event.target.value); if (props.isEditing && props.editStepArtifactObject.description) { if (event.target.value === props.editStepArtifactObject.description) { setDescriptionTouched(false); } } } } if (event.target.id === "srcQuery") { if (event.target.value === " ") { setSrcQueryTouched(false); } else { setSrcQueryTouched(true); setSrcQuery(event.target.value); if (event.target.value.length > 0) { if (stepName) { setIsValid(true); props.setIsValid(true); } } else { setIsValid(false); props.setIsValid(false); } } } if (event.target.id === "collList") { if (event.target.value === " ") { setCollectionsTouched(false); } else { setCollectionsTouched(true); setCollections(event.target.value); if (props.isEditing && props.editStepArtifactObject.collection) { if (props.editStepArtifactObject.collection === event.target.value) { setCollectionsTouched(false); } } if (event.target.value.length > 0) { if (stepName) { setIsValid(true); props.setIsValid(true); } } else { setIsValid(false); props.setIsValid(false); } } } if (event.target.id === "timestamp") { if (event.target.value === " ") { setTimestampTouched(false); } else { setTimestampTouched(true); setTimestamp(event.target.value); if (props.isEditing && props.editStepArtifactObject.timestamp) { if (event.target.value === props.editStepArtifactObject.timestamp) { setTimestampTouched(false); } } } } }; const handleSelectedSource = (event) => { if (event.target.value === " ") { setSelectedSourceTouched(false); } else { setSelectedSourceTouched(true); setSelectedSource(event.target.value); if (props.isEditing && event.target.value === props.editStepArtifactObject.selectedSource) { setSelectedSourceTouched(false); } if (event.target.value === "collection") { if (stepName && collections) { setIsValid(true); props.setIsValid(true); } else { setIsValid(false); props.setIsValid(false); } } else { if (stepName && srcQuery) { setIsValid(true); props.setIsValid(true); } else { setIsValid(false); props.setIsValid(false); } } } }; return ( <div className={styles.createEditStep}> {(props.stepType === StepType.Matching || props.stepType === StepType.Merging) ? curationOptions.activeStep.hasWarnings.length > 0 ? ( curationOptions.activeStep.hasWarnings.map((warning, index) => { let description; if (warning["message"].includes("target entity type")) { description = "Please remove target entity type from target collections"; } else if (warning["message"].includes("source collection")) { description= "Please remove source collection from target collections"; } else if (warning["message"].includes("temporal collection")) { description= "Please remove temporal collection from target collections"; } else { description = ""; } return ( <MLAlert id="step-warn" className={styles.alert} type="warning" showIcon key={warning["level"] + index} message={<div className={styles.alertMessage}>{warning["message"]}</div>} description={description} /> ); }) ) : null : null} <Form {...formItemLayout} onSubmit={handleSubmit} colon={false}> <Form.Item label={<span> Name:&nbsp;<span className={styles.asterisk}>*</span> &nbsp; </span>} labelAlign="left" validateStatus={(stepName || !isStepNameTouched) ? (invalidChars ? "error" : "") : "error"} help={invalidChars ? "Names must start with a letter and can contain letters, numbers, hyphens, and underscores only." : (stepName || !isStepNameTouched) ? "" : "Name is required"} > { tobeDisabled?<MLTooltip title={NewMatchTooltips.nameField} placement={"bottom"}> <Input id="name" placeholder="Enter name" value={stepName} onChange={handleChange} disabled={tobeDisabled} className={styles.input} onBlur={sendPayload} /></MLTooltip>:<Input id="name" placeholder="Enter name" value={stepName} onChange={handleChange} disabled={tobeDisabled} className={styles.input} onBlur={sendPayload} />}&nbsp;&nbsp; { props.stepType === StepType.Mapping ? <MLTooltip title={NewMapTooltips.name} placement={"right"}> <Icon type="question-circle" className={styles.questionCircle} theme="filled" /> </MLTooltip>: props.stepType === StepType.Matching ? <MLTooltip title={NewMatchTooltips.name} placement={"right"}> <Icon type="question-circle" className={styles.questionCircle} theme="filled" /> </MLTooltip>: <MLTooltip title={NewMergeTooltips.name} placement={"right"}> <Icon type="question-circle" className={styles.questionCircle} theme="filled" /> </MLTooltip> } </Form.Item> <Form.Item label={<span> Description: &nbsp; </span>} labelAlign="left"> <Input id="description" placeholder="Enter description" value={description} onChange={handleChange} disabled={props.canReadOnly && !props.canReadWrite} className={styles.input} onBlur={sendPayload} />&nbsp;&nbsp; { props.stepType === StepType.Mapping ? <MLTooltip title={NewMapTooltips.description} placement={"right"}> <Icon type="question-circle" className={styles.questionCircle} theme="filled" /> </MLTooltip>: props.stepType === StepType.Matching ? <MLTooltip title={NewMatchTooltips.description} placement={"right"}> <Icon type="question-circle" className={styles.questionCircle} theme="filled" /> </MLTooltip>: <MLTooltip title={NewMergeTooltips.description} placement={"right"}> <Icon type="question-circle" className={styles.questionCircle} theme="filled" /> </MLTooltip> } </Form.Item> <Form.Item label={<span> Source Query:&nbsp;<span className={styles.asterisk}>*</span> &nbsp; </span>} labelAlign="left" validateStatus={((collections && selectedSource === "collection") || (srcQuery && selectedSource !== "collection") || (!isSelectedSourceTouched && !isCollectionsTouched && !isSrcQueryTouched)) ? "" : "error"} help={((collections && selectedSource === "collection") || (srcQuery && selectedSource !== "collection") || (!isSelectedSourceTouched && !isCollectionsTouched && !isSrcQueryTouched)) ? "" : "Collection or Query is required"} > <Radio.Group id="srcType" options={srcTypeOptions} onChange={handleSelectedSource} value={selectedSource} disabled={!props.canReadWrite} > </Radio.Group> <span id={props.stepType !== StepType.Merging ? "radioCollectionPopover" : "radioCollectionMergePopover" }> <Popover content={collectionQueryInfo} trigger="hover" placement="left" > <Icon type="question-circle" className={styles.questionCircleCollection} theme="filled" data-testid="collectionTooltip"/> </Popover></span> <MLTooltip title={CommonStepTooltips.radioQuery} placement={"top"}> <Icon type="question-circle" className={styles.questionCircleQuery} theme="filled" data-testid="queryTooltip"/> </MLTooltip> {selectedSource === "collection" ? <div ><span className={styles.srcCollectionInput}><AutoComplete id="collList" //mode="tags" className={styles.input} dataSource={collectionOptions} aria-label="collection-input" placeholder= {<span>Enter collection name<Icon className={styles.searchIcon} type="search" theme="outlined"/></span>} value={collections} disabled={!props.canReadWrite} onSearch={handleSearch} onFocus= {handleFocus} onChange={handleTypeaheadChange} onBlur={sendPayload} > {/* {collectionsList} */} </AutoComplete>&nbsp;&nbsp;{props.canReadWrite ? <Icon className={styles.searchIcon} type="search" theme="outlined"/> : ""}</span></div> : <span><TextArea id="srcQuery" placeholder="Enter source query" value={srcQuery} onChange={handleChange} disabled={!props.canReadWrite} className={styles.input} onBlur={sendPayload} ></TextArea></span>} </Form.Item> {props.stepType === StepType.Merging ? <Form.Item label={<span> Timestamp Path: &nbsp; </span>} labelAlign="left" className={styles.timestamp}> <Input id="timestamp" placeholder="Enter path to the timestamp" value={timestamp} onChange={handleChange} disabled={props.canReadOnly && !props.canReadWrite} className={styles.input} onBlur={sendPayload} />&nbsp;&nbsp; <MLTooltip title={NewMergeTooltips.timestampPath} placement={"right"}> <Icon type="question-circle" className={styles.questionCircle} theme="filled" /> </MLTooltip> </Form.Item> : ""} <Form.Item className={styles.submitButtonsForm}> <div className={styles.submitButtons}> <MLButton data-testid={`${props.stepType}-dialog-cancel`} onClick={() => onCancel()}>Cancel</MLButton> &nbsp;&nbsp; {!props.canReadWrite?<MLTooltip title={NewMergeTooltips.missingPermission} placement={"bottomRight"}><span className={styles.disabledCursor}> <MLButton className={styles.disabledSaveButton} type="primary" htmlType="submit" disabled={true} data-testid={`${props.stepType}-dialog-save`} onClick={handleSubmit}>Save</MLButton></span></MLTooltip> :<MLButton type="primary" htmlType="submit" disabled={false} data-testid={`${props.stepType}-dialog-save`} onClick={handleSubmit} onFocus={sendPayload}>Save</MLButton>} </div> </Form.Item> </Form> </div> ); }; export default CreateEditStep;
the_stack
import * as console from './console' import * as timer from './timer' @external("env", "wasm_response_send") declare function wasm_response_send(buffer: ArrayBuffer, size: i32): void; @external("env", "wasm_register_resource") declare function wasm_register_resource(url: ArrayBuffer): void; @external("env", "wasm_post_request") declare function wasm_post_request(buffer: ArrayBuffer, size: i32): void; @external("env", "wasm_sub_event") declare function wasm_sub_event(url: ArrayBuffer): void; var COAP_GET = 1; var COAP_POST = 2; var COAP_PUT = 3; var COAP_DELETE = 4; var COAP_EVENT = COAP_DELETE + 2; /* CoAP response codes */ export enum CoAP_Status { NO_ERROR = 0, CREATED_2_01 = 65, /* CREATED */ DELETED_2_02 = 66, /* DELETED */ VALID_2_03 = 67, /* NOT_MODIFIED */ CHANGED_2_04 = 68, /* CHANGED */ CONTENT_2_05 = 69, /* OK */ CONTINUE_2_31 = 95, /* CONTINUE */ BAD_REQUEST_4_00 = 128, /* BAD_REQUEST */ UNAUTHORIZED_4_01 = 129, /* UNAUTHORIZED */ BAD_OPTION_4_02 = 130, /* BAD_OPTION */ FORBIDDEN_4_03 = 131, /* FORBIDDEN */ NOT_FOUND_4_04 = 132, /* NOT_FOUND */ METHOD_NOT_ALLOWED_4_05 = 133, /* METHOD_NOT_ALLOWED */ NOT_ACCEPTABLE_4_06 = 134, /* NOT_ACCEPTABLE */ PRECONDITION_FAILED_4_12 = 140, /* BAD_REQUEST */ REQUEST_ENTITY_TOO_LARGE_4_13 = 141, /* REQUEST_ENTITY_TOO_LARGE */ UNSUPPORTED_MEDIA_TYPE_4_15 = 143, /* UNSUPPORTED_MEDIA_TYPE */ INTERNAL_SERVER_ERROR_5_00 = 160, /* INTERNAL_SERVER_ERROR */ NOT_IMPLEMENTED_5_01 = 161, /* NOT_IMPLEMENTED */ BAD_GATEWAY_5_02 = 162, /* BAD_GATEWAY */ SERVICE_UNAVAILABLE_5_03 = 163, /* SERVICE_UNAVAILABLE */ GATEWAY_TIMEOUT_5_04 = 164, /* GATEWAY_TIMEOUT */ PROXYING_NOT_SUPPORTED_5_05 = 165, /* PROXYING_NOT_SUPPORTED */ /* Erbium errors */ MEMORY_ALLOCATION_ERROR = 192, PACKET_SERIALIZATION_ERROR, /* Erbium hooks */ MANUAL_RESPONSE, PING_RESPONSE }; var g_mid: i32 = 0; class wamr_request { mid: i32 = 0; url: string = ""; action: i32 = 0; fmt: i32 = 0; payload: ArrayBuffer; payload_len: i32 = 0; sender: i32 = 0; constructor(mid: i32, url: string, action: i32, fmt: i32, payload: ArrayBuffer, payload_len: number) { this.mid = mid; this.url = url; this.action = action; this.fmt = fmt; this.payload = payload; this.payload_len = i32(payload_len); } } class wamr_response { mid: i32 = 0; status: i32 = 0; fmt: i32 = 0; payload: ArrayBuffer | null; payload_len: i32 = 0; receiver: i32 = 0; constructor(mid: i32, status: i32, fmt: i32, payload: ArrayBuffer | null, payload_len: i32) { this.mid = mid; this.status = status; this.fmt = fmt; this.payload = payload; this.payload_len = payload_len; } set_status(status: number): void { this.status = i32(status); } set_payload(payload: ArrayBuffer, payload_len: number): void { this.payload = payload; this.payload_len = i32(payload_len); } } class wamr_resource { url: string; type: number; cb: request_handler_f; constructor(url: string, type: number, cb: request_handler_f) { this.url = url; this.type = type; this.cb = cb; } } function is_expire(trans: wamr_transaction, index: i32, array: Array<wamr_transaction>): bool { var now = timer.now(); var elapsed_ms = (now < trans.time) ? (now + (0xFFFFFFFF - trans.time) + 1) : (now - trans.time); return elapsed_ms >= TRANSACTION_TIMEOUT_MS; } function not_expire(trans: wamr_transaction, index: i32, array: Array<wamr_transaction>): bool { var now = timer.now(); var elapsed_ms = (now < trans.time) ? (now + (0xFFFFFFFF - trans.time) + 1) : (now - trans.time); return elapsed_ms >= TRANSACTION_TIMEOUT_MS; } function transaction_timeout_handler(): void { var now = timer.now(); var expired = transaction_list.filter(is_expire); transaction_list = transaction_list.filter(not_expire); expired.forEach(item => { item.cb(null); transaction_remove(item); }) if (transaction_list.length > 0) { var elpased_ms: number, ms_to_expiry: number; now = timer.now(); if (now < transaction_list[0].time) { elpased_ms = now + (0xFFFFFFFF - transaction_list[0].time) + 1; } else { elpased_ms = now - transaction_list[0].time; } ms_to_expiry = TRANSACTION_TIMEOUT_MS - elpased_ms; timer.timer_restart(g_trans_timer, ms_to_expiry); } else { timer.timer_cancel(g_trans_timer); } } function transaction_find(mid: number): wamr_transaction | null { for (let i = 0; i < transaction_list.length; i++) { if (transaction_list[i].mid == mid) return transaction_list[i]; } return null; } function transaction_add(trans: wamr_transaction): void { transaction_list.push(trans); if (transaction_list.length == 1) { g_trans_timer = timer.setTimeout( transaction_timeout_handler, TRANSACTION_TIMEOUT_MS ); } } function transaction_remove(trans: wamr_transaction): void { var index = transaction_list.indexOf(trans); transaction_list.splice(index, 1); } var transaction_list = new Array<wamr_transaction>(); class wamr_transaction { mid: number; time: number; cb: (resp: wamr_response | null) => void; constructor(mid: number, time: number, cb: (resp: wamr_response) => void) { this.mid = mid; this.time = time; this.cb = cb; } } var REQUEST_PACKET_FIX_PART_LEN = 18; var RESPONSE_PACKET_FIX_PART_LEN = 16; var TRANSACTION_TIMEOUT_MS = 5000; var g_trans_timer: timer.user_timer; var Reg_Event = 0; var Reg_Request = 1; function pack_request(req: wamr_request): DataView { var url_len = req.url.length + 1; var len = REQUEST_PACKET_FIX_PART_LEN + url_len + req.payload_len var buf = new ArrayBuffer(len); var dataview = new DataView(buf, 0, len); dataview.setUint8(0, 1); dataview.setUint8(1, u8(req.action)); dataview.setUint16(2, u16(req.fmt)); dataview.setUint32(4, req.mid); dataview.setUint32(8, req.sender); dataview.setUint16(12, u16(url_len)) dataview.setUint32(14, req.payload_len); var i = 0; for (i = 0; i < url_len - 1; i++) { dataview.setUint8(i + 18, u8(req.url.codePointAt(i))); } dataview.setUint8(i + 18, 0); var payload_view = new DataView(req.payload); for (i = 0; i < req.payload_len; i++) { dataview.setUint8(i + 18 + url_len, u8(payload_view.getUint8(i))); } return dataview; } function unpack_request(packet: ArrayBuffer, size: i32): wamr_request { var dataview = new DataView(packet, 0, size); if (dataview.getUint8(0) != 1) throw new Error("packet version mismatch"); if (size < REQUEST_PACKET_FIX_PART_LEN) throw new Error("packet size error"); var url_len = dataview.getUint16(12); var payload_len = dataview.getUint32(14); if (size != (REQUEST_PACKET_FIX_PART_LEN + url_len + payload_len)) throw new Error("packet size error"); var action = dataview.getUint8(1); var fmt = dataview.getUint16(2); var mid = dataview.getUint32(4); var sender = dataview.getUint32(8); var url = packet.slice(REQUEST_PACKET_FIX_PART_LEN, REQUEST_PACKET_FIX_PART_LEN + url_len - 1); var payload = packet.slice(REQUEST_PACKET_FIX_PART_LEN + url_len, REQUEST_PACKET_FIX_PART_LEN + url_len + payload_len); var req = new wamr_request(mid, String.UTF8.decode(url), action, fmt, payload, payload_len); req.sender = sender; return req; } function pack_response(resp: wamr_response): DataView { var len = RESPONSE_PACKET_FIX_PART_LEN + resp.payload_len var buf = new ArrayBuffer(len); var dataview = new DataView(buf, 0, len); dataview.setUint8(0, 1); dataview.setUint8(1, u8(resp.status)); dataview.setUint16(2, u16(resp.fmt)); dataview.setUint32(4, resp.mid); dataview.setUint32(8, resp.receiver); dataview.setUint32(12, resp.payload_len) if (resp.payload != null) { var payload_view = new DataView(resp.payload!); for (let i = 0; i < resp.payload_len; i++) { dataview.setUint8(i + 16, payload_view.getUint8(i)); } } return dataview; } function unpack_response(packet: ArrayBuffer, size: i32): wamr_response { var dataview = new DataView(packet, 0, size); if (dataview.getUint8(0) != 1) throw new Error("packet version mismatch"); if (size < RESPONSE_PACKET_FIX_PART_LEN) throw new Error("packet size error"); var payload_len = dataview.getUint32(12); if (size != RESPONSE_PACKET_FIX_PART_LEN + payload_len) throw new Error("packet size error"); var status = dataview.getUint8(1); var fmt = dataview.getUint16(2); var mid = dataview.getUint32(4); var receiver = dataview.getUint32(8); var payload = packet.slice(RESPONSE_PACKET_FIX_PART_LEN); var resp = new wamr_response(mid, status, fmt, payload, payload_len); resp.receiver = receiver; return resp; } function do_request(req: wamr_request, cb: (resp: wamr_response) => void): void { var trans = new wamr_transaction(req.mid, timer.now(), cb); var msg = pack_request(req); transaction_add(trans); wasm_post_request(msg.buffer, msg.byteLength); } function do_response(resp: wamr_response): void { var msg = pack_response(resp); wasm_response_send(msg.buffer, msg.byteLength); } var resource_list = new Array<wamr_resource>(); type request_handler_f = (req: wamr_request) => void; function registe_url_handler(url: string, cb: request_handler_f, type: number): void { for (let i = 0; i < resource_list.length; i++) { if (resource_list[i].type == type && resource_list[i].url == url) { resource_list[i].cb = cb; return; } } var res = new wamr_resource(url, type, cb); resource_list.push(res); if (type == Reg_Request) wasm_register_resource(String.UTF8.encode(url)); else wasm_sub_event(String.UTF8.encode(url)); } function is_event_type(req: wamr_request): bool { return req.action == COAP_EVENT; } function check_url_start(url: string, leading_str: string): bool { return url.split('/')[0] == leading_str.split('/')[0]; } /* User APIs below */ export function post(url: string, payload: ArrayBuffer, payload_len: number, tag: string, cb: (resp: wamr_response) => void): void { var req = new wamr_request(g_mid++, url, COAP_POST, 0, payload, payload_len); do_request(req, cb); } export function get(url: string, tag: string, cb: (resp: wamr_response) => void): void { var req = new wamr_request(g_mid++, url, COAP_GET, 0, new ArrayBuffer(0), 0); do_request(req, cb); } export function put(url: string, payload: ArrayBuffer, payload_len: number, tag: string, cb: (resp: wamr_response) => void): void { var req = new wamr_request(g_mid++, url, COAP_PUT, 0, payload, payload_len); do_request(req, cb); } export function del(url: string, tag: string, cb: (resp: wamr_response) => void): void { var req = new wamr_request(g_mid++, url, COAP_PUT, 0, new ArrayBuffer(0), 0); do_request(req, cb); } export function make_response_for_request(req: wamr_request): wamr_response { var resp = new wamr_response(req.mid, CoAP_Status.CONTENT_2_05, 0, null, 0); resp.receiver = req.sender; return resp; } export function api_response_send(resp: wamr_response): void { do_response(resp); } export function register_resource_handler(url: string, request_handle: request_handler_f): void { registe_url_handler(url, request_handle, Reg_Request); } export function publish_event(url: string, fmt: number, payload: ArrayBuffer, payload_len: number): void { var req = new wamr_request(g_mid++, url, COAP_EVENT, i32(fmt), payload, payload_len); var msg = pack_request(req); wasm_post_request(msg.buffer, msg.byteLength); } export function subscribe_event(url: string, cb: request_handler_f): void { registe_url_handler(url, cb, Reg_Event); } /* These two APIs are required by wamr runtime, use a wrapper to export them in the entry file e.g: import * as request from '.wamr_app_lib/request' // Your code here ... export function _on_request(buffer_offset: i32, size: i32): void { on_request(buffer_offset, size); } export function _on_response(buffer_offset: i32, size: i32): void { on_response(buffer_offset, size); } */ export function on_request(buffer_offset: i32, size: i32): void { var buffer = new ArrayBuffer(size); var dataview = new DataView(buffer); for (let i = 0; i < size; i++) { dataview.setUint8(i, load<i8>(buffer_offset + i, 0, 1)); } var req = unpack_request(buffer, size); var is_event = is_event_type(req); for (let i = 0; i < resource_list.length; i++) { if ((is_event && resource_list[i].type == Reg_Event) || (!is_event && resource_list[i].type == Reg_Request)) { if (check_url_start(req.url, resource_list[i].url)) { resource_list[i].cb(req); return; } } } console.log("on_request: exit. no service handler."); } export function on_response(buffer_offset: i32, size: i32): void { var buffer = new ArrayBuffer(size); var dataview = new DataView(buffer); for (let i = 0; i < size; i++) { dataview.setUint8(i, load<i8>(buffer_offset + i, 0, 1)); } var resp = unpack_response(buffer, size); var trans = transaction_find(resp.mid); if (trans != null) { if (transaction_list.indexOf(trans) == 0) { if (transaction_list.length >= 2) { var elpased_ms: number, ms_to_expiry: number; var now = timer.now(); if (now < transaction_list[1].time) { elpased_ms = now + (0xFFFFFFFF - transaction_list[1].time) + 1; } else { elpased_ms = now - transaction_list[1].time; } ms_to_expiry = TRANSACTION_TIMEOUT_MS - elpased_ms; timer.timer_restart(g_trans_timer, ms_to_expiry); } else { timer.timer_cancel(g_trans_timer); } } trans.cb(resp); } }
the_stack
import { expect } from "chai"; import fs from "fs/promises"; import path from "path"; import zlib from "zlib"; import crypto from "crypto"; export interface CommonTestExports { memory: WebAssembly.Memory; malloc: (len: number) => number; mallocFree: (ptr: number) => void; mallocInit: () => void; runtimeInit: () => void; runtimeCleanup: () => void; gHeap: () => number; gNil: () => number; gTrue: () => number; gFalse: () => number; strFrom32: (len: number, val: number) => number; strFrom64: (len: number, val: bigint) => number; strFrom128: (len: number, val1: bigint, val2: bigint) => number; strFromCodePoints: (ptr: number, len: number) => number; heapAlloc: ( heap: number, type: number, data1: number, data2: number ) => number; heapAllocError: (symbol: number, message: number) => number; } const enum SchemeType { Empty = 0, Nil = 1, Boolean = 2, Cons = 3, I64 = 4, F64 = 5, Symbol = 6, Str = 7, Char = 8, Env = 9, Special = 10, Builtin = 11, Lambda = 12, Error = 13, Values = 14, Vector = 15, Bytevector = 16, Cont = 17, BigInt = 18, Except = 19, ContProc = 20, MaxHeap = 20, Mask = 0x1f, } export function commonExportsFromInstance( instance: WebAssembly.Instance ): CommonTestExports { return { memory: instance.exports.memory as WebAssembly.Memory, malloc: instance.exports.malloc as (len: number) => number, mallocFree: instance.exports.mallocFree as (ptr: number) => void, mallocInit: instance.exports.mallocInit as () => void, runtimeInit: instance.exports.runtimeInit as () => void, runtimeCleanup: instance.exports.runtimeCleanup as () => void, gHeap: () => (instance.exports.gHeap as WebAssembly.Global).value as number, gNil: () => (instance.exports.gNil as WebAssembly.Global).value as number, gTrue: () => (instance.exports.gTrue as WebAssembly.Global).value as number, gFalse: () => (instance.exports.gFalse as WebAssembly.Global).value as number, strFrom32: instance.exports.strFrom32 as ( len: number, val: number ) => number, strFrom64: instance.exports.strFrom64 as ( len: number, val: bigint ) => number, strFrom128: instance.exports.strFrom128 as ( len: number, val1: bigint, val2: bigint ) => number, strFromCodePoints: instance.exports.strFromCodePoints as ( ptr: number, len: number ) => number, heapAlloc: instance.exports.heapAlloc as ( heap: number, type: number, data1: number, data2: number ) => number, heapAllocError: instance.exports.heapAllocError as ( symbol: number, message: number ) => number, }; } export interface IoModule extends Record<string, Function> { read: () => number; write: (ptr: number) => void; } export interface PortModule extends Record<string, Function> { close: (fd: number) => void; open: (name: number, mode: number) => number; } export interface ProcessModule extends Record<string, Function> { exit: (exitCode: number) => void; getEnvironmentVariable: (name: number) => number; getEnvironmentVariables: () => number; setEnvironmentVariable: (name: number, value: number) => void; commandLine: () => number; } export class ProcessTest { private exports_: CommonTestExports | undefined; private readonly env_: Map<string, string> = new Map(); public get exports(): CommonTestExports { if (!this.exports_) { throw new Error("Invalid Operation"); } return this.exports_; } public set exports(v: CommonTestExports) { this.exports_ = v; } exit(exitCode: number) { console.warn(`(exit ${exitCode})`); } getEnvironmentVariable(name: number) { if (this.exports_ === undefined) { return 0; } const str = getString(this.exports_, name); const value = this.env_.get(str); if (typeof value === "string") { return createHeapString(this.exports_, value); } else { return 0; } } getEnvironmentVariables() { if (this.exports_ === undefined) { return 0; } let tail = this.exports.gNil(); for (const entry of this.env_.entries()) { const item = this.exports_.heapAlloc( this.exports_.gHeap(), SchemeType.Cons, createHeapString(this.exports_, entry[0]), createHeapString(this.exports_, entry[1]) ); tail = this.exports_.heapAlloc( this.exports_.gHeap(), SchemeType.Cons, item, tail ); } return tail; } setEnvironmentVariable(name: number, value: number) { if (this.exports_ === undefined) { return; } this.env_.set( getString(this.exports_, name), getString(this.exports_, value) ); } commandLine(): number { if (this.exports_ === undefined) { return 0; } return this.exports_.heapAlloc( this.exports_.gHeap(), SchemeType.Cons, createHeapString(this.exports_, "scheme.wasm"), this.exports.gNil() ); } get module(): ProcessModule { return { exit: (exitCode) => this.exit(exitCode), getEnvironmentVariable: (name) => this.getEnvironmentVariable(name), getEnvironmentVariables: () => this.getEnvironmentVariables(), setEnvironmentVariable: (name, value) => this.setEnvironmentVariable(name, value), commandLine: () => this.commandLine(), }; } } export interface UnicodeModule extends Record<string, Function> { loadData: (block: number, ptr: number) => void; } export class TestUnicode { private exports_: CommonTestExports | undefined; private readonly unicodeData_: Record<number, ArrayBuffer> = {}; public get exports(): CommonTestExports { if (!this.exports_) { throw new Error("Invalid Operation"); } return this.exports_; } public set exports(v: CommonTestExports) { this.exports_ = v; } async loadUnicodeBlocks() { const fullpath = path.resolve(__dirname, "../dist/unicode/blocks.json.gz"); const compressed = await fs.readFile(fullpath); const decompressed = await new Promise<string>((resolve, reject) => { zlib.gunzip(compressed, (err, buf) => { if (err) { reject(err); } else { resolve(buf.toString("utf-8")); } }); }); const data = JSON.parse(decompressed); for (const key of Object.keys(data)) { const blockIndex = Number(key); if (isNaN(blockIndex)) { continue; } const blockData = Buffer.from(data[key], "base64"); this.unicodeData_[blockIndex] = blockData; } } loadData(block: number, ptr: number) { const data = this.unicodeData_[block]; if (!data) { throw new Error( `No unicode data for ${block.toString(16).padStart(4, "0")}` ); } pokeMemory(this.exports, ptr, this.unicodeData_[block]); } get module(): UnicodeModule { return { loadData: (block, ptr) => this.loadData(block, ptr), }; } } export interface FileModule extends Record<string, Function> { read: (filenamePtr: number) => number; } export interface TimeModule extends Record<string, Function> { current: () => number; } export async function loadWasm( modules: { io?: IoModule; port?: PortModule; process?: ProcessModule; unicode?: UnicodeModule; file?: FileModule; time?: TimeModule; } = {} ): Promise<WebAssembly.Instance> { const wasm = await fs.readFile("dist/test.wasm"); try { const imports: WebAssembly.Imports = {}; imports["io"] = modules.io || { read: () => { console.warn("READ"); return 0; }, write: (ptr: number) => { console.warn(`WRITE: 0x${ptr.toString(16).padStart(8, "0")}`); }, }; imports["port"] = modules.port || { close: (fd: number) => { console.warn(`(close-port ${fd})`); }, open: (name: number, mode: number) => { console.warn(`(open 0x${name.toString(16).padStart(8, "0")} ${mode})`); }, }; imports["process"] = modules.process || { exit: (exitCode: number) => { console.warn(`EXIT: ${exitCode}`); }, getEnvironmentVariable: (name: number) => { console.warn( `(get-environment-variable 0x${name.toString(16).padStart(8, "0")})` ); return 0; }, getEnvironmentVariables: () => { console.warn("(get-environment-variables)"); return 0; }, setEnvironmentVariable: (name: number, value: number) => { console.warn( `(set-environment-variable 0x${name .toString(16) .padStart(8, "0")} 0x${value.toString(16).padStart(8, "0")})` ); }, commandLine: () => { console.warn("(command-line)"); return; }, }; imports["unicode"] = modules.unicode || { loadData: (block: number, ptr: number) => { const blockPath = `../dist/unicode/${block .toString(16) .padStart(4, "0")}.bin`; throw new Error( `unicode.loadData not implemented, looking for ${blockPath}` ); }, }; imports["dbg"] = { data: (a: number, b: number, c: number) => { console.log(`${a}: ${b} #x${c.toString(16).padStart(5, "0")} `); }, }; imports["file"] = modules.file || { read: (filenamePtr: number) => { console.log(`file-read ${filenamePtr.toString(16)}`); return filenamePtr; }, }; imports["time"] = modules.time || { currentSecond: () => Date.now() / 1000, currentJiffy: () => Math.round(performance.now()), jiffiesPerSecond: () => 1000, }; const module = await WebAssembly.instantiate(wasm, imports); return module.instance; } catch (err) { console.error(err); throw err; } } export function pokeMemory( exports: CommonTestExports, ptr: number, data: ArrayBuffer ) { const byteArray = new Uint8Array(data); const view = new Uint8Array(exports.memory.buffer); view.set(byteArray, ptr); } export function createString(exports: CommonTestExports, str: string): number { const ptr = createStringImpl(exports, str); checkMemory(exports); return ptr; } export function createHeapError( exports: CommonTestExports, symbol: string, message: string ) { return exports.heapAllocError( createString(exports, symbol), createString(exports, message) ); } export function createStringImpl( exports: CommonTestExports, str: string ): number { const array = new TextEncoder().encode(str); if (array.byteLength > 16) { const codePoints = new Uint32Array( Array.from(str).map((el) => el.codePointAt(0) || 0xfffd) ); const byteArray = new Uint8Array(codePoints.buffer); const ptr = exports.malloc(codePoints.length * 4); const view = new Uint8Array(exports.memory.buffer); view.set(byteArray, ptr); const strPtr = exports.strFromCodePoints(ptr, codePoints.length); exports.mallocFree(ptr); return strPtr; } const extended = new Uint8Array(16); extended.set(array); if (array.byteLength <= 4) { const words = new Uint32Array(extended.buffer); return exports.strFrom32(array.byteLength, words[0]); } const big = new BigUint64Array(extended.buffer); if (array.byteLength <= 8) { return exports.strFrom64(array.byteLength, big[0]); } else { return exports.strFrom128(array.byteLength, big[0], big[1]); } } export function getString(exports: CommonTestExports, ptr: number): string { const view = new Uint8Array(exports.memory.buffer); const words = new Uint32Array(exports.memory.buffer); expect(ptr).to.be.greaterThanOrEqual( 32, `String ptr 0x${ptr.toString(16).padStart(8, "0")} is out of bounds (32 – ${ view.byteLength })` ); expect(ptr).to.be.lessThanOrEqual( view.byteLength - 8, `String ptr 0x${ptr.toString(16).padStart(8, "0")} is out of bounds (32 – ${ view.byteLength })` ); expect(ptr & 0xfffffff8).to.equal( ptr, `String ptr 0x${ptr.toString(16).padStart(8, "0")} is badly aligned` ); const len = words[ptr / 4]; return new TextDecoder().decode(view.slice(ptr + 4, ptr + 4 + len)); } export function createHeapSymbol( exports: CommonTestExports, str: string ): number { const ptr = createString(exports, str); return exports.heapAlloc(exports.gHeap(), SchemeType.Symbol, ptr, 0); } export function createHeapString( exports: CommonTestExports, str: string ): number { const ptr = createString(exports, str); return exports.heapAlloc(exports.gHeap(), SchemeType.Str, ptr, 0); } export function checkMemory( exports: CommonTestExports, checkForLeaks: boolean = false ) { const view = new Uint8Array(exports.memory.buffer); const words = new Uint32Array(exports.memory.buffer); // console.log(`${i.toString().padStart(2, "0")} Check Heap`); // check free list let offset = 8; let curr = words[offset]; expect(words[9]).to.equal( view.byteLength, "second word of malloc header should be size of memory" ); const allocations: { ptr: number; size: number }[] = []; // console.log("---------------"); while (curr != 0) { offset = curr / 4; const c_next = words[offset]; const c_size = words[offset + 1]; // console.log( // `Free list at ${curr}..${ // curr + c_size + 8 // } = {next: ${c_next}, size: ${c_size}}` // ); expect(c_size & 7).to.equal(0, "free block size should be divisible by 8"); if (c_next != 0) { expect(c_next).to.be.greaterThan( curr, "next should be greater than curr" ); expect(curr + c_size + 8).to.be.lessThanOrEqual( c_next, "next should be beyond curr + size + 8" ); expect(curr + c_size + 8).to.not.equal(c_next, "Failed merge!!"); } else { expect(curr + c_size + 8).to.be.lessThanOrEqual(view.byteLength); } // check for allocated blocks between curr + size + 8 and c_next let alloc = curr + c_size + 8; const limit = c_next ? c_next : view.byteLength; while (alloc < limit) { const hdr = words.slice(alloc / 4, (alloc + 8) / 4); const a_ptr = hdr[0]; const a_size = hdr[1]; // console.log( // `Alloc at ${alloc}..${ // alloc + a_size + 8 // } = {ptr: ${a_ptr}, size: ${a_size}}` // ); allocations.push({ ptr: alloc + 8, size: a_size }); alloc += a_size + 8; } curr = c_next; } if (allocations.length) { for (const { ptr, size } of allocations) { const hdr = words.slice((ptr - 8) / 4, ptr / 4); if (hdr[0] != ptr - 8 || hdr[1] != ((size + 7) & ~7)) { dumpAlloc(hdr, size, ptr); expect(hdr[0]).to.equal( ptr - 8, `next ptr should be self ref ${ptr}:(${size}) ${hdr[0]}:(${hdr[1]})` ); expect(hdr[1]).to.equal( (size + 7) & ~7, `size should be rounded to next multiple of 8 ${ptr}:(${size}) ${hdr[0]}:(${hdr[1]})` ); } if (checkForLeaks) { console.log( `Leaked alloc at ${ptr}..${ptr + size} = {ptr: ${ptr}, size: ${size}}` ); dumpAlloc(hdr, size, ptr); } } } if (checkForLeaks) { expect(allocations.length).to.equal(0, "There should be no allocations"); } function dumpAlloc(hdr: Uint32Array, size: number, ptr: number) { const slice = view.slice(ptr, ptr + size); console.log( `ptr: #x${hdr[0].toString(16).padStart(5, "0")}, size: ${hdr[1]}` ); for (let ii = 0; ii < size; ii += 16) { const line = Array.from(slice.slice(ii, Math.min(ii + 16, size))); const hexes = line.map((el) => el.toString(16).padStart(2, "0")); while (hexes.length < 16) { hexes.push("--"); } const chars = line.map((el) => el >= 0x20 && el < 0x80 ? String.fromCodePoint(el) : "." ); console.log( `${(ii + ptr).toString(16).padStart(5, "0")} ${hexes.join( " " )} ${chars.join("")}` ); } } } export function checkForLeaks(exports: CommonTestExports) { return checkMemory(exports, true); } export function dumpMemory(exports: CommonTestExports) { const view = new Uint8Array(exports.memory.buffer); const words = new Uint32Array(exports.memory.buffer); // check free list let offset = 8; let curr = words[offset]; const allocations: { ptr: number; size: number }[] = []; console.log("---------------"); while (curr != 0) { offset = curr / 4; const c_next = words[offset]; const c_size = words[offset + 1]; console.log( `Free list at ${curr}..${ curr + c_size + 8 } = {next: ${c_next}, size: ${c_size}}` ); expect(c_size & 7).to.equal(0, "free block size should be divisible by 8"); if (c_next != 0) { expect(c_next).to.be.greaterThan( curr, "next should be greater than curr" ); expect(curr + c_size + 8).to.be.lessThanOrEqual( c_next, "next should be beyond curr + size + 8" ); expect(curr + c_size + 8).to.not.equal(c_next, "Failed merge!!"); } else { expect(curr + c_size + 8).to.be.lessThanOrEqual(view.byteLength); } // check for allocated blocks between curr + size + 8 and c_next let alloc = curr + c_size + 8; const limit = c_next ? c_next : view.byteLength; while (alloc < limit) { const hdr = words.slice(alloc / 4, (alloc + 8) / 4); const a_ptr = hdr[0]; const a_size = hdr[1]; allocations.push({ ptr: alloc + 8, size: a_size }); alloc += a_size + 8; } curr = c_next; } if (allocations.length) { for (const { ptr, size } of allocations) { const hdr = words.slice((ptr - 8) / 4, ptr / 4); const slice = view.slice(ptr, ptr + size); console.log( `Alloc at ${ptr}..${ptr + size} = {ptr: ${ptr}, size: ${size}}` ); console.log(`ptr: ${hdr[0]}, size: ${hdr[1]}`); for (let ii = 0; ii < size; ii += 16) { const line = Array.from(slice.slice(ii, Math.min(ii + 16, size))); const hexes = line.map((el) => el.toString(16).padStart(2, "0")); while (hexes.length < 16) { hexes.push("--"); } const chars = line.map((el) => el >= 0x20 && el < 0x80 ? String.fromCodePoint(el) : "." ); console.log( `${(ii + ptr).toString(16).padStart(5, "0")} ${hexes.join( " " )} ${chars.join("")}` ); } } } } export class IoEvent { private _data?: string; private _type: "read" | "write"; constructor(type: "read" | "write", data?: string) { this._type = type; this._data = data; } public get type(): "read" | "write" { return this._type; } public set type(v: "read" | "write") { this._type = v; } public get data(): string | undefined { return this._data; } public set data(v: string | undefined) { this._data = v; } } export type IoEventHandler = (evt: IoEvent) => boolean; export class IoTest { private exports_: CommonTestExports | null = null; private readonly readEvents: IoEventHandler[] = []; private readonly writeEvents: IoEventHandler[] = []; constructor() {} get exports(): CommonTestExports | null { return this.exports_; } set exports(value: CommonTestExports | null) { this.exports_ = value; } addEventListener(type: "read" | "write", callback: IoEventHandler): void { if (type === "read") { this.readEvents.push(callback); } else { this.writeEvents.push(callback); } } removeEventListener(type: "read" | "write", callback: IoEventHandler): void { const list = type === "read" ? this.readEvents : this.writeEvents; const index = list.indexOf(callback); if (index >= 0) { list.splice(index, 1); } } read(): number { if (!this.exports_) { return 0; } const event = new IoEvent("read"); for (const handler of this.readEvents) { const res = handler(event); if (event.data != undefined) { return createString(this.exports_, event.data); } else if (res) { return 0; } } return 0; } write(str: number) { if (!this.exports_) { return; } const toWrite = getString(this.exports_, str); const event = new IoEvent("write", toWrite); for (const handler of this.writeEvents) { handler(event); } } get module(): IoModule { return { read: () => this.read(), write: (ptr) => this.write(ptr), }; } } export class FileTest { private exports_: CommonTestExports | null = null; private readonly promises_: Record<number, (ptr: number) => void> = {}; constructor() {} get exports(): CommonTestExports | null { return this.exports_; } set exports(value: CommonTestExports | null) { this.exports_ = value; } async waitFor(ms: number) { return new Promise((resolve) => setTimeout(resolve, ms)); } heapItem(ptr: number): Uint32Array { if (!this.exports_) { throw new Error("FileTest object not initialized"); } return new Uint32Array(this.exports_.memory.buffer.slice(ptr, ptr + 12)); } addImportPromise(ptr: number): Promise<number> { return new Promise((resolve) => (this.promises_[ptr] = resolve)); } isImportPromise(ptr: number) { const heapWords = this.heapItem(ptr); if ((heapWords[0] & SchemeType.Mask) != SchemeType.Cont) { return false; } const continuation = this.heapItem(heapWords[1]); return continuation[0] == 204; } pokeMemory(ptr: number, data: ArrayBuffer) { if (!this.exports_) { throw new Error("FileTest object not initialized"); } pokeMemory(this.exports_, ptr, data); } settleImportPromise(promise: number, value: number): boolean { for (const ptrStr of Object.keys(this.promises_)) { const ptr = Number(ptrStr); if (isNaN(ptr)) { continue; } if (!this.isImportPromise(ptr)) { console.error("Expecting Import promise"); } const heapWords = this.heapItem(ptr); const continuation = this.heapItem(heapWords[1]); if (continuation[2] === promise) { continuation[0] = 0; continuation[2] = value; this.pokeMemory(heapWords[1], continuation.buffer); const resolver = this.promises_[ptr]; delete this.promises_[ptr]; resolver(ptr); return true; } } return false; } doRead(filenamePtr: number): number { const word = new Uint32Array(crypto.randomBytes(8).buffer); const promise = word[0]; this.doReadImpl(promise, filenamePtr).catch((err) => console.error(err)); return promise; } async doReadImpl(promise: number, filenamePtr: number): Promise<void> { if (!this.exports_) { throw new Error("FileTest object not initialized"); } try { const filename = getString(this.exports_, filenamePtr); const fullpath = path.resolve(__dirname, "../src/scheme", filename); const response = await fs.readFile(fullpath, "utf-8"); while ( !this.settleImportPromise( promise, createHeapString(this.exports_, response) ) ) { await this.waitFor(100); } } catch (err) { console.error(err); this.settleImportPromise( promise, createHeapError( this.exports_, "file-read", err instanceof Error ? err.message : (err as any).toString() ) ); } } read(filenamePtr: number): number { return this.doRead(filenamePtr); } get module(): FileModule { return { read: (filenamePtr: number) => this.read(filenamePtr), }; } }
the_stack
import type { Rule } from 'eslint'; import type { ExportAllDeclaration, ExportNamedDeclaration, ExportSpecifier, ImportDeclaration, ImportSpecifier, } from 'estree'; type Node = ( | ImportDeclaration | ExportNamedDeclaration | ExportAllDeclaration ) & Rule.NodeParentExtension; type Package = 'foundations' | 'all'; const typographyObjChanges = ['body', 'headline', 'textSans', 'titlepiece']; const removedImports: Record<string, string[]> = { "'@guardian/source-foundations/utils'": ['InteractionModeEngine'], "'@guardian/src-foundations/size/global'": ['remSize', 'remIconSize'], "'@guardian/src-foundations/themes'": ['defaultTheme', 'brand', 'brandAlt'], "'@guardian/src-foundations'": ['palette'], "'@guardian/src-helpers'": [ 'storybookBackgrounds', 'ThemeName', 'svgBackgroundImage', ], }; const newThemeNames: Record<string, string> = { accordionDefault: 'accordionThemeDefault', buttonReaderRevenue: 'buttonThemeReaderRevenue', buttonReaderRevenueBrand: 'buttonThemeReaderRevenueBrand', buttonReaderRevenueBrandAlt: 'buttonThemeReaderRevenueBrandAlt', buttonBrand: 'buttonThemeBrand', buttonBrandAlt: 'buttonThemeBrandAlt', buttonDefault: 'buttonThemeDefault', checkboxBrand: 'checkboxThemeBrand', checkboxDefault: 'checkboxThemeDefault', choiceCardDefault: 'choiceCardThemeDefault', footerBrand: 'footerThemeBrand', labelDefault: 'labelThemeDefault', labelBrand: 'labelThemeBrand', linkBrand: 'linkThemeBrand', linkBrandAlt: 'linkThemeBrandAlt', linkDefault: 'linkThemeDefault', radioBrand: 'radioThemeBrand', radioDefault: 'radioThemeDefault', selectDefault: 'selectThemeDefault', textInputDefault: 'textInputThemeDefault', userFeedbackBrand: 'userFeedbackThemeBrand', userFeedbackDefault: 'userFeedbackThemeDefault', }; const capitalise = (str: string): string => str.charAt(0).toUpperCase() + str.slice(1); const getNewPackage = (oldPackage: string): string => { if (oldPackage === "'@guardian/src-foundations/themes'") { return "'@guardian/source-react-components'"; } else if (oldPackage.startsWith("'@guardian/src-foundations")) { return "'@guardian/source-foundations'"; } else { return "'@guardian/source-react-components'"; } }; const getRemovedExports = ( node: Node, ): ImportSpecifier[] | ExportSpecifier[] => { switch (node.type) { case 'ImportDeclaration': return node.specifiers.filter((i) => { const source = node.source.raw; if (!source || !Object.keys(removedImports).includes(source)) return false; const removedImportsForSource = removedImports[source]; return ( i.type === 'ImportSpecifier' && removedImportsForSource.includes(i.imported.name) ); }) as ImportSpecifier[]; case 'ExportNamedDeclaration': return node.specifiers.filter((i) => { const source = node.source?.raw; if (!source || !Object.keys(removedImports).includes(source)) return false; const removedImportsForSource = removedImports[source]; return removedImportsForSource.includes(i.exported.name); }); case 'ExportAllDeclaration': return []; } }; const getImportName = (i: ImportSpecifier | ExportSpecifier): string => { const imported = i.type === 'ImportSpecifier' ? i.imported.name : i.exported.name; const local = i.local.name; return imported === local ? imported : `${imported} as ${local}`; }; const getSpecifierName = (i: ImportSpecifier | ExportSpecifier): string => { return i.type === 'ImportSpecifier' ? i.imported.name : i.exported.name; }; const getRenameImportFixers = ( node: Node, removedExports: ImportSpecifier[] | ExportSpecifier[], fixer: Rule.RuleFixer, nodeSource: string, ): Rule.Fix[] => { const fixers: Rule.Fix[] = []; if (!node.source?.raw || node.type === 'ExportAllDeclaration') return fixers; // If anything has been removed then remove it from the fixed import // Also add a new line which imports the removed exports from the original source if (removedExports.length) { for (const i of removedExports) { if (!i.range) break; // Account for a possible comma after the import (e.g. import {one, two} from 'source') const end = i.range[1]; const comma = nodeSource.slice(end, end + 1); fixers.push(fixer.removeRange([i.range[0], comma ? end + 1 : end])); } const importsArray: string[] = []; for (const rExport of removedExports) { const newName = getImportName(rExport); importsArray.push(newName); } fixers.push( fixer.insertTextBeforeRange( node.range ?? [0, 0], `import { ${importsArray.join(', ')} } from ${ node.source.raw };\n`, ), ); } return fixers; }; const getMessage = ( newPackage: string, removedExports: ImportSpecifier[] | ExportSpecifier[], node: Node, ): string => { const importOrExport = node.type.startsWith('Export') ? 'export' : 'import'; const newPackageMessage = `@guardian/src-* packages are deprecated. ${capitalise( importOrExport, )} from ${newPackage} instead.`; if (node.type === 'ExportAllDeclaration') { return newPackageMessage; } const renamedExports: Array<[string, string]> = []; // Some of the typography obj exports have changed name if (node.source?.raw === "'@guardian/src-foundations/typography/obj'") { for (const i of node.specifiers) { if ( i.type === 'ImportNamespaceSpecifier' || i.type === 'ImportDefaultSpecifier' ) continue; const name = getSpecifierName(i); if (typographyObjChanges.includes(name)) { renamedExports.push([name, `${name}ObjectStyles`]); } } } // Some of the theme exports have changed name for (const i of node.specifiers) { if ( i.type === 'ImportNamespaceSpecifier' || i.type === 'ImportDefaultSpecifier' ) continue; const name = getSpecifierName(i); if (name in newThemeNames) { renamedExports.push([name, `${newThemeNames[name]}`]); } } let renamedExportsMessage = ''; if (renamedExports.length) { renamedExportsMessage = `The following export(s) have been renamed [from -> to]: ${renamedExports .map(([oldName, newName]) => `${oldName} -> ${newName}`) .join(', ')}`; } if (!removedExports.length) { return renamedExportsMessage ? `${newPackageMessage}\n${renamedExportsMessage}` : newPackageMessage; } const totalImports = node.specifiers.length; const removedExportsArray: string[] = []; for (const rExport of removedExports) { removedExportsArray.push( rExport.type === 'ImportSpecifier' ? rExport.imported.name : rExport.exported.name, ); } const removedExportsMessage = `The following export(s) have been removed: ${removedExportsArray.join( ', ', )}.`; if (totalImports === removedExports.length) { return removedExportsMessage; } else { return [newPackageMessage, removedExportsMessage, renamedExportsMessage] .filter((s) => !!s) .join('\n'); } }; const relevantImportSource = (importSource: string, pkg: Package): boolean => { if ( pkg === 'foundations' && importSource.startsWith("'@guardian/src-foundations") ) return true; if (pkg === 'all' && importSource.startsWith("'@guardian/src-")) return true; return false; }; const createReport = (context: Rule.RuleContext, node: Node, pkg: Package) => { const importSource = node.source?.raw; if (!importSource || !relevantImportSource(importSource, pkg)) return; const newPackage = getNewPackage(importSource); // Check if the export statement is exporting everything // If so, we won't autofix if (node.type === 'ExportAllDeclaration') { return context.report({ node, message: getMessage(newPackage, [], node), }); } // Check if the import statement contains any all or default imports // If so, we won't autofix const nonNamedImports = node.type === 'ImportDeclaration' && !node.specifiers.every((s) => s.type === 'ImportSpecifier'); if (nonNamedImports) { return context.report({ node, message: getMessage(newPackage, [], node), }); } // Some exports are no longer available from the new packages // We need to account for these const removedExports = getRemovedExports(node); const nodeSource = context.getSourceCode().getText(node); return context.report({ node, message: getMessage(newPackage, removedExports, node), fix: (fixer) => { // If all of the exports have been removed then don't autofix return node.specifiers.length === removedExports.length ? null : [ ...getRenameImportFixers( node, removedExports, fixer, nodeSource, ), fixer.replaceTextRange( node.source?.range ?? [0, 0], newPackage, ), ]; }, }); }; export const validImportPath: Rule.RuleModule = { meta: { type: 'problem', docs: { description: 'Get Source imports from v4 packages', category: 'Deprecated', url: 'https://github.com/guardian/source', }, fixable: 'code', schema: [], }, create(context: Rule.RuleContext): Rule.RuleListener { return { ImportDeclaration(node) { return createReport(context, node, 'all'); }, ExportNamedDeclaration(node) { // e.g. export {Props} from '@guardian/src-helpers' return createReport(context, node, 'all'); }, ExportAllDeclaration(node) { // e.g. export * from '@guardian/src-foundations'` return createReport(context, node, 'all'); }, }; }, }; export const validFoundationsImportPath: Rule.RuleModule = { meta: { type: 'problem', docs: { description: 'Get Source imports from v4 packages', category: 'Deprecated', url: 'https://github.com/guardian/source', }, fixable: 'code', schema: [], }, create(context: Rule.RuleContext): Rule.RuleListener { return { ImportDeclaration(node) { return createReport(context, node, 'foundations'); }, ExportNamedDeclaration(node) { // e.g. export {Props} from '@guardian/src-helpers' return createReport(context, node, 'foundations'); }, ExportAllDeclaration(node) { // e.g. export * from '@guardian/src-foundations'` return createReport(context, node, 'foundations'); }, }; }, };
the_stack
import * as assert from "assert"; import * as Utils from "./misc/Utils"; import { ANTLRErrorListener } from "./ANTLRErrorListener"; import { ANTLRErrorStrategy } from "./ANTLRErrorStrategy"; import { ATN } from "./atn/ATN"; import { ATNDeserializationOptions } from "./atn/ATNDeserializationOptions"; import { ATNDeserializer } from "./atn/ATNDeserializer"; import { ATNSimulator } from "./atn/ATNSimulator"; import { ATNState } from "./atn/ATNState"; import { DefaultErrorStrategy } from "./DefaultErrorStrategy"; import { DFA } from "./dfa/DFA"; import { ErrorNode } from "./tree/ErrorNode"; import { IntegerStack } from "./misc/IntegerStack"; import { IntervalSet } from "./misc/IntervalSet"; import { IntStream } from "./IntStream"; import { Lexer } from "./Lexer"; import { Override, NotNull, Nullable } from "./Decorators"; import { ParseInfo } from "./atn/ParseInfo"; import { ParserATNSimulator } from "./atn/ParserATNSimulator"; import { ParserErrorListener } from "./ParserErrorListener"; import { ParserRuleContext } from "./ParserRuleContext"; import { ParseTreeListener } from "./tree/ParseTreeListener"; import { ParseTreePattern } from "./tree/pattern/ParseTreePattern"; import { ProxyParserErrorListener } from "./ProxyParserErrorListener"; import { RecognitionException } from "./RecognitionException"; import { Recognizer } from "./Recognizer"; import { RuleContext } from "./RuleContext"; import { RuleTransition } from "./atn/RuleTransition"; import { TerminalNode } from "./tree/TerminalNode"; import { Token } from "./Token"; import { TokenFactory } from "./TokenFactory"; import { TokenSource } from "./TokenSource"; import { TokenStream } from "./TokenStream"; class TraceListener implements ParseTreeListener { constructor(private ruleNames: string[], private tokenStream: TokenStream) { } @Override public enterEveryRule(ctx: ParserRuleContext): void { console.log("enter " + this.ruleNames[ctx.ruleIndex] + ", LT(1)=" + this.tokenStream.LT(1).text); } @Override public exitEveryRule(ctx: ParserRuleContext): void { console.log("exit " + this.ruleNames[ctx.ruleIndex] + ", LT(1)=" + this.tokenStream.LT(1).text); } @Override public visitErrorNode(node: ErrorNode): void { // intentionally empty } @Override public visitTerminal(node: TerminalNode): void { let parent = node.parent!.ruleContext; let token: Token = node.symbol; console.log("consume " + token + " rule " + this.ruleNames[parent.ruleIndex]); } } /** This is all the parsing support code essentially; most of it is error recovery stuff. */ export abstract class Parser extends Recognizer<Token, ParserATNSimulator> { /** * This field maps from the serialized ATN string to the deserialized {@link ATN} with * bypass alternatives. * * @see ATNDeserializationOptions.isGenerateRuleBypassTransitions */ private static readonly bypassAltsAtnCache = new Map<string, ATN>(); /** * The error handling strategy for the parser. The default value is a new * instance of {@link DefaultErrorStrategy}. * * @see #getErrorHandler * @see #setErrorHandler */ @NotNull protected _errHandler: ANTLRErrorStrategy = new DefaultErrorStrategy(); /** * The input stream. * * @see #getInputStream * @see #setInputStream */ protected _input!: TokenStream; protected readonly _precedenceStack: IntegerStack = new IntegerStack(); /** * The {@link ParserRuleContext} object for the currently executing rule. * * This is always non-undefined during the parsing process. */ protected _ctx!: ParserRuleContext; /** * Specifies whether or not the parser should construct a parse tree during * the parsing process. The default value is `true`. * * @see `buildParseTree` */ private _buildParseTrees: boolean = true; /** * When {@link #setTrace}`(true)` is called, a reference to the * {@link TraceListener} is stored here so it can be easily removed in a * later call to {@link #setTrace}`(false)`. The listener itself is * implemented as a parser listener so this field is not directly used by * other parser methods. */ private _tracer: TraceListener | undefined; /** * The list of {@link ParseTreeListener} listeners registered to receive * events during the parse. * * @see #addParseListener */ protected _parseListeners: ParseTreeListener[] = []; /** * The number of syntax errors reported during parsing. This value is * incremented each time {@link #notifyErrorListeners} is called. */ protected _syntaxErrors: number = 0; /** Indicates parser has match()ed EOF token. See {@link #exitRule()}. */ protected matchedEOF: boolean = false; constructor(input: TokenStream) { super(); this._precedenceStack.push(0); this.inputStream = input; } /** reset the parser's state */ public reset(): void; public reset(resetInput: boolean): void; public reset(resetInput?: boolean): void { // Note: this method executes when not parsing, so _ctx can be undefined if (resetInput === undefined || resetInput) { this.inputStream.seek(0); } this._errHandler.reset(this); this._ctx = undefined as any; this._syntaxErrors = 0; this.matchedEOF = false; this.isTrace = false; this._precedenceStack.clear(); this._precedenceStack.push(0); let interpreter: ATNSimulator = this.interpreter; if (interpreter != null) { interpreter.reset(); } } /** * Match current input symbol against `ttype`. If the symbol type * matches, {@link ANTLRErrorStrategy#reportMatch} and {@link #consume} are * called to complete the match process. * * If the symbol type does not match, * {@link ANTLRErrorStrategy#recoverInline} is called on the current error * strategy to attempt recovery. If {@link #getBuildParseTree} is * `true` and the token index of the symbol returned by * {@link ANTLRErrorStrategy#recoverInline} is -1, the symbol is added to * the parse tree by calling {@link #createErrorNode(ParserRuleContext, Token)} then * {@link ParserRuleContext#addErrorNode(ErrorNode)}. * * @param ttype the token type to match * @returns the matched symbol * @ if the current input symbol did not match * `ttype` and the error strategy could not recover from the * mismatched symbol */ @NotNull public match(ttype: number): Token { let t: Token = this.currentToken; if (t.type === ttype) { if (ttype === Token.EOF) { this.matchedEOF = true; } this._errHandler.reportMatch(this); this.consume(); } else { t = this._errHandler.recoverInline(this); if (this._buildParseTrees && t.tokenIndex === -1) { // we must have conjured up a new token during single token insertion // if it's not the current symbol this._ctx.addErrorNode(this.createErrorNode(this._ctx, t)); } } return t; } /** * Match current input symbol as a wildcard. If the symbol type matches * (i.e. has a value greater than 0), {@link ANTLRErrorStrategy#reportMatch} * and {@link #consume} are called to complete the match process. * * If the symbol type does not match, * {@link ANTLRErrorStrategy#recoverInline} is called on the current error * strategy to attempt recovery. If {@link #getBuildParseTree} is * `true` and the token index of the symbol returned by * {@link ANTLRErrorStrategy#recoverInline} is -1, the symbol is added to * the parse tree by calling {@link Parser#createErrorNode(ParserRuleContext, Token)} then * {@link ParserRuleContext#addErrorNode(ErrorNode)}. * * @returns the matched symbol * @ if the current input symbol did not match * a wildcard and the error strategy could not recover from the mismatched * symbol */ @NotNull public matchWildcard(): Token { let t: Token = this.currentToken; if (t.type > 0) { this._errHandler.reportMatch(this); this.consume(); } else { t = this._errHandler.recoverInline(this); if (this._buildParseTrees && t.tokenIndex === -1) { // we must have conjured up a new token during single token insertion // if it's not the current symbol this._ctx.addErrorNode(this.createErrorNode(this._ctx, t)); } } return t; } /** * Track the {@link ParserRuleContext} objects during the parse and hook * them up using the {@link ParserRuleContext#children} list so that it * forms a parse tree. The {@link ParserRuleContext} returned from the start * rule represents the root of the parse tree. * * Note that if we are not building parse trees, rule contexts only point * upwards. When a rule exits, it returns the context but that gets garbage * collected if nobody holds a reference. It points upwards but nobody * points at it. * * When we build parse trees, we are adding all of these contexts to * {@link ParserRuleContext#children} list. Contexts are then not candidates * for garbage collection. */ set buildParseTree(buildParseTrees: boolean) { this._buildParseTrees = buildParseTrees; } /** * Gets whether or not a complete parse tree will be constructed while * parsing. This property is `true` for a newly constructed parser. * * @returns `true` if a complete parse tree will be constructed while * parsing, otherwise `false` */ get buildParseTree(): boolean { return this._buildParseTrees; } @NotNull public getParseListeners(): ParseTreeListener[] { return this._parseListeners; } /** * Registers `listener` to receive events during the parsing process. * * To support output-preserving grammar transformations (including but not * limited to left-recursion removal, automated left-factoring, and * optimized code generation), calls to listener methods during the parse * may differ substantially from calls made by * {@link ParseTreeWalker#DEFAULT} used after the parse is complete. In * particular, rule entry and exit events may occur in a different order * during the parse than after the parser. In addition, calls to certain * rule entry methods may be omitted. * * With the following specific exceptions, calls to listener events are * *deterministic*, i.e. for identical input the calls to listener * methods will be the same. * * * Alterations to the grammar used to generate code may change the * behavior of the listener calls. * * Alterations to the command line options passed to ANTLR 4 when * generating the parser may change the behavior of the listener calls. * * Changing the version of the ANTLR Tool used to generate the parser * may change the behavior of the listener calls. * * @param listener the listener to add * * @throws {@link TypeError} if `listener` is `undefined` */ public addParseListener(@NotNull listener: ParseTreeListener): void { if (listener == null) { throw new TypeError("listener cannot be null"); } this._parseListeners.push(listener); } /** * Remove `listener` from the list of parse listeners. * * If `listener` is `undefined` or has not been added as a parse * listener, this method does nothing. * * @see #addParseListener * * @param listener the listener to remove */ public removeParseListener(listener: ParseTreeListener): void { let index = this._parseListeners.findIndex((l) => l === listener); if (index !== -1) { this._parseListeners.splice(index, 1); } } /** * Remove all parse listeners. * * @see #addParseListener */ public removeParseListeners(): void { this._parseListeners.length = 0; } /** * Notify any parse listeners of an enter rule event. * * @see #addParseListener */ protected triggerEnterRuleEvent(): void { for (let listener of this._parseListeners) { if (listener.enterEveryRule) { listener.enterEveryRule(this._ctx); } this._ctx.enterRule(listener); } } /** * Notify any parse listeners of an exit rule event. * * @see #addParseListener */ protected triggerExitRuleEvent(): void { // reverse order walk of listeners for (let i = this._parseListeners.length - 1; i >= 0; i--) { let listener: ParseTreeListener = this._parseListeners[i]; this._ctx.exitRule(listener); if (listener.exitEveryRule) { listener.exitEveryRule(this._ctx); } } } /** * Gets the number of syntax errors reported during parsing. This value is * incremented each time {@link #notifyErrorListeners} is called. * * @see #notifyErrorListeners */ get numberOfSyntaxErrors(): number { return this._syntaxErrors; } get tokenFactory(): TokenFactory { return this._input.tokenSource.tokenFactory; } /** * The ATN with bypass alternatives is expensive to create so we create it * lazily. * * @ if the current parser does not * implement the `serializedATN` property. */ @NotNull public getATNWithBypassAlts(): ATN { let serializedAtn: string = this.serializedATN; if (serializedAtn == null) { throw new Error("The current parser does not support an ATN with bypass alternatives."); } let result = Parser.bypassAltsAtnCache.get(serializedAtn); if (result == null) { let deserializationOptions: ATNDeserializationOptions = new ATNDeserializationOptions(); deserializationOptions.isGenerateRuleBypassTransitions = true; result = new ATNDeserializer(deserializationOptions).deserialize(Utils.toCharArray(serializedAtn)); Parser.bypassAltsAtnCache.set(serializedAtn, result); } return result; } /** * The preferred method of getting a tree pattern. For example, here's a * sample use: * * ``` * let t: ParseTree = parser.expr(); * let p: ParseTreePattern = await parser.compileParseTreePattern("<ID>+0", MyParser.RULE_expr); * let m: ParseTreeMatch = p.match(t); * let id: string = m.get("ID"); * ``` */ public compileParseTreePattern(pattern: string, patternRuleIndex: number): Promise<ParseTreePattern>; /** * The same as {@link #compileParseTreePattern(String, int)} but specify a * {@link Lexer} rather than trying to deduce it from this parser. */ public compileParseTreePattern(pattern: string, patternRuleIndex: number, lexer?: Lexer): Promise<ParseTreePattern>; public async compileParseTreePattern(pattern: string, patternRuleIndex: number, lexer?: Lexer): Promise<ParseTreePattern> { if (!lexer) { if (this.inputStream) { let tokenSource = this.inputStream.tokenSource; if (tokenSource instanceof Lexer) { lexer = tokenSource; } } if (!lexer) { throw new Error("Parser can't discover a lexer to use"); } } let currentLexer = lexer; let m = await import("./tree/pattern/ParseTreePatternMatcher"); let matcher = new m.ParseTreePatternMatcher(currentLexer, this); return matcher.compile(pattern, patternRuleIndex); } @NotNull get errorHandler(): ANTLRErrorStrategy { return this._errHandler; } set errorHandler(@NotNull handler: ANTLRErrorStrategy) { this._errHandler = handler; } @Override get inputStream(): TokenStream { return this._input; } /** Set the token stream and reset the parser. */ set inputStream(input: TokenStream) { this.reset(false); this._input = input; } /** Match needs to return the current input symbol, which gets put * into the label for the associated token ref; e.g., x=ID. */ @NotNull get currentToken(): Token { return this._input.LT(1); } public notifyErrorListeners(/*@NotNull*/ msg: string): void; public notifyErrorListeners(/*@NotNull*/ msg: string, /*@NotNull*/ offendingToken: Token | null, e: RecognitionException | undefined): void; public notifyErrorListeners(msg: string, offendingToken?: Token | null, e?: RecognitionException | undefined): void { if (offendingToken === undefined) { offendingToken = this.currentToken; } else if (offendingToken === null) { offendingToken = undefined; } this._syntaxErrors++; let line: number = -1; let charPositionInLine: number = -1; if (offendingToken != null) { line = offendingToken.line; charPositionInLine = offendingToken.charPositionInLine; } let listener = this.getErrorListenerDispatch(); if (listener.syntaxError) { listener.syntaxError(this, offendingToken, line, charPositionInLine, msg, e); } } /** * Consume and return the [current symbol](`currentToken`). * * E.g., given the following input with `A` being the current * lookahead symbol, this function moves the cursor to `B` and returns * `A`. * * ``` * A B * ^ * ``` * * If the parser is not in error recovery mode, the consumed symbol is added * to the parse tree using {@link ParserRuleContext#addChild(TerminalNode)}, and * {@link ParseTreeListener#visitTerminal} is called on any parse listeners. * If the parser *is* in error recovery mode, the consumed symbol is * added to the parse tree using {@link #createErrorNode(ParserRuleContext, Token)} then * {@link ParserRuleContext#addErrorNode(ErrorNode)} and * {@link ParseTreeListener#visitErrorNode} is called on any parse * listeners. */ public consume(): Token { let o: Token = this.currentToken; if (o.type !== Parser.EOF) { this.inputStream.consume(); } let hasListener: boolean = this._parseListeners.length !== 0; if (this._buildParseTrees || hasListener) { if (this._errHandler.inErrorRecoveryMode(this)) { let node: ErrorNode = this._ctx.addErrorNode(this.createErrorNode(this._ctx, o)); if (hasListener) { for (let listener of this._parseListeners) { if (listener.visitErrorNode) { listener.visitErrorNode(node); } } } } else { let node: TerminalNode = this.createTerminalNode(this._ctx, o); this._ctx.addChild(node); if (hasListener) { for (let listener of this._parseListeners) { if (listener.visitTerminal) { listener.visitTerminal(node); } } } } } return o; } /** * How to create a token leaf node associated with a parent. * Typically, the terminal node to create is not a function of the parent. * * @since 4.7 */ public createTerminalNode(parent: ParserRuleContext, t: Token): TerminalNode { return new TerminalNode(t); } /** * How to create an error node, given a token, associated with a parent. * Typically, the error node to create is not a function of the parent. * * @since 4.7 */ public createErrorNode(parent: ParserRuleContext, t: Token): ErrorNode { return new ErrorNode(t); } protected addContextToParseTree(): void { let parent = this._ctx._parent as ParserRuleContext | undefined; // add current context to parent if we have a parent if (parent != null) { parent.addChild(this._ctx); } } /** * Always called by generated parsers upon entry to a rule. Access field * {@link #_ctx} get the current context. */ public enterRule(@NotNull localctx: ParserRuleContext, state: number, ruleIndex: number): void { this.state = state; this._ctx = localctx; this._ctx._start = this._input.LT(1); if (this._buildParseTrees) { this.addContextToParseTree(); } this.triggerEnterRuleEvent(); } public enterLeftFactoredRule(localctx: ParserRuleContext, state: number, ruleIndex: number): void { this.state = state; if (this._buildParseTrees) { let factoredContext = this._ctx.getChild(this._ctx.childCount - 1) as ParserRuleContext; this._ctx.removeLastChild(); factoredContext._parent = localctx; localctx.addChild(factoredContext); } this._ctx = localctx; this._ctx._start = this._input.LT(1); if (this._buildParseTrees) { this.addContextToParseTree(); } this.triggerEnterRuleEvent(); } public exitRule(): void { if (this.matchedEOF) { // if we have matched EOF, it cannot consume past EOF so we use LT(1) here this._ctx._stop = this._input.LT(1); // LT(1) will be end of file } else { this._ctx._stop = this._input.tryLT(-1); // stop node is what we just matched } // trigger event on _ctx, before it reverts to parent this.triggerExitRuleEvent(); this.state = this._ctx.invokingState; this._ctx = this._ctx._parent as ParserRuleContext; } public enterOuterAlt(localctx: ParserRuleContext, altNum: number): void { localctx.altNumber = altNum; // if we have new localctx, make sure we replace existing ctx // that is previous child of parse tree if (this._buildParseTrees && this._ctx !== localctx) { let parent = this._ctx._parent as ParserRuleContext | undefined; if (parent != null) { parent.removeLastChild(); parent.addChild(localctx); } } this._ctx = localctx; } /** * Get the precedence level for the top-most precedence rule. * * @returns The precedence level for the top-most precedence rule, or -1 if * the parser context is not nested within a precedence rule. */ get precedence(): number { if (this._precedenceStack.isEmpty) { return -1; } return this._precedenceStack.peek(); } public enterRecursionRule(localctx: ParserRuleContext, state: number, ruleIndex: number, precedence: number): void { this.state = state; this._precedenceStack.push(precedence); this._ctx = localctx; this._ctx._start = this._input.LT(1); this.triggerEnterRuleEvent(); // simulates rule entry for left-recursive rules } /** Like {@link #enterRule} but for recursive rules. * Make the current context the child of the incoming localctx. */ public pushNewRecursionContext(localctx: ParserRuleContext, state: number, ruleIndex: number): void { let previous: ParserRuleContext = this._ctx; previous._parent = localctx; previous.invokingState = state; previous._stop = this._input.tryLT(-1); this._ctx = localctx; this._ctx._start = previous._start; if (this._buildParseTrees) { this._ctx.addChild(previous); } this.triggerEnterRuleEvent(); // simulates rule entry for left-recursive rules } public unrollRecursionContexts(_parentctx: ParserRuleContext): void { this._precedenceStack.pop(); this._ctx._stop = this._input.tryLT(-1); let retctx: ParserRuleContext = this._ctx; // save current ctx (return value) // unroll so _ctx is as it was before call to recursive method if (this._parseListeners.length > 0) { while (this._ctx !== _parentctx) { this.triggerExitRuleEvent(); this._ctx = this._ctx._parent as ParserRuleContext; } } else { this._ctx = _parentctx; } // hook into tree retctx._parent = _parentctx; if (this._buildParseTrees && _parentctx != null) { // add return ctx into invoking rule's tree _parentctx.addChild(retctx); } } public getInvokingContext(ruleIndex: number): ParserRuleContext | undefined { let p = this._ctx; while (p && p.ruleIndex !== ruleIndex) { p = p._parent as ParserRuleContext; } return p; } get context(): ParserRuleContext { return this._ctx; } set context(ctx: ParserRuleContext) { this._ctx = ctx; } @Override public precpred(@Nullable localctx: RuleContext, precedence: number): boolean { return precedence >= this._precedenceStack.peek(); } @Override public getErrorListenerDispatch(): ParserErrorListener { return new ProxyParserErrorListener(this.getErrorListeners()); } public inContext(context: string): boolean { // TODO: useful in parser? return false; } /** * Checks whether or not `symbol` can follow the current state in the * ATN. The behavior of this method is equivalent to the following, but is * implemented such that the complete context-sensitive follow set does not * need to be explicitly constructed. * * ``` * return getExpectedTokens().contains(symbol); * ``` * * @param symbol the symbol type to check * @returns `true` if `symbol` can follow the current state in * the ATN, otherwise `false`. */ public isExpectedToken(symbol: number): boolean { // return interpreter.atn.nextTokens(_ctx); let atn: ATN = this.interpreter.atn; let ctx: ParserRuleContext = this._ctx; let s: ATNState = atn.states[this.state]; let following: IntervalSet = atn.nextTokens(s); if (following.contains(symbol)) { return true; } // System.out.println("following "+s+"="+following); if (!following.contains(Token.EPSILON)) { return false; } while (ctx != null && ctx.invokingState >= 0 && following.contains(Token.EPSILON)) { let invokingState: ATNState = atn.states[ctx.invokingState]; let rt = invokingState.transition(0) as RuleTransition; following = atn.nextTokens(rt.followState); if (following.contains(symbol)) { return true; } ctx = ctx._parent as ParserRuleContext; } if (following.contains(Token.EPSILON) && symbol === Token.EOF) { return true; } return false; } get isMatchedEOF(): boolean { return this.matchedEOF; } /** * Computes the set of input symbols which could follow the current parser * state and context, as given by {@link #getState} and {@link #getContext}, * respectively. * * @see ATN#getExpectedTokens(int, RuleContext) */ @NotNull public getExpectedTokens(): IntervalSet { return this.atn.getExpectedTokens(this.state, this.context); } @NotNull public getExpectedTokensWithinCurrentRule(): IntervalSet { let atn: ATN = this.interpreter.atn; let s: ATNState = atn.states[this.state]; return atn.nextTokens(s); } /** Get a rule's index (i.e., `RULE_ruleName` field) or -1 if not found. */ public getRuleIndex(ruleName: string): number { let ruleIndex = this.getRuleIndexMap().get(ruleName); if (ruleIndex != null) { return ruleIndex; } return -1; } get ruleContext(): ParserRuleContext { return this._ctx; } /** Return List&lt;String&gt; of the rule names in your parser instance * leading up to a call to the current rule. You could override if * you want more details such as the file/line info of where * in the ATN a rule is invoked. * * This is very useful for error messages. */ public getRuleInvocationStack(ctx: RuleContext = this._ctx): string[] { let p: RuleContext | undefined = ctx; // Workaround for Microsoft/TypeScript#14487 let ruleNames: string[] = this.ruleNames; let stack: string[] = []; while (p != null) { // compute what follows who invoked us let ruleIndex: number = p.ruleIndex; if (ruleIndex < 0) { stack.push("n/a"); } else { stack.push(ruleNames[ruleIndex]); } p = p._parent as RuleContext; } return stack; } /** For debugging and other purposes. */ public getDFAStrings(): string[] { let s: string[] = []; for (let dfa of this._interp.atn.decisionToDFA) { s.push(dfa.toString(this.vocabulary, this.ruleNames)); } return s; } /** For debugging and other purposes. */ public dumpDFA(): void { let seenOne: boolean = false; for (let dfa of this._interp.atn.decisionToDFA) { if (!dfa.isEmpty) { if (seenOne) { console.log(); } console.log("Decision " + dfa.decision + ":"); process.stdout.write(dfa.toString(this.vocabulary, this.ruleNames)); seenOne = true; } } } get sourceName(): string { return this._input.sourceName; } @Override get parseInfo(): Promise<ParseInfo | undefined> { return import("./atn/ProfilingATNSimulator").then((m) => { let interp: ParserATNSimulator = this.interpreter; if (interp instanceof m.ProfilingATNSimulator) { return new ParseInfo(interp); } return undefined; }); } /** * @since 4.3 */ public async setProfile(profile: boolean): Promise<void> { let m = await import("./atn/ProfilingATNSimulator"); let interp: ParserATNSimulator = this.interpreter; if (profile) { if (!(interp instanceof m.ProfilingATNSimulator)) { this.interpreter = new m.ProfilingATNSimulator(this); } } else if (interp instanceof m.ProfilingATNSimulator) { this.interpreter = new ParserATNSimulator(this.atn, this); } this.interpreter.setPredictionMode(interp.getPredictionMode()); } /** During a parse is sometimes useful to listen in on the rule entry and exit * events as well as token matches. This is for quick and dirty debugging. */ set isTrace(trace: boolean) { if (!trace) { if (this._tracer) { this.removeParseListener(this._tracer); this._tracer = undefined; } } else { if (this._tracer) { this.removeParseListener(this._tracer); } else { this._tracer = new TraceListener(this.ruleNames, this._input); } this.addParseListener(this._tracer); } } /** * Gets whether a {@link TraceListener} is registered as a parse listener * for the parser. */ get isTrace(): boolean { return this._tracer != null; } }
the_stack
* AccumulationChart Selection src file */ import { Browser, extend, isNullOrUndefined } from '@syncfusion/ej2-base'; import { Rect, SvgRenderer, CanvasRenderer } from '@syncfusion/ej2-svg-base'; import { indexFinder, getElement } from '../../common/utils/helper'; import { AccumulationSelectionMode, AccumulationHighlightMode } from '../model/enum'; import { AccumulationChart } from '../accumulation'; import { AccumulationSeries, pointByIndex, AccPoints } from '../model/acc-base'; import { AccumulationSeriesModel } from '../model/acc-base-model'; import { Indexes, Index } from '../../common/model/base'; import { BaseSelection } from '../../common/user-interaction/selection'; import { AccumulationTooltip } from './tooltip'; import { IAccSelectionCompleteEventArgs } from '../model/pie-interface'; import { selectionComplete } from '../../common/model/constants'; /** * `AccumulationSelection` module handles the selection for accumulation chart. */ export class AccumulationSelection extends BaseSelection { /** @private */ public renderer: SvgRenderer | CanvasRenderer; /** @private */ public rectPoints: Rect; /** @private */ public selectedDataIndexes: Indexes[]; /** @private */ public highlightDataIndexes: Indexes[]; /** @private */ public series: AccumulationSeries[]; /** @private */ public accumulation: AccumulationChart; /** @private */ public currentMode: AccumulationSelectionMode | AccumulationHighlightMode; /** @private */ public previousSelectedElement: Element[]; constructor(accumulation: AccumulationChart) { super(accumulation); this.accumulation = accumulation; this.renderer = accumulation.renderer; this.addEventListener(); } /** * Binding events for selection module. */ private addEventListener(): void { if (this.accumulation.isDestroyed) { return; } let cancelEvent: string = Browser.isPointer ? 'pointerleave' : 'mouseleave'; this.accumulation.on(Browser.touchMoveEvent, this.mouseMove, this); this.accumulation.on('click', this.calculateSelectedElements, this); } /** * UnBinding events for selection module. */ private removeEventListener(): void { if (this.accumulation.isDestroyed) { return; } this.accumulation.off(Browser.touchMoveEvent, this.mouseMove); this.accumulation.off('click', this.calculateSelectedElements); } /** * To initialize the private variables */ private initPrivateVariables(accumulation: AccumulationChart): void { this.styleId = accumulation.element.id + '_ej2_chart_selection'; this.unselected = accumulation.element.id + '_ej2_deselected'; this.selectedDataIndexes = []; this.rectPoints = null; } /** * Invoke selection for rendered chart. * * @param {AccumulationChart} accumulation Define the chart to invoke the selection. * @returns {void} */ public invokeSelection(accumulation: AccumulationChart): void { this.initPrivateVariables(accumulation); this.series = <AccumulationSeries[]>extend({}, accumulation.visibleSeries, null, true); this.seriesStyles(); this.currentMode = accumulation.selectionMode; this.selectDataIndex(this.concatIndexes(accumulation.selectedDataIndexes, this.selectedDataIndexes), accumulation); } /** * To get series selection style by series. */ private generateStyle(series: AccumulationSeriesModel): string { return (series.selectionStyle || this.styleId + '_series_' + (<AccumulationSeries>series).index); } /** * To get series selection style while hovering legend */ private generateLegendClickStyle(series: AccumulationSeriesModel, event ?: Event | PointerEvent): string { if (event.type === 'mousemove') { this.styleId = this.accumulation.element.id + '_ej2_chart_highlight'; } else if (event.type === 'click') { this.styleId = this.accumulation.element.id + '_ej2_chart_selection'; } return (series.selectionStyle || this.styleId + '_series_' + (<AccumulationSeries>series).index); } /** * To get elements by index, series */ private findElements(accumulation: AccumulationChart, series: AccumulationSeriesModel, index: Index): Element[] { return [this.getElementByIndex(index)]; } /** * To get series point element by index */ private getElementByIndex(index: Index): Element { const elementId: string = this.control.element.id + '_Series_' + index.series + '_Point_' + index.point; return document.getElementById(elementId); } /** * To find the selected element. * @return {void} * @private */ public isAlreadySelected(event : Event | PointerEvent): boolean { if (event.type === 'mousemove') { this.currentMode = this.accumulation.highlightMode; this.highlightDataIndexes = []; this.styleId = this.accumulation.element.id + '_ej2_chart_highlight'; } else if (event.type === 'click') { this.currentMode = this.accumulation.selectionMode; this.styleId = this.accumulation.element.id + '_ej2_chart_selection'; } if (this.accumulation.highlightMode !== 'None' && this.accumulation.selectionMode === 'None') { if (event.type === 'click') { return false; } } let targetElement: Element = <Element>event.target; if ((this.accumulation.highlightMode !== 'None' && this.previousSelectedElement && this.previousSelectedElement[0])) { let parentNodeId: string = (<Element>targetElement.parentNode).id; let isValidElement: boolean; if (targetElement.parentNode) { isValidElement = (parentNodeId.indexOf('SeriesGroup') > 0 || parentNodeId.indexOf('SymbolGroup') > 0) ? true : false; } for (let i: number = 0; i < this.previousSelectedElement.length; i++) { if (this.previousSelectedElement[i].hasAttribute('class')) { if (this.previousSelectedElement[i].getAttribute('class').indexOf('highlight') > -1 && (isValidElement || event.type === 'click')) { this.previousSelectedElement[i].removeAttribute('class'); this.addOrRemoveIndex(this.highlightDataIndexes, indexFinder((<HTMLElement>this.previousSelectedElement[i]).id)); } else if (!isValidElement && this.previousSelectedElement[i].getAttribute('class').indexOf('highlight') > -1) { this.performSelection(indexFinder(this.previousSelectedElement[i].id), this.accumulation, this.previousSelectedElement[i]); } } } } return true; } /** * To calculate selected elements on mouse click or touch * * @private */ public calculateSelectedElements(accumulation: AccumulationChart, event: Event): void { if (isNullOrUndefined(event.target)) { return; } let targetEle: HTMLElement = <HTMLElement>event.target; if ((accumulation.highlightMode === 'None' && accumulation.selectionMode === 'None') || targetEle.id.indexOf(accumulation.element.id + '_') === -1) { return; } if (event.type === 'mousemove') { if (!isNullOrUndefined(targetEle.parentNode) && ( <Element>targetEle.parentNode).hasAttribute('class') && ((<Element>targetEle.parentNode).getAttribute('class').indexOf('highlight') > 0 || (<Element>targetEle.parentNode).getAttribute('class').indexOf('selection') > 0)) { return; } } if (targetEle.getAttribute('id').indexOf('_connector_') > -1) { return; } else { this.isAlreadySelected(event); if (targetEle.id.indexOf('_Series_') > -1 || targetEle.id.indexOf('_datalabel_') > -1) { this.performSelection(indexFinder(targetEle.id), accumulation, <Element>event.target); } } } /** * To perform the selection process based on index and element. */ private performSelection(index: Index, accumulation: AccumulationChart, element?: Element): void { element = element.id.indexOf('datalabel') > -1 ? <Element>accumulation.getSeriesElement().childNodes[index.series].childNodes[index.point] : element; switch (this.currentMode) { case 'Point': if (!isNaN(index.point)) { this.selection(accumulation, index, [element]); this.selectionComplete(accumulation, <AccumulationSeries>accumulation.series[0]); this.blurEffect(accumulation.element.id, accumulation.visibleSeries); } break; } } /** * Method to get the selected data index * * @private */ private selectionComplete(accumulation: AccumulationChart, series: AccumulationSeries): void { let pointIndex: number; const selectedPointValues: { x?: string | number | Date, y?: number, seriesIndex?: number, pointIndex?: number }[] = []; for (let i: number = 0; i < this.selectedDataIndexes.length; i++) { pointIndex = this.selectedDataIndexes[i].point; if (!isNaN(pointIndex)) { selectedPointValues.push({ x: series.dataSource[pointIndex][series.xName], y: series.points[pointIndex].y, seriesIndex: this.selectedDataIndexes[i].series, pointIndex: pointIndex }); } } const args: IAccSelectionCompleteEventArgs = { name: selectionComplete, selectedDataValues: selectedPointValues, cancel: false }; accumulation.trigger(selectionComplete, args); } /** * To select the element by index. Adding or removing selection style class name. */ private selection(accumulation: AccumulationChart, index: Index, selectedElements: Element[]): void { if (!accumulation.isMultiSelect && this.styleId.indexOf('highlight') === -1 && accumulation.selectionMode !== 'None') { this.removeMultiSelectEelments(accumulation, this.selectedDataIndexes, index, accumulation.series); } const className: string = selectedElements[0] && (selectedElements[0].getAttribute('class') || ''); if (selectedElements[0] && className.indexOf(this.getSelectionClass(selectedElements[0].id)) > -1) { this.removeStyles(selectedElements, index); if (this.styleId.indexOf('highlight') > 0 && accumulation.highlightMode !== 'None') { this.addOrRemoveIndex(this.highlightDataIndexes, index); } else { this.addOrRemoveIndex(this.selectedDataIndexes, index); } if (accumulation.enableBorderOnMouseMove) { const borderElement: Element = document.getElementById(selectedElements[0].id.split('_')[0] + 'PointHover_Border'); if (!isNullOrUndefined(borderElement)) { this.removeSvgClass(borderElement, borderElement.getAttribute('class')); } } } else { this.previousSelectedElement = accumulation.highlightMode !== 'None' ? selectedElements : []; if (className.indexOf('selection') < 0) { this.applyStyles(selectedElements, index); } if (accumulation.enableBorderOnMouseMove) { const borderElement: Element = document.getElementById(selectedElements[0].id.split('_')[0] + 'PointHover_Border'); if (!isNullOrUndefined(borderElement)) { this.removeSvgClass(borderElement, borderElement.getAttribute('class')); this.addSvgClass(borderElement, selectedElements[0].getAttribute('class')); } } if (this.styleId.indexOf('highlight') > 0 && accumulation.highlightMode !== 'None') { this.addOrRemoveIndex(this.highlightDataIndexes, index, true); } else { this.addOrRemoveIndex(this.selectedDataIndexes, index, true); } } } /** * To redraw the selection process on accumulation chart refresh. * * @private */ public redrawSelection(accumulation: AccumulationChart): void { let selectedDataIndexes: Indexes[] = <Indexes[]>extend([], this.selectedDataIndexes, null, true); let highlightDataIndexes: Indexes[] = <Indexes[]>extend([], this.highlightDataIndexes, null, true); if (this.styleId.indexOf('highlight') > 0 && highlightDataIndexes.length > 0 ) { this.removeSelectedElements(accumulation, this.highlightDataIndexes); selectedDataIndexes = highlightDataIndexes; } else { this.removeSelectedElements(accumulation, this.selectedDataIndexes); } this.blurEffect(accumulation.element.id, accumulation.visibleSeries); this.selectDataIndex(selectedDataIndexes, accumulation); } /** * To remove the selected elements style classes by indexes. */ private removeSelectedElements(accumulation: AccumulationChart, indexes: Index[]): void { for (const index of indexes) { this.removeStyles([this.getElementByIndex(index)], index); } } /** * To perform the selection for legend elements. * * @private */ public legendSelection(accumulation: AccumulationChart, series: number, pointIndex: number, event: Event): void { let targetEle: Element = <Element>event.target; if (event.type === 'mousemove') { if ((<Element>event.target).id.indexOf('text') > 1) { targetEle = getElement((<Element>event.target).id.replace('text', 'shape')); } if (targetEle.hasAttribute('class') && (targetEle.getAttribute('class').indexOf('highlight') > -1 || targetEle.getAttribute('class').indexOf('selection') > -1)) { return; } this.currentMode = this.accumulation.highlightMode; } let isPreSelected: boolean = this.isAlreadySelected(event); if (isPreSelected) { let element: Element = <Element>accumulation.getSeriesElement().childNodes[series].childNodes[pointIndex]; let seriesStyle: string = this.generateLegendClickStyle(accumulation.visibleSeries[series], event); let seriesElements: Element = <Element>accumulation.getSeriesElement().childNodes[series].childNodes[pointIndex]; this.selection(accumulation, new Index(series, pointIndex), [seriesElements]); this.blurEffect(accumulation.element.id, accumulation.visibleSeries); } } /** * To select the element by selected data indexes. */ private selectDataIndex(indexes: Index[], accumulation: AccumulationChart): void { let element: Element; for (const index of indexes) { element = this.getElementByIndex(index); if (element) { this.performSelection(index, accumulation, element); } } } /** * To remove the selection styles for multi selection process. */ private removeMultiSelectEelments(accumulation: AccumulationChart, index: Index[], currentIndex: Index, seriesCollection: AccumulationSeriesModel[]): void { let series: AccumulationSeriesModel; for (let i: number = 0; i < index.length; i++) { series = seriesCollection[index[i].series]; if (!this.checkEquals(index[i], currentIndex)) { this.removeStyles(this.findElements(accumulation, series, index[i]), index[i]); index.splice(i, 1); i--; } } } /** * To apply the opacity effect for accumulation chart series elements. */ private blurEffect(pieId: string, visibleSeries: AccumulationSeries[]): void { const visibility: boolean = (this.checkVisibility(this.highlightDataIndexes) || this.checkVisibility(this.selectedDataIndexes)); // legend click scenario for (const series of visibleSeries) { if (series.visible) { this.checkSelectionElements(document.getElementById(pieId + '_SeriesCollection'), this.generateStyle(series), visibility); } } } /** * To check selection elements by style class name. */ private checkSelectionElements(element: Element, className: string, visibility: boolean): void { const children: NodeList = element.childNodes[0].childNodes; let legendShape: Element; let elementClass: string; let parentClass: string; let selectElement: Element = element; for (let i: number = 0; i < children.length; i++) { elementClass = (children[i] as HTMLElement).getAttribute('class') || ''; parentClass = (<Element>children[i].parentNode).getAttribute('class') || ''; if (this.accumulation.selectionMode !== 'None' && this.accumulation.highlightMode !== 'None') { className = elementClass.indexOf('selection') > 0 || elementClass.indexOf('highlight') > 0 ? elementClass : className; className = (parentClass.indexOf('selection') > 0 || parentClass.indexOf('highlight') > 0) ? parentClass : className; } if (elementClass.indexOf(className) === -1 && parentClass.indexOf(className) === -1 && visibility) { this.addSvgClass(children[i] as HTMLElement, this.unselected); } else { this.removeSvgClass(children[i] as HTMLElement, this.unselected); } if (elementClass.indexOf(className) === -1 && parentClass.indexOf(className) === -1 && visibility) { this.addSvgClass(children[i] as HTMLElement, this.unselected); } else { selectElement = children[i] as HTMLElement; this.removeSvgClass(children[i] as HTMLElement, this.unselected); this.removeSvgClass(<Element>children[i].parentNode, this.unselected); } if ((this.control as AccumulationChart).accumulationLegendModule && this.control.legendSettings.visible) { legendShape = document.getElementById(this.control.element.id + '_chart_legend_shape_' + i); if (legendShape) { if (elementClass.indexOf(className) === -1 && parentClass.indexOf(className) === -1 && visibility) { this.addSvgClass(legendShape, this.unselected); } else { this.removeSvgClass(legendShape, this.unselected); } } } } } /** * To apply selection style for elements. */ private applyStyles(elements: Element[], index: Index): void { const accumulationTooltip: AccumulationTooltip = (this.control as AccumulationChart).accumulationTooltipModule; for (const element of elements) { let legendShape: Element; if (element) { if ((this.control as AccumulationChart).accumulationLegendModule && this.control.legendSettings.visible) { legendShape = document.getElementById(this.control.element.id + '_chart_legend_shape_' + index.point); this.removeSvgClass(legendShape, legendShape.getAttribute('class')); this.addSvgClass(legendShape, this.getSelectionClass(legendShape.id)); } this.removeSvgClass(<Element>element.parentNode, this.unselected); this.removeSvgClass(element, this.unselected); const opacity: number = accumulationTooltip && (accumulationTooltip.previousPoints.length > 0 && accumulationTooltip.previousPoints[0].point.index !== index.point) ? accumulationTooltip.svgTooltip.opacity : this.series[index.series].opacity; element.setAttribute('opacity', opacity.toString()); this.addSvgClass(element, this.getSelectionClass(element.id)); } } } /** * To get selection style class name by id */ private getSelectionClass(id: string): string { return this.generateStyle((this.control as AccumulationChart).series[indexFinder(id).series]); } /** * To remove selection style for elements. */ private removeStyles(elements: Element[], index: Index): void { const accumulationTooltip: AccumulationTooltip = (this.control as AccumulationChart).accumulationTooltipModule; let legendShape: Element; for (const element of elements) { if (element) { if ((this.control as AccumulationChart).accumulationLegendModule && this.control.legendSettings.visible) { legendShape = document.getElementById(this.control.element.id + '_chart_legend_shape_' + index.point); this.removeSvgClass(legendShape, this.getSelectionClass(legendShape.id)); } const opacity: number = accumulationTooltip && accumulationTooltip.previousPoints.length > 0 && (accumulationTooltip.previousPoints[0].point.index === index.point) ? accumulationTooltip.svgTooltip.opacity : this.series[index.series].opacity; element.setAttribute('opacity', opacity.toString()); this.removeSvgClass(element, this.getSelectionClass(element.id)); } } } /** * To apply or remove selected elements index. */ private addOrRemoveIndex(indexes: Index[], index: Index, add?: boolean): void { for (let i: number = 0; i < indexes.length; i++) { if (this.checkEquals(indexes[i], index)) { indexes.splice(i, 1); i--; } } if (add) { indexes.push(index); } } /** * To check two index, point and series are equal */ private checkEquals(first: Index, second: Index): boolean { return ((first.point === second.point) && (first.series === second.series)); } /** @private */ public mouseMove(event: PointerEvent | TouchEvent): void{ let accumulation: AccumulationChart = this.accumulation; let targetElement: Element = <Element>event.target; if (accumulation.highlightMode !== 'None') { if (!isNullOrUndefined(targetElement)) { if ((<Element>event.target).id.indexOf('text') > 1) { targetElement = getElement((<Element>event.target).id.replace('text', 'shape')); } if ((targetElement).hasAttribute('class') && (targetElement).getAttribute('class').indexOf('highlight') > -1) { return; } this.calculateSelectedElements(accumulation, event); return; } } if (accumulation.selectionMode === 'None') { return; } } /** * To check selected points are visibility */ private checkPointVisibility(selectedDataIndexes: Indexes[]): boolean { let visible: boolean = false; for (const data of selectedDataIndexes) { if (pointByIndex(data.point, <AccPoints[]>this.control.visibleSeries[0].points).visible) { visible = true; break; } } return visible; } /** * Get module name. */ public getModuleName(): string { return 'AccumulationSelection'; } /** * To destroy the selection. * * @returns {void} * @private */ public destroy(): void { // Destroy method performed here this.removeEventListener(); } }
the_stack
import { ACCOUNTS } from "__test__/accounts"; import * as moment from "moment"; import { CollateralizerAdapterErrors } from "src/adapters/collateralized_simple_interest_loan_adapter"; import { OrderAPIErrors } from "src/apis/order_api"; import { DebtOrderData } from "src/types"; import { CollateralizedSimpleInterestTermsContractContract, DebtKernelContract, DebtOrderDataWrapper, DummyTokenContract, RepaymentRouterContract, SimpleInterestTermsContractContract, } from "src/wrappers"; import { BigNumber } from "utils/bignumber"; import { NULL_ADDRESS, NULL_BYTES32 } from "utils/constants"; import * as Units from "utils/units"; import { FillScenario } from "./"; export const INVALID_ORDERS: FillScenario[] = [ { description: "with principal < debtor fee", generateDebtOrderData: ( debtKernel: DebtKernelContract, repaymentRouter: RepaymentRouterContract, principalToken: DummyTokenContract, termsContract: SimpleInterestTermsContractContract, ) => { return { kernelVersion: debtKernel.address, issuanceVersion: repaymentRouter.address, principalAmount: Units.ether(0.49), principalToken: principalToken.address, debtor: ACCOUNTS[1].address, debtorFee: Units.ether(0.51), creditor: ACCOUNTS[2].address, creditorFee: Units.ether(0.001), relayer: ACCOUNTS[3].address, relayerFee: Units.ether(0.001), underwriter: ACCOUNTS[4].address, underwriterFee: Units.ether(0.511), underwriterRiskRating: Units.percent(0.001), termsContract: termsContract.address, termsContractParameters: NULL_BYTES32, expirationTimestampInSec: new BigNumber( moment() .add(7, "days") .unix(), ), salt: new BigNumber(0), }; }, filler: ACCOUNTS[2].address, signatories: { debtor: true, creditor: false, underwriter: true, }, successfullyFills: false, errorType: "INVALID_DEBTOR_FEE", errorMessage: OrderAPIErrors.INVALID_DEBTOR_FEE(), }, { description: "with no underwriter but with underwriter fee", generateDebtOrderData: ( debtKernel: DebtKernelContract, repaymentRouter: RepaymentRouterContract, principalToken: DummyTokenContract, termsContract: SimpleInterestTermsContractContract, ) => { return { kernelVersion: debtKernel.address, issuanceVersion: repaymentRouter.address, principalAmount: Units.ether(1), principalToken: principalToken.address, debtor: ACCOUNTS[1].address, debtorFee: Units.ether(0.001), creditor: ACCOUNTS[2].address, creditorFee: Units.ether(0.001), relayer: ACCOUNTS[3].address, relayerFee: Units.ether(0.001), underwriter: NULL_ADDRESS, underwriterFee: Units.ether(0.001), underwriterRiskRating: Units.percent(0.001), termsContract: termsContract.address, termsContractParameters: NULL_BYTES32, expirationTimestampInSec: new BigNumber( moment() .add(7, "days") .unix(), ), salt: new BigNumber(0), }; }, filler: ACCOUNTS[2].address, signatories: { debtor: true, creditor: false, underwriter: false, }, successfullyFills: false, errorType: "INVALID_UNDERWRITER_FEE", errorMessage: OrderAPIErrors.INVALID_UNDERWRITER_FEE(), }, { description: "with a relayer fee but no assigned relayer", generateDebtOrderData: ( debtKernel: DebtKernelContract, repaymentRouter: RepaymentRouterContract, principalToken: DummyTokenContract, termsContract: SimpleInterestTermsContractContract, ) => { return { kernelVersion: debtKernel.address, issuanceVersion: repaymentRouter.address, principalAmount: Units.ether(1), principalToken: principalToken.address, debtor: ACCOUNTS[1].address, debtorFee: Units.ether(0.001), creditor: ACCOUNTS[2].address, creditorFee: Units.ether(0.001), relayer: NULL_ADDRESS, relayerFee: Units.ether(0.001), underwriter: ACCOUNTS[4].address, underwriterFee: Units.ether(0.001), underwriterRiskRating: Units.percent(0.001), termsContract: termsContract.address, termsContractParameters: NULL_BYTES32, expirationTimestampInSec: new BigNumber( moment() .add(7, "days") .unix(), ), salt: new BigNumber(0), }; }, filler: ACCOUNTS[2].address, signatories: { debtor: true, creditor: false, underwriter: true, }, successfullyFills: false, errorType: "INVALID_RELAYER_FEE", errorMessage: OrderAPIErrors.INVALID_RELAYER_FEE(), }, { description: "creditor + debtor fee does not equal underwriter + relayer fee", generateDebtOrderData: ( debtKernel: DebtKernelContract, repaymentRouter: RepaymentRouterContract, principalToken: DummyTokenContract, termsContract: SimpleInterestTermsContractContract, ) => { return { kernelVersion: debtKernel.address, issuanceVersion: repaymentRouter.address, principalAmount: Units.ether(1), principalToken: principalToken.address, debtor: ACCOUNTS[1].address, debtorFee: Units.ether(0.001), creditor: ACCOUNTS[2].address, creditorFee: Units.ether(0.001), relayer: ACCOUNTS[3].address, relayerFee: Units.ether(0.004), underwriter: ACCOUNTS[4].address, underwriterFee: Units.ether(0.001), underwriterRiskRating: Units.percent(0.001), termsContract: termsContract.address, termsContractParameters: NULL_BYTES32, expirationTimestampInSec: new BigNumber( moment() .add(7, "days") .unix(), ), salt: new BigNumber(0), }; }, filler: ACCOUNTS[2].address, signatories: { debtor: true, creditor: false, underwriter: true, }, successfullyFills: false, errorType: "INVALID_FEES", errorMessage: OrderAPIErrors.INVALID_FEES(), }, { description: "order has already expired", generateDebtOrderData: ( debtKernel: DebtKernelContract, repaymentRouter: RepaymentRouterContract, principalToken: DummyTokenContract, termsContract: SimpleInterestTermsContractContract, ) => { return { kernelVersion: debtKernel.address, issuanceVersion: repaymentRouter.address, principalAmount: Units.ether(1), principalToken: principalToken.address, debtor: ACCOUNTS[1].address, debtorFee: Units.ether(0.001), creditor: ACCOUNTS[2].address, creditorFee: Units.ether(0.001), relayer: ACCOUNTS[3].address, relayerFee: Units.ether(0.001), underwriter: ACCOUNTS[4].address, underwriterFee: Units.ether(0.001), underwriterRiskRating: Units.percent(0.001), termsContract: termsContract.address, termsContractParameters: NULL_BYTES32, expirationTimestampInSec: new BigNumber( moment() .subtract(7, "days") .unix(), ), salt: new BigNumber(0), }; }, filler: ACCOUNTS[2].address, signatories: { debtor: true, creditor: false, underwriter: true, }, successfullyFills: false, errorType: "EXPIRED", errorMessage: OrderAPIErrors.EXPIRED(), }, { description: "order has been cancelled", generateDebtOrderData: ( debtKernel: DebtKernelContract, repaymentRouter: RepaymentRouterContract, principalToken: DummyTokenContract, termsContract: SimpleInterestTermsContractContract, ) => { return { kernelVersion: debtKernel.address, issuanceVersion: repaymentRouter.address, principalAmount: Units.ether(1), principalToken: principalToken.address, debtor: ACCOUNTS[1].address, debtorFee: Units.ether(0.001), creditor: ACCOUNTS[2].address, creditorFee: Units.ether(0.001), relayer: ACCOUNTS[3].address, relayerFee: Units.ether(0.001), underwriter: ACCOUNTS[4].address, underwriterFee: Units.ether(0.001), underwriterRiskRating: Units.percent(0.001), termsContract: termsContract.address, termsContractParameters: NULL_BYTES32, expirationTimestampInSec: new BigNumber( moment() .add(7, "days") .unix(), ), salt: new BigNumber(0), }; }, filler: ACCOUNTS[2].address, signatories: { debtor: true, creditor: false, underwriter: true, }, successfullyFills: false, errorType: "DEBT_ORDER_CANCELLED", errorMessage: OrderAPIErrors.ORDER_CANCELLED(), beforeBlock: async (debtOrderData: DebtOrderData, debtKernel: DebtKernelContract) => { const debtOrderDataWrapper = new DebtOrderDataWrapper(debtOrderData); await debtKernel.cancelDebtOrder.sendTransactionAsync( debtOrderDataWrapper.getOrderAddresses(), debtOrderDataWrapper.getOrderValues(), debtOrderDataWrapper.getOrderBytes32(), { from: debtOrderData.debtor }, ); }, }, { description: "order has already been filled", generateDebtOrderData: ( debtKernel: DebtKernelContract, repaymentRouter: RepaymentRouterContract, principalToken: DummyTokenContract, termsContract: SimpleInterestTermsContractContract, ) => { return { kernelVersion: debtKernel.address, issuanceVersion: repaymentRouter.address, principalAmount: Units.ether(1), principalToken: principalToken.address, debtor: ACCOUNTS[1].address, debtorFee: Units.ether(0.001), creditor: ACCOUNTS[2].address, creditorFee: Units.ether(0.001), relayer: ACCOUNTS[3].address, relayerFee: Units.ether(0.001), underwriter: ACCOUNTS[4].address, underwriterFee: Units.ether(0.001), underwriterRiskRating: Units.percent(0.001), termsContract: termsContract.address, termsContractParameters: NULL_BYTES32, expirationTimestampInSec: new BigNumber( moment() .add(7, "days") .unix(), ), salt: new BigNumber(0), }; }, filler: ACCOUNTS[2].address, signatories: { debtor: true, creditor: false, underwriter: true, }, successfullyFills: false, errorType: "DEBT_ORDER_ALREADY_FILLED", errorMessage: OrderAPIErrors.DEBT_ORDER_ALREADY_FILLED(), beforeBlock: async (debtOrderData: DebtOrderData, debtKernel: DebtKernelContract) => { const debtOrderDataWrapped = new DebtOrderDataWrapper(debtOrderData); await debtKernel.fillDebtOrder.sendTransactionAsync( debtOrderDataWrapped.getCreditor(), debtOrderDataWrapped.getOrderAddresses(), debtOrderDataWrapped.getOrderValues(), debtOrderDataWrapped.getOrderBytes32(), debtOrderDataWrapped.getSignaturesV(), debtOrderDataWrapped.getSignaturesR(), debtOrderDataWrapped.getSignaturesS(), { from: debtOrderData.creditor }, ); }, }, { description: "collateral allowance is insufficient", generateDebtOrderData: ( debtKernel: DebtKernelContract, repaymentRouter: RepaymentRouterContract, principalToken: DummyTokenContract, termsContract: CollateralizedSimpleInterestTermsContractContract, ) => { return { kernelVersion: debtKernel.address, issuanceVersion: repaymentRouter.address, principalAmount: Units.ether(1), principalToken: principalToken.address, debtor: ACCOUNTS[1].address, debtorFee: Units.ether(0.001), creditor: ACCOUNTS[2].address, creditorFee: Units.ether(0.001), relayer: ACCOUNTS[3].address, relayerFee: Units.ether(0.002), termsContract: termsContract.address, /** * Principal token index is 0 * Principal Amount: 1e18 * Interest Rate: 0.1% * Monthly installments * 7 day term length * 10 units of collateral * Collateral token index is 2 * Grace period is 90 days */ termsContractParameters: "0x000000003635c9adc5dea000000003e8300020200000008ac7230489e800005a", expirationTimestampInSec: new BigNumber( moment() .add(7, "days") .unix(), ), salt: new BigNumber(0), }; }, filler: ACCOUNTS[2].address, signatories: { debtor: true, creditor: false, underwriter: false, }, successfullyFills: false, errorType: "INSUFFICIENT_COLLATERALIZER_ALLOWANCE", errorMessage: OrderAPIErrors.INSUFFICIENT_COLLATERALIZER_ALLOWANCE(), isCollateralized: true, collateralBalance: Units.ether(10), // Collateral allowance is insufficient by 1 unit. collateralAllowance: Units.ether(9), collateralTokenIndex: new BigNumber(2), }, { description: "collateral balance is insufficient", generateDebtOrderData: ( debtKernel: DebtKernelContract, repaymentRouter: RepaymentRouterContract, principalToken: DummyTokenContract, termsContract: CollateralizedSimpleInterestTermsContractContract, ) => { return { kernelVersion: debtKernel.address, issuanceVersion: repaymentRouter.address, principalAmount: Units.ether(1), principalToken: principalToken.address, debtor: ACCOUNTS[1].address, debtorFee: Units.ether(0.001), creditor: ACCOUNTS[2].address, creditorFee: Units.ether(0.001), relayer: ACCOUNTS[3].address, relayerFee: Units.ether(0.002), termsContract: termsContract.address, /** * Principal token index is 0 * Principal Amount: 1e18 * Interest Rate: 0.1% * Monthly installments * 7 day term length * 10 units of collateral * Collateral token index is 2 * Grace period is 90 days */ termsContractParameters: "0x000000003635c9adc5dea000000003e8300020200000008ac7230489e800005a", expirationTimestampInSec: new BigNumber( moment() .add(7, "days") .unix(), ), salt: new BigNumber(0), }; }, filler: ACCOUNTS[2].address, signatories: { debtor: true, creditor: false, underwriter: false, }, successfullyFills: false, errorType: "INSUFFICIENT_COLLATERALIZER_BALANCE", errorMessage: OrderAPIErrors.INSUFFICIENT_COLLATERALIZER_BALANCE(), isCollateralized: true, // Collateral balance is insufficient by 1 unit. collateralBalance: Units.ether(9), collateralAllowance: Units.ether(10), collateralTokenIndex: new BigNumber(2), }, { description: "collateralized but collateral amount is 0", generateDebtOrderData: ( debtKernel: DebtKernelContract, repaymentRouter: RepaymentRouterContract, principalToken: DummyTokenContract, termsContract: CollateralizedSimpleInterestTermsContractContract, ) => { return { kernelVersion: debtKernel.address, issuanceVersion: repaymentRouter.address, principalAmount: Units.ether(1), principalToken: principalToken.address, debtor: ACCOUNTS[1].address, debtorFee: Units.ether(0.001), creditor: ACCOUNTS[2].address, creditorFee: Units.ether(0.001), relayer: ACCOUNTS[3].address, relayerFee: Units.ether(0.002), termsContract: termsContract.address, /** * Principal token index is 0 * Principal Amount: 1e18 * Interest Rate: 0.1% * Monthly installments * 7 day term length * 0 units of collateral * Collateral token index is 2 * Grace period is 90 days */ termsContractParameters: "0x000000003635c9adc5dea000000003e83000202000000000000000000000005a", expirationTimestampInSec: new BigNumber( moment() .add(7, "days") .unix(), ), salt: new BigNumber(0), }; }, filler: ACCOUNTS[2].address, signatories: { debtor: true, creditor: false, underwriter: false, }, successfullyFills: false, errorType: "COLLATERAL_AMOUNT_MUST_BE_POSITIVE", errorMessage: CollateralizerAdapterErrors.COLLATERAL_AMOUNT_MUST_BE_POSITIVE(), isCollateralized: true, collateralBalance: Units.ether(1), collateralAllowance: Units.ether(10), collateralTokenIndex: new BigNumber(2), }, ];
the_stack
import { Injectable } from '@nestjs/common' import { ApolloError } from 'apollo-server-express' import { logger } from '@island.is/logging' import { AudienceAndScope, ClientCredentials, Contact, TestResult, Organisation, Helpdesk, ProviderStatistics, } from './models' import { DocumentProviderClientTest } from './client/documentProviderClientTest' import { DocumentProviderClientProd } from './client/documentProviderClientProd' import { UpdateOrganisationInput, UpdateContactInput, UpdateHelpdeskInput, CreateContactInput, CreateHelpdeskInput, } from './dto' import { OrganisationsApi, ProvidersApi } from '../../gen/fetch' import type { Auth } from '@island.is/auth-nest-tools' import { AuthMiddleware } from '@island.is/auth-nest-tools' // eslint-disable-next-line const handleError = (error: any) => { logger.error(JSON.stringify(error)) if (error.response?.data) { throw new ApolloError(error.response.data, error.status) } else { throw new ApolloError('Failed to resolve request', error.status) } } @Injectable() export class DocumentProviderService { constructor( private documentProviderClientTest: DocumentProviderClientTest, private documentProviderClientProd: DocumentProviderClientProd, private organisationsApi: OrganisationsApi, private providersApi: ProvidersApi, ) {} organisationsApiWithAuth(authorization: Auth) { return this.organisationsApi.withMiddleware( new AuthMiddleware(authorization), ) } providersApiWithAuth(authorization: Auth) { return this.providersApi.withMiddleware(new AuthMiddleware(authorization)) } async getOrganisations(authorization: Auth): Promise<Organisation[]> { return await this.organisationsApiWithAuth(authorization) .organisationControllerGetOrganisations({}) .catch(handleError) } async getOrganisation( nationalId: string, authorization: Auth, ): Promise<Organisation> { return await this.organisationsApiWithAuth(authorization) .organisationControllerFindByNationalId({ nationalId }) .catch(handleError) } async organisationExists( nationalId: string, authorization: Auth, ): Promise<boolean> { const organisation = await this.organisationsApiWithAuth(authorization) .organisationControllerFindByNationalId({ nationalId }) .catch(() => { //Find returns 404 error if organisation is not found. Do nothing. }) return !organisation ? false : true } async updateOrganisation( id: string, organisation: UpdateOrganisationInput, authorization: Auth, ): Promise<Organisation> { const dto = { id, updateOrganisationDto: { ...organisation }, } return await this.organisationsApiWithAuth(authorization) .organisationControllerUpdateOrganisation(dto) .catch(handleError) } async createAdministrativeContact( organisationId: string, input: CreateContactInput, authorization: Auth, ): Promise<Contact> { const dto = { id: organisationId, createContactDto: { ...input }, } return await this.organisationsApiWithAuth(authorization) .organisationControllerCreateAdministrativeContact(dto) .catch(handleError) } async updateAdministrativeContact( organisationId: string, contactId: string, contact: UpdateContactInput, authorization: Auth, ): Promise<Contact> { const dto = { id: organisationId, administrativeContactId: contactId, updateContactDto: { ...contact }, } return await this.organisationsApiWithAuth(authorization) .organisationControllerUpdateAdministrativeContact(dto) .catch(handleError) } async createTechnicalContact( organisationId: string, input: CreateContactInput, authorization: Auth, ): Promise<Contact> { const dto = { id: organisationId, createContactDto: { ...input }, } return await this.organisationsApiWithAuth(authorization) .organisationControllerCreateTechnicalContact(dto) .catch(handleError) } async updateTechnicalContact( organisationId: string, contactId: string, contact: UpdateContactInput, authorization: Auth, ): Promise<Contact> { const dto = { id: organisationId, technicalContactId: contactId, updateContactDto: { ...contact }, } return await this.organisationsApiWithAuth(authorization) .organisationControllerUpdateTechnicalContact(dto) .catch(handleError) } async createHelpdesk( organisationId: string, input: CreateHelpdeskInput, authorization: Auth, ): Promise<Helpdesk> { const dto = { id: organisationId, createHelpdeskDto: { ...input }, } return await this.organisationsApiWithAuth(authorization) .organisationControllerCreateHelpdesk(dto) .catch(handleError) } async updateHelpdesk( organisationId: string, helpdeskId: string, helpdesk: UpdateHelpdeskInput, authorization: Auth, ): Promise<Helpdesk> { const dto = { id: organisationId, helpdeskId: helpdeskId, updateHelpdeskDto: { ...helpdesk }, } return await this.organisationsApiWithAuth(authorization) .organisationControllerUpdateHelpdesk(dto) .catch(handleError) } async isLastModifierOfOrganisation( organisationNationalId: string, authorization: Auth, ): Promise<boolean> { return await this.organisationsApiWithAuth( authorization, ).organisationControllerIsLastModifierOfOrganisation({ nationalId: organisationNationalId, }) } //-------------------- PROVIDER -------------------------- async createProviderOnTest( nationalId: string, clientName: string, authorization: Auth, ): Promise<ClientCredentials> { // return new ClientCredentials( // '5016d8d5cb6ce0758107b9969ea3c301', // '7a557951364a960a608735371db61ed8ed320d6bfc59f52fe37fc08e23dbd8d1', // 'd6a4d279-6243-46d1-81c0-d98b825959bc', // ) const isLastModifier = await this.isLastModifierOfOrganisation( nationalId, authorization, ) if (!isLastModifier) { throw new ApolloError( 'Forbidden. User is not last modifier of organisation.', '403', ) } const result = await this.documentProviderClientTest .createClient(nationalId, clientName) .catch(handleError) const credentials = new ClientCredentials( result.clientId, result.clientSecret, result.providerId, ) return credentials } async updateEndpointOnTest( endpoint: string, providerId: string, xroad: boolean, ): Promise<AudienceAndScope> { // return new AudienceAndScope( // 'https://test-skjalaveita-island-is.azurewebsites.net', // 'https://test-skjalaveita-island-is.azurewebsites.net/api/v1/customer/.default', // ) const result = await this.documentProviderClientTest .updateEndpoint(providerId, endpoint, xroad) .catch(handleError) const audienceAndScope = new AudienceAndScope(result.audience, result.scope) return audienceAndScope } async runEndpointTests( recipient: string, documentId: string, providerId: string, ): Promise<TestResult[]> { //return [new TestResult('getMessageFromMailbox', true, 'Skjal fannst.')] const results = await this.documentProviderClientTest .runTests(providerId, recipient, documentId) .catch(handleError) return results.map((result) => { return new TestResult(result.id, result.isValid, result.message) }) } async createProvider( nationalId: string, clientName: string, authorization: Auth, ): Promise<ClientCredentials> { // return new ClientCredentials( // '5016d8d5cb6ce0758107b9969ea3c301', // '7a557951364a960a608735371db61ed8ed320d6bfc59f52fe37fc08e23dbd8d1', // 'd6a4d279-6243-46d1-81c0-d98b825959bc', // ) const isLastModifier = await this.isLastModifierOfOrganisation( nationalId, authorization, ) if (!isLastModifier) { throw new ApolloError( 'Forbidden. User is not last modifier of organisation.', '403', ) } const result = await this.documentProviderClientProd .createClient(nationalId, clientName) .catch(handleError) const credentials = new ClientCredentials( result.clientId, result.clientSecret, result.providerId, ) // Get the current organisation from nationalId const organisation = await this.getOrganisation(nationalId, authorization) if (!organisation) { throw new ApolloError('Could not find organisation.') } // Create provider for organisation const dto = { createProviderDto: { externalProviderId: credentials.providerId, organisationId: organisation.id, }, } const provider = await this.providersApiWithAuth( authorization, ).providerControllerCreateProvider(dto) if (!provider) { throw new ApolloError('Could not create provider.') } return credentials } async updateEndpoint( endpoint: string, providerId: string, xroad: boolean, authorization: Auth, ): Promise<AudienceAndScope> { // return new AudienceAndScope( // 'https://test-skjalaveita-island-is.azurewebsites.net', // 'https://test-skjalaveita-island-is.azurewebsites.net/api/v1/customer/.default', // ) const result = await this.documentProviderClientProd .updateEndpoint(providerId, endpoint, xroad) .catch(handleError) const audienceAndScope = new AudienceAndScope(result.audience, result.scope) // Find provider by externalProviderId const provider = await this.providersApi.providerControllerFindByExternalId( { id: providerId }, ) // Update the provider const dto = { id: provider.id, updateProviderDto: { endpoint, endpointType: 'REST', apiScope: audienceAndScope.scope, xroad, }, } const updatedProvider = await this.providersApiWithAuth( authorization, ).providerControllerUpdateProvider(dto) if (!updatedProvider) { throw new ApolloError('Could not update provider.') } return audienceAndScope } //-------------------- STATISTICS -------------------------- async getStatisticsTotal( authorization: Auth, organisationId?: string, fromDate?: string, toDate?: string, ): Promise<ProviderStatistics> { let providers = undefined // Get external provider ids if organisationId is included if (organisationId) { const orgProviders = await this.organisationsApiWithAuth( authorization, ).organisationControllerGetOrganisationsProviders({ id: organisationId, }) // Filter out null values and only set providers if organisation has external providers if (orgProviders) { const externalProviders = orgProviders .filter( (item) => item.externalProviderId !== null && item.externalProviderId !== undefined, ) .map((item) => { return item.externalProviderId }) if (externalProviders.length > 0) { providers = externalProviders as string[] } } } const result = await this.documentProviderClientProd .statisticsTotal(providers, fromDate, toDate) .catch(handleError) return new ProviderStatistics( result.published, result.notifications, result.opened, ) } }
the_stack
import assert from "assert"; import getProvider from "../../helpers/getProvider"; import { Quantity } from "@ganache/utils"; import EthereumProvider from "../../../src/provider"; import { RpcTransaction } from "@ganache/ethereum-transaction"; describe("api", () => { describe("personal", () => { describe("listAccounts", () => { it("matches eth_accounts", async () => { const provider = await getProvider({ wallet: { seed: "temet nosce" }, chain: { // use berlin here because we just want to test if we can use the // "zero" address, and we do this by transferring value while // setting the gasPrice to `0`. This isn't possible after the // `london` hardfork currently, as we don't provide an option to // allow for a 0 `maxFeePerGas` value. // TODO: remove once we have a configurable `maxFeePerGas` hardfork: "berlin" } }); const accounts = await provider.send("eth_accounts"); const personalAccounts = await provider.send("personal_listAccounts"); assert.deepStrictEqual(personalAccounts, accounts); }); }); async function testLockedAccountWithPassphraseViaEth_SendTransaction( provider: EthereumProvider, newAccount: string, passphrase: string ) { const transaction = { from: newAccount, to: newAccount, gasLimit: `0x${(21000).toString(16)}`, gasPrice: "0x0", value: "0x0", nonce: "0x0" }; // make sure we can't use the account via eth_sendTransaction await assert.rejects( provider.send("eth_sendTransaction", [transaction]), { message: "authentication needed: password or unlock" }, "eth_sendTransaction should have rejected due to locked from account without its passphrase" ); // unlock the account indefinitely const unlocked = await provider.send("personal_unlockAccount", [ newAccount, passphrase, 0 ]); assert.strictEqual(unlocked, true); await provider.send("eth_subscribe", ["newHeads"]); // send a normal transaction const transactionHash = await provider.send("eth_sendTransaction", [ transaction ]); await provider.once("message"); // ensure sure it worked const receipt = await provider.send("eth_getTransactionReceipt", [ transactionHash ]); assert.strictEqual( receipt.status, "0x1", "Transaction failed when it should have succeeded" ); // lock the account const accountLocked = await provider.send("personal_lockAccount", [ newAccount ]); assert.strictEqual(accountLocked, true); // make sure it is locked await assert.rejects( provider.send("eth_sendTransaction", [ Object.assign({}, transaction, { nonce: 1 }) ]), { message: "authentication needed: password or unlock" }, "personal_lockAccount didn't work" ); } async function testLockedAccountWithPassphraseViaPersonal_SendTransaction( provider: EthereumProvider, newAccount: string, passphrase: string ) { const transaction = { from: newAccount, to: newAccount, gasLimit: `0x${(21000).toString(16)}`, gasPrice: "0x0", value: "0x0", nonce: "0x0" }; // make sure we can't use the account via personal_sendTransaction and no passphrase await assert.rejects( provider.send("personal_sendTransaction", [transaction, undefined]), { message: "could not decrypt key with given password" }, "personal_sendTransaction should have rejected due to locked from account without its passphrase" ); // make sure we can't use the account with bad passphrases const invalidPassphrases = [ "this is not my passphrase", null, undefined, Buffer.allocUnsafe(0), 1, 0, Infinity, NaN ]; await Promise.all( invalidPassphrases.map(invalidPassphrase => { return assert.rejects( provider.send("personal_sendTransaction", [ transaction, invalidPassphrase as any ]), { message: "could not decrypt key with given password" }, "Transaction should have rejected due to locked from account with wrong passphrase" ); }) ); // use personal_sendTransaction with the valid passphrase await provider.send("eth_subscribe", ["newHeads"]); const transactionHashPromise = provider.send("personal_sendTransaction", [ transaction, passphrase ]); const msgPromise = transactionHashPromise.then(() => provider.once("message") ); await assert.rejects( provider.send("eth_sendTransaction", [ Object.assign({}, transaction, { nonce: 1 }) ]), { message: "authentication needed: password or unlock" }, "personal_sendTransaction should not unlock the while transaction is bring processed" ); const transactionHash = await transactionHashPromise; await msgPromise; const receipt = await provider.send("eth_getTransactionReceipt", [ transactionHash ]); assert.strictEqual( receipt.status, "0x1", "Transaction failed when it should have succeeded" ); // ensure the account is still locked await assert.rejects( provider.send("eth_sendTransaction", [ Object.assign({}, transaction, { nonce: 1 }) ]), { message: "authentication needed: password or unlock" }, "personal_sendTransaction should still be locked the after the transaction is processed" ); } async function testLockedAccountWithPassphraseViaPersonal_SignTransaction( provider: EthereumProvider, newAccount: string, passphrase: string ) { const transaction = { from: newAccount, to: newAccount, gasLimit: Quantity.from(21000).toString(), gasPrice: "0x0", value: "0x0", nonce: "0x0" }; // make sure we can't use the account via personal_sendTransaction and no passphrase await assert.rejects( provider.send("personal_signTransaction", [transaction, undefined]), { message: "could not decrypt key with given password" }, "personal_sendTransaction should have rejected due to locked from account without its passphrase" ); // make sure we can't use the account with bad passphrases const invalidPassphrases = [ "this is not my passphrase", null, undefined, Buffer.allocUnsafe(0), 1, 0, Infinity, NaN ]; await Promise.all( invalidPassphrases.map(invalidPassphrase => { return assert.rejects( provider.send("personal_signTransaction", [ transaction, invalidPassphrase as any ]), { message: "could not decrypt key with given password" }, "Transaction should have rejected due to locked from account with wrong passphrase" ); }) ); // use personal_sendTransaction with the valid passphrase await provider.send("eth_subscribe", ["newHeads"]); const signedTxPromise = provider.send("personal_signTransaction", [ transaction, passphrase ]); const msgPromise = signedTxPromise.then(() => provider.once("message")); await assert.rejects( provider.send("eth_signTransaction", [ Object.assign({}, transaction, { nonce: 1 }) ]), { message: "authentication needed: password or unlock" }, "personal_signTransaction should not unlock the while transaction is bring processed" ); const signedTx = await signedTxPromise; const transactionHash = await provider.send("eth_sendRawTransaction", [ signedTx ]); await msgPromise; const receipt = await provider.send("eth_getTransactionReceipt", [ transactionHash ]); assert.strictEqual( receipt.status, "0x1", "Transaction failed when it should have succeeded" ); // ensure the account is still locked await assert.rejects( provider.send("eth_sendTransaction", [ Object.assign({}, transaction, { nonce: "0x0" }) ]), { message: "authentication needed: password or unlock" }, "personal_sendTransaction should still be locked the after the transaction is processed" ); } describe("newAccount", () => { it("generates deterministic accounts", async () => { const controlProvider = await getProvider(); const provider = await getProvider(); const newAccount = await provider.send("personal_newAccount", [""]); const controlAccount = await controlProvider.send( "personal_newAccount", [""] ); assert.strictEqual(newAccount, controlAccount); }); it("generates different accounts based on the `seed` option", async () => { const controlProvider = await getProvider(); const provider = await getProvider({ wallet: { seed: "temet nosce" } }); const newAccount = await provider.send("personal_newAccount", [""]); const controlAccount = await controlProvider.send( "personal_newAccount", [""] ); assert.notStrictEqual(newAccount, controlAccount); }); it("generates different accounts based on the `mnemonic` option", async () => { const controlProvider = await getProvider(); const provider = await getProvider({ wallet: { mnemonic: "sweet treat" } }); const newAccount = await provider.send("personal_newAccount", [""]); const controlAccount = await controlProvider.send( "personal_newAccount", [""] ); assert.notStrictEqual(newAccount, controlAccount); }); it("generates different accounts on successive calls", async () => { const provider = await getProvider(); const firstNewAccount = await provider.send("personal_newAccount", [ "" ]); const secondNewAccount = await provider.send("personal_newAccount", [ "" ]); assert.notStrictEqual(firstNewAccount, secondNewAccount); }); it("generates different accounts on successive calls based on the seed", async () => { const controlProvider = await getProvider(); const provider = await getProvider({ wallet: { seed: "temet nosce" } }); const firstNewAccount = await provider.send("personal_newAccount", [ "" ]); const secondNewAccount = await provider.send("personal_newAccount", [ "" ]); await provider.send("personal_newAccount", [""]); const controlSecondNewAccount = await controlProvider.send( "personal_newAccount", [""] ); assert.notStrictEqual( firstNewAccount, secondNewAccount, "First and second generated accounts are the same when they shouldn't be" ); assert.notStrictEqual( secondNewAccount, controlSecondNewAccount, "Second account is identical to control's second account when it shouldn't be" ); }); describe("personal_unlockAccount ➡ eth_sendTransaction ➡ personal_lockAccount", () => { it("generates locked accounts with passphrase", async () => { const provider = await getProvider({ miner: { defaultGasPrice: 0 } }); const passphrase = "this is my passphrase"; // generate an account const newAccount = await provider.send("personal_newAccount", [ passphrase ]); testLockedAccountWithPassphraseViaEth_SendTransaction( provider, newAccount, passphrase ); }); }); describe("personal_sendTransaction", () => { it("generates locked accounts with passphrase", async () => { const provider = await getProvider({ miner: { defaultGasPrice: 0 }, // use berlin here because we just want to test if we can use the // "zero" address, and we do this by transferring value while // setting the gasPrice to `0`. This isn't possible after the // `london` hardfork currently, as we don't provide an option to // allow for a 0 `maxFeePerGas` value. // TODO: remove once we have a configurable `maxFeePerGas` chain: { hardfork: "berlin" } }); const passphrase = "this is my passphrase"; // generate an account const newAccount = await provider.send("personal_newAccount", [ passphrase ]); testLockedAccountWithPassphraseViaPersonal_SendTransaction( provider, newAccount, passphrase ); }); }); describe("personal_signTransaction", () => { it("signs transaction from locked accounts with passphrase", async () => { const provider = await getProvider({ miner: { defaultGasPrice: 0 }, // use berlin here because we just want to test if we can use the // "zero" address, and we do this by transferring value while // setting the gasPrice to `0`. This isn't possible after the // `london` hardfork currently, as we don't provide an option to // allow for a 0 `maxFeePerGas` value. // TODO: remove once we have a configurable `maxFeePerGas` chain: { hardfork: "berlin" } }); const passphrase = "this is my passphrase"; // generate an account const newAccount = await provider.send("personal_newAccount", [ passphrase ]); testLockedAccountWithPassphraseViaPersonal_SignTransaction( provider, newAccount, passphrase ); }); }); }); describe("personal_importRawKey", () => { const secretKey = "0x0123456789012345678901234567890123456789012345678901234567890123"; const passphrase = "this is my passphrase"; it("should return the known account address", async () => { const provider = await getProvider(); const newAccount = await provider.send("personal_importRawKey", [ secretKey, passphrase ]); assert.strictEqual( newAccount, "0x14791697260e4c9a71f18484c9f997b308e59325", "Raw account not imported correctly" ); }); describe("personal_unlockAccount ➡ eth_sendTransaction ➡ personal_lockAccount", () => { it("generates locked accounts with passphrase", async () => { const provider = await getProvider({ miner: { defaultGasPrice: 0 }, // use berlin here because we just want to test if we can use the // "zero" address, and we do this by transferring value while // setting the gasPrice to `0`. This isn't possible after the // `london` hardfork currently, as we don't provide an option to // allow for a 0 `maxFeePerGas` value. // TODO: remove once we have a configurable `maxFeePerGas` chain: { hardfork: "berlin" } }); const passphrase = "this is my passphrase"; // generate an account const newAccount = await provider.send("personal_importRawKey", [ secretKey, passphrase ]); await testLockedAccountWithPassphraseViaEth_SendTransaction( provider, newAccount, passphrase ); }); }); describe("personal_sendTransaction", () => { it("generates locked accounts with passphrase", async () => { const provider = await getProvider({ miner: { defaultGasPrice: 0 }, // use berlin here because we just want to test if we can use the // "zero" address, and we do this by transferring value while // setting the gasPrice to `0`. This isn't possible after the // `london` hardfork currently, as we don't provide an option to // allow for a 0 `maxFeePerGas` value. // TODO: remove once we have a configurable `maxFeePerGas` chain: { hardfork: "berlin" } }); // generate an account const newAccount = await provider.send("personal_importRawKey", [ secretKey, passphrase ]); await testLockedAccountWithPassphraseViaPersonal_SendTransaction( provider, newAccount, passphrase ); }); }); describe("personal_signTransaction", () => { it("signs transaction from locked accounts with passphrase", async () => { const provider = await getProvider({ miner: { defaultGasPrice: 0 }, // use berlin here because we just want to test if we can use the // "zero" address, and we do this by transferring value while // setting the gasPrice to `0`. This isn't possible after the // `london` hardfork currently, as we don't provide an option to // allow for a 0 `maxFeePerGas` value. // TODO: remove once we have a configurable `maxFeePerGas` chain: { hardfork: "berlin" } }); // generate an account const newAccount = await provider.send("personal_importRawKey", [ secretKey, passphrase ]); await testLockedAccountWithPassphraseViaPersonal_SignTransaction( provider, newAccount, passphrase ); }); }); }); }); });
the_stack
import * as fs from "fs"; import * as path from "path"; import * as vscode from "vscode"; import * as constants from "./common/constants"; import * as util from "./common/util"; import { ARDUINO_CONFIG_FILE } from "./common/constants"; import { ArduinoWorkspace } from "./common/workspace"; import { DeviceSettings } from "./deviceSettings" /** * Interface that represents the arduino context information. * @interface */ export interface IDeviceContext { /** * COM Port connect to the device * @property {string} */ port: string; /** * Current selected Arduino board alias. * @property {string} */ board: string; /** * Arduino main sketch file * @property {string} */ sketch: string; /** * Arduino build output path */ output: string; /** * Arduino debugger */ debugger_: string; /** * Current selected programmer. * @property {string} */ programmer: string; /** * Arduino custom board configuration * @property {string} */ configuration: string; /** * IntelliSense configuration auto-generation project override. */ intelliSenseGen: string; initialize(): void; } export class DeviceContext implements IDeviceContext, vscode.Disposable { public static getInstance(): DeviceContext { return DeviceContext._deviceContext; } private static _deviceContext: DeviceContext = new DeviceContext(); private _settings = new DeviceSettings(); /** * TODO EW, 2020-02-17: * The absolute file path of the directory containing the vscode-arduino * extension. Not sure why this is stored here (it's a bit misplaced) and * not in a dedicated extension object containing the extension context * passed during activation. Another way would be a function in util.ts * using a mechanism like * * path.normalize(path.join(path.dirname(__filename), "..")) */ private _extensionPath: string; private _watcher: vscode.FileSystemWatcher; private _vscodeWatcher: vscode.FileSystemWatcher; private _sketchStatusBar: vscode.StatusBarItem; private _prebuild: string; private _programmer: string; private _suppressSaveContext: boolean = false; /** * @constructor */ private constructor() { if (vscode.workspace && ArduinoWorkspace.rootPath) { this._watcher = vscode.workspace.createFileSystemWatcher(path.join(ArduinoWorkspace.rootPath, ARDUINO_CONFIG_FILE)); // We only care about the deletion arduino.json in the .vscode folder: this._vscodeWatcher = vscode.workspace.createFileSystemWatcher(path.join(ArduinoWorkspace.rootPath, ".vscode"), true, true, false); this._watcher.onDidCreate(() => this.loadContext()); this._watcher.onDidChange(() => this.loadContext()); this._watcher.onDidDelete(() => this.loadContext()); this._vscodeWatcher.onDidDelete(() => this.loadContext()); this._sketchStatusBar = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, constants.statusBarPriority.SKETCH); this._sketchStatusBar.command = "arduino.selectSketch"; this._sketchStatusBar.tooltip = "Sketch File"; } } public dispose() { if (this._watcher) { this._watcher.dispose(); } if (this._vscodeWatcher) { this._vscodeWatcher.dispose(); } } public get extensionPath(): string { return this._extensionPath; } public set extensionPath(value: string) { this._extensionPath = value; } /** * TODO: Current we use the Arduino default settings. For future release, this dependency might be removed * and the setting only depends on device.json. * @method * * TODO EW, 2020-02-18: * A problem I discovered: here you try to find the config file location * and when you're writing below, you use a hard-coded location. When * resorting to "find", you have to store the file's location at least and * reuse it when saving. * But I think the intention is: load a config file from anywhere and save * it under .vscode/arduino.json. But then the initial load has to use find * and afterwards it must not use find anymore. */ public loadContext(): Thenable<object> { return vscode.workspace.findFiles(ARDUINO_CONFIG_FILE, null, 1) .then((files) => { if (files && files.length > 0) { this._settings.load(files[0].fsPath); // on invalid configuration we continue with current settings } else { // No configuration file found, starting over with defaults this._settings.reset(); } return this; }, (reason) => { // Workaround for change in API. // vscode.workspace.findFiles() for some reason now throws an error ehn path does not exist // vscode.window.showErrorMessage(reason.toString()); // Logger.notifyUserError("arduinoFileUnhandleError", new Error(reason.toString())); // Workaround for change in API, populate required props for arduino.json this._settings.reset(); return this; }); } public showStatusBar() { if (!this._settings.sketch.value) { return false; } this._sketchStatusBar.text = this._settings.sketch.value; this._sketchStatusBar.show(); } public get onChangePort() { return this._settings.port.emitter.event } public get onChangeBoard() { return this._settings.board.emitter.event } public get onChangeSketch() { return this._settings.sketch.emitter.event } public get onChangeOutput() { return this._settings.output.emitter.event } public get onChangeDebugger() { return this._settings.debugger.emitter.event } public get onChangeISAutoGen() { return this._settings.intelliSenseGen.emitter.event } public get onChangeConfiguration() { return this._settings.configuration.emitter.event } public get onChangePrebuild() { return this._settings.prebuild.emitter.event } public get onChangePostbuild() { return this._settings.postbuild.emitter.event } public get onChangeProgrammer() { return this._settings.programmer.emitter.event } public get port() { return this._settings.port.value; } public set port(value: string) { this._settings.port.value = value; this.saveContext(); } public get board() { return this._settings.board.value; } public set board(value: string) { this._settings.board.value = value; this.saveContext(); } public get sketch() { return this._settings.sketch.value; } public set sketch(value: string) { this._settings.sketch.value = value; this.saveContext(); } public get prebuild() { return this._settings.prebuild.value; } public get postbuild() { return this._settings.postbuild.value; } public get output() { return this._settings.output.value; } public set output(value: string) { this._settings.output.value = value; this.saveContext(); } public get debugger_() { return this._settings.debugger.value; } public set debugger_(value: string) { this._settings.debugger.value = value; this.saveContext(); } public get intelliSenseGen() { return this._settings.intelliSenseGen.value; } public set intelliSenseGen(value: string) { this._settings.intelliSenseGen.value = value; this.saveContext(); } public get configuration() { return this._settings.configuration.value; } public set configuration(value: string) { this._settings.configuration.value = value; this.saveContext(); } public get programmer() { return this._settings.programmer.value; } public set programmer(value: string) { this._settings.programmer.value = value; this.saveContext(); } public get suppressSaveContext() { return this._suppressSaveContext; } public set suppressSaveContext(value: boolean) { this._suppressSaveContext = value; } public get buildPreferences() { return this._settings.buildPreferences.value; } public async initialize() { if (ArduinoWorkspace.rootPath && util.fileExistsSync(path.join(ArduinoWorkspace.rootPath, ARDUINO_CONFIG_FILE))) { vscode.window.showInformationMessage("Arduino.json already generated."); return; } else { if (!ArduinoWorkspace.rootPath) { vscode.window.showInformationMessage("Please open a folder first."); return; } await this.resolveMainSketch(); if (this.sketch) { await vscode.commands.executeCommand("arduino.changeBoardType"); vscode.window.showInformationMessage("The workspace is initialized with the Arduino extension support."); } else { vscode.window.showInformationMessage("No sketch (*.ino or *.cpp) was found or selected - initialization skipped."); } } } /** * Note: We're using the class' setter for the sketch (i.e. this.sketch = ...) * to make sure that any changes are synched to the configuration file. */ public async resolveMainSketch() { // TODO (EW, 2020-02-18): Here you look for *.ino files but below you allow // *.cpp/*.c files to be set as sketch await vscode.workspace.findFiles("**/*.ino", null) .then(async (fileUris) => { if (fileUris.length === 0) { let newSketchFileName = await vscode.window.showInputBox({ value: "my-sketch.ino", prompt: "No sketch (*.ino) found in workspace, please provide a name", placeHolder: "Sketch file name (*.ino or *.cpp)", validateInput: (value) => { /* TODO (EW, 2020-02-18): * is 'c' actually allowed? Also found on within other files. * And the regular expression doesn't need the internal groups. * The outer group can be an anonymous group. * And \w doesn't match dashes - so any sketch containing dashes * will not be found. * The correct expression therefore would be something like this: * * /^[\w\-]+\.(?:ino|cpp)$/ * * I'd recommend to define such regular expressions (including) * line splitting etc.) at the global constants file. * This is true for any hard coded paths (like the snippets below) * as well. */ if (value && /^\w+\.((ino)|(cpp)|c)$/.test(value.trim())) { return null; } else { return "Invalid sketch file name. Should be *.ino/*.cpp/*.c"; } }, }); newSketchFileName = (newSketchFileName && newSketchFileName.trim()) || ""; if (newSketchFileName) { const snippets = fs.readFileSync(path.join(this.extensionPath, "snippets", "sample.ino")); fs.writeFileSync(path.join(ArduinoWorkspace.rootPath, newSketchFileName), snippets); this.sketch = newSketchFileName; // Open the new sketch file. const textDocument = await vscode.workspace.openTextDocument(path.join(ArduinoWorkspace.rootPath, newSketchFileName)); vscode.window.showTextDocument(textDocument, vscode.ViewColumn.One, true); } else { this.sketch = undefined; } } else if (fileUris.length === 1) { this.sketch = path.relative(ArduinoWorkspace.rootPath, fileUris[0].fsPath); } else if (fileUris.length > 1) { const chosen = await vscode.window.showQuickPick(<vscode.QuickPickItem[]>fileUris.map((fileUri): vscode.QuickPickItem => { return <vscode.QuickPickItem>{ label: path.relative(ArduinoWorkspace.rootPath, fileUri.fsPath), description: fileUri.fsPath, }; }), { placeHolder: "Select the main sketch file" }); if (chosen && chosen.label) { this.sketch = chosen.label; } } }); return this.sketch; } private saveContext() { if (!ArduinoWorkspace.rootPath) { return; } const deviceConfigFile = path.join(ArduinoWorkspace.rootPath, ARDUINO_CONFIG_FILE); this._settings.save(deviceConfigFile); } }
the_stack