text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest';
import * as models from '../models';
/**
* @class
* Catalog
* __NOTE__: An instance of this class is automatically created for an
* instance of the DataLakeAnalyticsCatalogManagementClient.
*/
export interface Catalog {
/**
* Creates the specified secret for use with external data sources in the
* specified database. This is deprecated and will be removed in the next
* release. Please use CreateCredential instead.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database in which to create the
* secret.
*
* @param {string} secretName The name of the secret.
*
* @param {object} parameters The parameters required to create the secret
* (name and password)
*
* @param {string} parameters.password the password for the secret to pass in
*
* @param {string} [parameters.uri] the URI identifier for the secret in the
* format <hostname>:<port>
*
* @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.
*/
createSecretWithHttpOperationResponse(accountName: string, databaseName: string, secretName: string, parameters: models.DataLakeAnalyticsCatalogSecretCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Creates the specified secret for use with external data sources in the
* specified database. This is deprecated and will be removed in the next
* release. Please use CreateCredential instead.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database in which to create the
* secret.
*
* @param {string} secretName The name of the secret.
*
* @param {object} parameters The parameters required to create the secret
* (name and password)
*
* @param {string} parameters.password the password for the secret to pass in
*
* @param {string} [parameters.uri] the URI identifier for the secret in the
* format <hostname>:<port>
*
* @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.
*/
createSecret(accountName: string, databaseName: string, secretName: string, parameters: models.DataLakeAnalyticsCatalogSecretCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
createSecret(accountName: string, databaseName: string, secretName: string, parameters: models.DataLakeAnalyticsCatalogSecretCreateOrUpdateParameters, callback: ServiceCallback<void>): void;
createSecret(accountName: string, databaseName: string, secretName: string, parameters: models.DataLakeAnalyticsCatalogSecretCreateOrUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Modifies the specified secret for use with external data sources in the
* specified database. This is deprecated and will be removed in the next
* release. Please use UpdateCredential instead.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the secret.
*
* @param {string} secretName The name of the secret.
*
* @param {object} parameters The parameters required to modify the secret
* (name and password)
*
* @param {string} parameters.password the password for the secret to pass in
*
* @param {string} [parameters.uri] the URI identifier for the secret in the
* format <hostname>:<port>
*
* @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.
*/
updateSecretWithHttpOperationResponse(accountName: string, databaseName: string, secretName: string, parameters: models.DataLakeAnalyticsCatalogSecretCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Modifies the specified secret for use with external data sources in the
* specified database. This is deprecated and will be removed in the next
* release. Please use UpdateCredential instead.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the secret.
*
* @param {string} secretName The name of the secret.
*
* @param {object} parameters The parameters required to modify the secret
* (name and password)
*
* @param {string} parameters.password the password for the secret to pass in
*
* @param {string} [parameters.uri] the URI identifier for the secret in the
* format <hostname>:<port>
*
* @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.
*/
updateSecret(accountName: string, databaseName: string, secretName: string, parameters: models.DataLakeAnalyticsCatalogSecretCreateOrUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
updateSecret(accountName: string, databaseName: string, secretName: string, parameters: models.DataLakeAnalyticsCatalogSecretCreateOrUpdateParameters, callback: ServiceCallback<void>): void;
updateSecret(accountName: string, databaseName: string, secretName: string, parameters: models.DataLakeAnalyticsCatalogSecretCreateOrUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Deletes the specified secret in the specified database. This is deprecated
* and will be removed in the next release. Please use DeleteCredential
* instead.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the secret.
*
* @param {string} secretName The name of the secret to delete
*
* @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.
*/
deleteSecretWithHttpOperationResponse(accountName: string, databaseName: string, secretName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes the specified secret in the specified database. This is deprecated
* and will be removed in the next release. Please use DeleteCredential
* instead.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the secret.
*
* @param {string} secretName The name of the secret to delete
*
* @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.
*/
deleteSecret(accountName: string, databaseName: string, secretName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteSecret(accountName: string, databaseName: string, secretName: string, callback: ServiceCallback<void>): void;
deleteSecret(accountName: string, databaseName: string, secretName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Gets the specified secret in the specified database. This is deprecated and
* will be removed in the next release. Please use GetCredential instead.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the secret.
*
* @param {string} secretName The name of the secret to get
*
* @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<USqlSecret>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getSecretWithHttpOperationResponse(accountName: string, databaseName: string, secretName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlSecret>>;
/**
* Gets the specified secret in the specified database. This is deprecated and
* will be removed in the next release. Please use GetCredential instead.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the secret.
*
* @param {string} secretName The name of the secret to get
*
* @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 {USqlSecret} - 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.
*
* {USqlSecret} [result] - The deserialized result object if an error did not occur.
* See {@link USqlSecret} 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.
*/
getSecret(accountName: string, databaseName: string, secretName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlSecret>;
getSecret(accountName: string, databaseName: string, secretName: string, callback: ServiceCallback<models.USqlSecret>): void;
getSecret(accountName: string, databaseName: string, secretName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlSecret>): void;
/**
* Deletes all secrets in the specified database. This is deprecated and will
* be removed in the next release. In the future, please only drop individual
* credentials using DeleteCredential
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the secret.
*
* @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.
*/
deleteAllSecretsWithHttpOperationResponse(accountName: string, databaseName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes all secrets in the specified database. This is deprecated and will
* be removed in the next release. In the future, please only drop individual
* credentials using DeleteCredential
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the secret.
*
* @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.
*/
deleteAllSecrets(accountName: string, databaseName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteAllSecrets(accountName: string, databaseName: string, callback: ServiceCallback<void>): void;
deleteAllSecrets(accountName: string, databaseName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Creates the specified credential for use with external data sources in the
* specified database.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database in which to create the
* credential. Note: This is NOT an external database name, but the name of an
* existing U-SQL database that should contain the new credential object.
*
* @param {string} credentialName The name of the credential.
*
* @param {object} parameters The parameters required to create the credential
* (name and password)
*
* @param {string} parameters.password the password for the credential and user
* with access to the data source.
*
* @param {string} parameters.uri the URI identifier for the data source this
* credential can connect to in the format <hostname>:<port>
*
* @param {string} parameters.userId the object identifier for the user
* associated with this credential with access to the data source.
*
* @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.
*/
createCredentialWithHttpOperationResponse(accountName: string, databaseName: string, credentialName: string, parameters: models.DataLakeAnalyticsCatalogCredentialCreateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Creates the specified credential for use with external data sources in the
* specified database.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database in which to create the
* credential. Note: This is NOT an external database name, but the name of an
* existing U-SQL database that should contain the new credential object.
*
* @param {string} credentialName The name of the credential.
*
* @param {object} parameters The parameters required to create the credential
* (name and password)
*
* @param {string} parameters.password the password for the credential and user
* with access to the data source.
*
* @param {string} parameters.uri the URI identifier for the data source this
* credential can connect to in the format <hostname>:<port>
*
* @param {string} parameters.userId the object identifier for the user
* associated with this credential with access to the data source.
*
* @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.
*/
createCredential(accountName: string, databaseName: string, credentialName: string, parameters: models.DataLakeAnalyticsCatalogCredentialCreateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
createCredential(accountName: string, databaseName: string, credentialName: string, parameters: models.DataLakeAnalyticsCatalogCredentialCreateParameters, callback: ServiceCallback<void>): void;
createCredential(accountName: string, databaseName: string, credentialName: string, parameters: models.DataLakeAnalyticsCatalogCredentialCreateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Modifies the specified credential for use with external data sources in the
* specified database
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* credential.
*
* @param {string} credentialName The name of the credential.
*
* @param {object} parameters The parameters required to modify the credential
* (name and password)
*
* @param {string} [parameters.password] the current password for the
* credential and user with access to the data source. This is required if the
* requester is not the account owner.
*
* @param {string} [parameters.newPassword] the new password for the credential
* and user with access to the data source.
*
* @param {string} [parameters.uri] the URI identifier for the data source this
* credential can connect to in the format <hostname>:<port>
*
* @param {string} [parameters.userId] the object identifier for the user
* associated with this credential with access to the data source.
*
* @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.
*/
updateCredentialWithHttpOperationResponse(accountName: string, databaseName: string, credentialName: string, parameters: models.DataLakeAnalyticsCatalogCredentialUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Modifies the specified credential for use with external data sources in the
* specified database
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* credential.
*
* @param {string} credentialName The name of the credential.
*
* @param {object} parameters The parameters required to modify the credential
* (name and password)
*
* @param {string} [parameters.password] the current password for the
* credential and user with access to the data source. This is required if the
* requester is not the account owner.
*
* @param {string} [parameters.newPassword] the new password for the credential
* and user with access to the data source.
*
* @param {string} [parameters.uri] the URI identifier for the data source this
* credential can connect to in the format <hostname>:<port>
*
* @param {string} [parameters.userId] the object identifier for the user
* associated with this credential with access to the data source.
*
* @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.
*/
updateCredential(accountName: string, databaseName: string, credentialName: string, parameters: models.DataLakeAnalyticsCatalogCredentialUpdateParameters, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>;
updateCredential(accountName: string, databaseName: string, credentialName: string, parameters: models.DataLakeAnalyticsCatalogCredentialUpdateParameters, callback: ServiceCallback<void>): void;
updateCredential(accountName: string, databaseName: string, credentialName: string, parameters: models.DataLakeAnalyticsCatalogCredentialUpdateParameters, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Deletes the specified credential in the specified database
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* credential.
*
* @param {string} credentialName The name of the credential to delete
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.parameters] The parameters to delete a credential
* if the current user is not the account owner.
*
* @param {string} [options.parameters.password] the current password for the
* credential and user with access to the data source. This is required if the
* requester is not the account owner.
*
* @param {boolean} [options.cascade] Indicates if the delete should be a
* cascading delete (which deletes all resources dependent on the credential as
* well as the credential) or not. If false will fail if there are any
* resources relying on the credential.
*
* @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.
*/
deleteCredentialWithHttpOperationResponse(accountName: string, databaseName: string, credentialName: string, options?: { parameters? : models.DataLakeAnalyticsCatalogCredentialDeleteParameters, cascade? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>;
/**
* Deletes the specified credential in the specified database
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* credential.
*
* @param {string} credentialName The name of the credential to delete
*
* @param {object} [options] Optional Parameters.
*
* @param {object} [options.parameters] The parameters to delete a credential
* if the current user is not the account owner.
*
* @param {string} [options.parameters.password] the current password for the
* credential and user with access to the data source. This is required if the
* requester is not the account owner.
*
* @param {boolean} [options.cascade] Indicates if the delete should be a
* cascading delete (which deletes all resources dependent on the credential as
* well as the credential) or not. If false will fail if there are any
* resources relying on the credential.
*
* @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.
*/
deleteCredential(accountName: string, databaseName: string, credentialName: string, options?: { parameters? : models.DataLakeAnalyticsCatalogCredentialDeleteParameters, cascade? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<void>;
deleteCredential(accountName: string, databaseName: string, credentialName: string, callback: ServiceCallback<void>): void;
deleteCredential(accountName: string, databaseName: string, credentialName: string, options: { parameters? : models.DataLakeAnalyticsCatalogCredentialDeleteParameters, cascade? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void;
/**
* Retrieves the specified credential from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the schema.
*
* @param {string} credentialName The name of the credential.
*
* @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<USqlCredential>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getCredentialWithHttpOperationResponse(accountName: string, databaseName: string, credentialName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlCredential>>;
/**
* Retrieves the specified credential from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the schema.
*
* @param {string} credentialName The name of the credential.
*
* @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 {USqlCredential} - 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.
*
* {USqlCredential} [result] - The deserialized result object if an error did not occur.
* See {@link USqlCredential} 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.
*/
getCredential(accountName: string, databaseName: string, credentialName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlCredential>;
getCredential(accountName: string, databaseName: string, credentialName: string, callback: ServiceCallback<models.USqlCredential>): void;
getCredential(accountName: string, databaseName: string, credentialName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlCredential>): void;
/**
* Retrieves the list of credentials from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the schema.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<USqlCredentialList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listCredentialsWithHttpOperationResponse(accountName: string, databaseName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlCredentialList>>;
/**
* Retrieves the list of credentials from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the schema.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @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 {USqlCredentialList} - 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.
*
* {USqlCredentialList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlCredentialList} 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.
*/
listCredentials(accountName: string, databaseName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlCredentialList>;
listCredentials(accountName: string, databaseName: string, callback: ServiceCallback<models.USqlCredentialList>): void;
listCredentials(accountName: string, databaseName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlCredentialList>): void;
/**
* Retrieves the specified external data source from the Data Lake Analytics
* catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* external data source.
*
* @param {string} externalDataSourceName The name of the external data source.
*
* @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<USqlExternalDataSource>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getExternalDataSourceWithHttpOperationResponse(accountName: string, databaseName: string, externalDataSourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlExternalDataSource>>;
/**
* Retrieves the specified external data source from the Data Lake Analytics
* catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* external data source.
*
* @param {string} externalDataSourceName The name of the external data source.
*
* @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 {USqlExternalDataSource} - 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.
*
* {USqlExternalDataSource} [result] - The deserialized result object if an error did not occur.
* See {@link USqlExternalDataSource} 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.
*/
getExternalDataSource(accountName: string, databaseName: string, externalDataSourceName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlExternalDataSource>;
getExternalDataSource(accountName: string, databaseName: string, externalDataSourceName: string, callback: ServiceCallback<models.USqlExternalDataSource>): void;
getExternalDataSource(accountName: string, databaseName: string, externalDataSourceName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlExternalDataSource>): void;
/**
* Retrieves the list of external data sources from the Data Lake Analytics
* catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* external data sources.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<USqlExternalDataSourceList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listExternalDataSourcesWithHttpOperationResponse(accountName: string, databaseName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlExternalDataSourceList>>;
/**
* Retrieves the list of external data sources from the Data Lake Analytics
* catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* external data sources.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @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 {USqlExternalDataSourceList} - 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.
*
* {USqlExternalDataSourceList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlExternalDataSourceList} 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.
*/
listExternalDataSources(accountName: string, databaseName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlExternalDataSourceList>;
listExternalDataSources(accountName: string, databaseName: string, callback: ServiceCallback<models.USqlExternalDataSourceList>): void;
listExternalDataSources(accountName: string, databaseName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlExternalDataSourceList>): void;
/**
* Retrieves the specified procedure from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* procedure.
*
* @param {string} schemaName The name of the schema containing the procedure.
*
* @param {string} procedureName The name of the procedure.
*
* @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<USqlProcedure>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getProcedureWithHttpOperationResponse(accountName: string, databaseName: string, schemaName: string, procedureName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlProcedure>>;
/**
* Retrieves the specified procedure from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* procedure.
*
* @param {string} schemaName The name of the schema containing the procedure.
*
* @param {string} procedureName The name of the procedure.
*
* @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 {USqlProcedure} - 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.
*
* {USqlProcedure} [result] - The deserialized result object if an error did not occur.
* See {@link USqlProcedure} 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.
*/
getProcedure(accountName: string, databaseName: string, schemaName: string, procedureName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlProcedure>;
getProcedure(accountName: string, databaseName: string, schemaName: string, procedureName: string, callback: ServiceCallback<models.USqlProcedure>): void;
getProcedure(accountName: string, databaseName: string, schemaName: string, procedureName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlProcedure>): void;
/**
* Retrieves the list of procedures from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* procedures.
*
* @param {string} schemaName The name of the schema containing the procedures.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<USqlProcedureList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listProceduresWithHttpOperationResponse(accountName: string, databaseName: string, schemaName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlProcedureList>>;
/**
* Retrieves the list of procedures from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* procedures.
*
* @param {string} schemaName The name of the schema containing the procedures.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @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 {USqlProcedureList} - 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.
*
* {USqlProcedureList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlProcedureList} 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.
*/
listProcedures(accountName: string, databaseName: string, schemaName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlProcedureList>;
listProcedures(accountName: string, databaseName: string, schemaName: string, callback: ServiceCallback<models.USqlProcedureList>): void;
listProcedures(accountName: string, databaseName: string, schemaName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlProcedureList>): void;
/**
* Retrieves the specified table from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the table.
*
* @param {string} schemaName The name of the schema containing the table.
*
* @param {string} tableName The name of the table.
*
* @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<USqlTable>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getTableWithHttpOperationResponse(accountName: string, databaseName: string, schemaName: string, tableName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTable>>;
/**
* Retrieves the specified table from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the table.
*
* @param {string} schemaName The name of the schema containing the table.
*
* @param {string} tableName The name of the table.
*
* @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 {USqlTable} - 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.
*
* {USqlTable} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTable} 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.
*/
getTable(accountName: string, databaseName: string, schemaName: string, tableName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTable>;
getTable(accountName: string, databaseName: string, schemaName: string, tableName: string, callback: ServiceCallback<models.USqlTable>): void;
getTable(accountName: string, databaseName: string, schemaName: string, tableName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTable>): void;
/**
* Retrieves the list of tables from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the tables.
*
* @param {string} schemaName The name of the schema containing the tables.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {boolean} [options.basic] The basic switch indicates what level of
* information to return when listing tables. When basic is true, only
* database_name, schema_name, table_name and version are returned for each
* table, otherwise all table metadata is returned. By default, it is false.
* Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<USqlTableList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTablesWithHttpOperationResponse(accountName: string, databaseName: string, schemaName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, basic? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTableList>>;
/**
* Retrieves the list of tables from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the tables.
*
* @param {string} schemaName The name of the schema containing the tables.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {boolean} [options.basic] The basic switch indicates what level of
* information to return when listing tables. When basic is true, only
* database_name, schema_name, table_name and version are returned for each
* table, otherwise all table metadata is returned. By default, it is false.
* Optional.
*
* @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 {USqlTableList} - 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.
*
* {USqlTableList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTableList} 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.
*/
listTables(accountName: string, databaseName: string, schemaName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, basic? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTableList>;
listTables(accountName: string, databaseName: string, schemaName: string, callback: ServiceCallback<models.USqlTableList>): void;
listTables(accountName: string, databaseName: string, schemaName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, basic? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTableList>): void;
/**
* Retrieves the list of all table statistics within the specified schema from
* the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* statistics.
*
* @param {string} schemaName The name of the schema containing the statistics.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<USqlTableStatisticsList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTableStatisticsByDatabaseAndSchemaWithHttpOperationResponse(accountName: string, databaseName: string, schemaName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTableStatisticsList>>;
/**
* Retrieves the list of all table statistics within the specified schema from
* the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* statistics.
*
* @param {string} schemaName The name of the schema containing the statistics.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @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 {USqlTableStatisticsList} - 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.
*
* {USqlTableStatisticsList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTableStatisticsList} 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.
*/
listTableStatisticsByDatabaseAndSchema(accountName: string, databaseName: string, schemaName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTableStatisticsList>;
listTableStatisticsByDatabaseAndSchema(accountName: string, databaseName: string, schemaName: string, callback: ServiceCallback<models.USqlTableStatisticsList>): void;
listTableStatisticsByDatabaseAndSchema(accountName: string, databaseName: string, schemaName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTableStatisticsList>): void;
/**
* Retrieves the specified table type from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the table
* type.
*
* @param {string} schemaName The name of the schema containing the table type.
*
* @param {string} tableTypeName The name of the table type to retrieve.
*
* @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<USqlTableType>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getTableTypeWithHttpOperationResponse(accountName: string, databaseName: string, schemaName: string, tableTypeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTableType>>;
/**
* Retrieves the specified table type from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the table
* type.
*
* @param {string} schemaName The name of the schema containing the table type.
*
* @param {string} tableTypeName The name of the table type to retrieve.
*
* @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 {USqlTableType} - 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.
*
* {USqlTableType} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTableType} 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.
*/
getTableType(accountName: string, databaseName: string, schemaName: string, tableTypeName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTableType>;
getTableType(accountName: string, databaseName: string, schemaName: string, tableTypeName: string, callback: ServiceCallback<models.USqlTableType>): void;
getTableType(accountName: string, databaseName: string, schemaName: string, tableTypeName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTableType>): void;
/**
* Retrieves the list of table types from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the table
* types.
*
* @param {string} schemaName The name of the schema containing the table
* types.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<USqlTableTypeList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTableTypesWithHttpOperationResponse(accountName: string, databaseName: string, schemaName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTableTypeList>>;
/**
* Retrieves the list of table types from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the table
* types.
*
* @param {string} schemaName The name of the schema containing the table
* types.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @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 {USqlTableTypeList} - 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.
*
* {USqlTableTypeList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTableTypeList} 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.
*/
listTableTypes(accountName: string, databaseName: string, schemaName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTableTypeList>;
listTableTypes(accountName: string, databaseName: string, schemaName: string, callback: ServiceCallback<models.USqlTableTypeList>): void;
listTableTypes(accountName: string, databaseName: string, schemaName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTableTypeList>): void;
/**
* Retrieves the specified package from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* package.
*
* @param {string} schemaName The name of the schema containing the package.
*
* @param {string} packageName The name of the package.
*
* @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<USqlPackage>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getPackageWithHttpOperationResponse(accountName: string, databaseName: string, schemaName: string, packageName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlPackage>>;
/**
* Retrieves the specified package from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* package.
*
* @param {string} schemaName The name of the schema containing the package.
*
* @param {string} packageName The name of the package.
*
* @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 {USqlPackage} - 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.
*
* {USqlPackage} [result] - The deserialized result object if an error did not occur.
* See {@link USqlPackage} 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.
*/
getPackage(accountName: string, databaseName: string, schemaName: string, packageName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlPackage>;
getPackage(accountName: string, databaseName: string, schemaName: string, packageName: string, callback: ServiceCallback<models.USqlPackage>): void;
getPackage(accountName: string, databaseName: string, schemaName: string, packageName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlPackage>): void;
/**
* Retrieves the list of packages from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* packages.
*
* @param {string} schemaName The name of the schema containing the packages.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<USqlPackageList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listPackagesWithHttpOperationResponse(accountName: string, databaseName: string, schemaName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlPackageList>>;
/**
* Retrieves the list of packages from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* packages.
*
* @param {string} schemaName The name of the schema containing the packages.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @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 {USqlPackageList} - 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.
*
* {USqlPackageList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlPackageList} 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.
*/
listPackages(accountName: string, databaseName: string, schemaName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlPackageList>;
listPackages(accountName: string, databaseName: string, schemaName: string, callback: ServiceCallback<models.USqlPackageList>): void;
listPackages(accountName: string, databaseName: string, schemaName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlPackageList>): void;
/**
* Retrieves the specified view from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the view.
*
* @param {string} schemaName The name of the schema containing the view.
*
* @param {string} viewName The name of the view.
*
* @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<USqlView>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getViewWithHttpOperationResponse(accountName: string, databaseName: string, schemaName: string, viewName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlView>>;
/**
* Retrieves the specified view from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the view.
*
* @param {string} schemaName The name of the schema containing the view.
*
* @param {string} viewName The name of the view.
*
* @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 {USqlView} - 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.
*
* {USqlView} [result] - The deserialized result object if an error did not occur.
* See {@link USqlView} 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.
*/
getView(accountName: string, databaseName: string, schemaName: string, viewName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlView>;
getView(accountName: string, databaseName: string, schemaName: string, viewName: string, callback: ServiceCallback<models.USqlView>): void;
getView(accountName: string, databaseName: string, schemaName: string, viewName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlView>): void;
/**
* Retrieves the list of views from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the views.
*
* @param {string} schemaName The name of the schema containing the views.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<USqlViewList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listViewsWithHttpOperationResponse(accountName: string, databaseName: string, schemaName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlViewList>>;
/**
* Retrieves the list of views from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the views.
*
* @param {string} schemaName The name of the schema containing the views.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @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 {USqlViewList} - 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.
*
* {USqlViewList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlViewList} 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.
*/
listViews(accountName: string, databaseName: string, schemaName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlViewList>;
listViews(accountName: string, databaseName: string, schemaName: string, callback: ServiceCallback<models.USqlViewList>): void;
listViews(accountName: string, databaseName: string, schemaName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlViewList>): void;
/**
* Retrieves the specified table statistics from the Data Lake Analytics
* catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* statistics.
*
* @param {string} schemaName The name of the schema containing the statistics.
*
* @param {string} tableName The name of the table containing the statistics.
*
* @param {string} statisticsName The name of the table statistics.
*
* @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<USqlTableStatistics>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getTableStatisticWithHttpOperationResponse(accountName: string, databaseName: string, schemaName: string, tableName: string, statisticsName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTableStatistics>>;
/**
* Retrieves the specified table statistics from the Data Lake Analytics
* catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* statistics.
*
* @param {string} schemaName The name of the schema containing the statistics.
*
* @param {string} tableName The name of the table containing the statistics.
*
* @param {string} statisticsName The name of the table statistics.
*
* @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 {USqlTableStatistics} - 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.
*
* {USqlTableStatistics} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTableStatistics} 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.
*/
getTableStatistic(accountName: string, databaseName: string, schemaName: string, tableName: string, statisticsName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTableStatistics>;
getTableStatistic(accountName: string, databaseName: string, schemaName: string, tableName: string, statisticsName: string, callback: ServiceCallback<models.USqlTableStatistics>): void;
getTableStatistic(accountName: string, databaseName: string, schemaName: string, tableName: string, statisticsName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTableStatistics>): void;
/**
* Retrieves the list of table statistics from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* statistics.
*
* @param {string} schemaName The name of the schema containing the statistics.
*
* @param {string} tableName The name of the table containing the statistics.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<USqlTableStatisticsList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTableStatisticsWithHttpOperationResponse(accountName: string, databaseName: string, schemaName: string, tableName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTableStatisticsList>>;
/**
* Retrieves the list of table statistics from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* statistics.
*
* @param {string} schemaName The name of the schema containing the statistics.
*
* @param {string} tableName The name of the table containing the statistics.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @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 {USqlTableStatisticsList} - 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.
*
* {USqlTableStatisticsList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTableStatisticsList} 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.
*/
listTableStatistics(accountName: string, databaseName: string, schemaName: string, tableName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTableStatisticsList>;
listTableStatistics(accountName: string, databaseName: string, schemaName: string, tableName: string, callback: ServiceCallback<models.USqlTableStatisticsList>): void;
listTableStatistics(accountName: string, databaseName: string, schemaName: string, tableName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTableStatisticsList>): void;
/**
* Retrieves the specified table partition from the Data Lake Analytics
* catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* partition.
*
* @param {string} schemaName The name of the schema containing the partition.
*
* @param {string} tableName The name of the table containing the partition.
*
* @param {string} partitionName The name of the table partition.
*
* @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<USqlTablePartition>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getTablePartitionWithHttpOperationResponse(accountName: string, databaseName: string, schemaName: string, tableName: string, partitionName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTablePartition>>;
/**
* Retrieves the specified table partition from the Data Lake Analytics
* catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* partition.
*
* @param {string} schemaName The name of the schema containing the partition.
*
* @param {string} tableName The name of the table containing the partition.
*
* @param {string} partitionName The name of the table partition.
*
* @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 {USqlTablePartition} - 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.
*
* {USqlTablePartition} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTablePartition} 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.
*/
getTablePartition(accountName: string, databaseName: string, schemaName: string, tableName: string, partitionName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTablePartition>;
getTablePartition(accountName: string, databaseName: string, schemaName: string, tableName: string, partitionName: string, callback: ServiceCallback<models.USqlTablePartition>): void;
getTablePartition(accountName: string, databaseName: string, schemaName: string, tableName: string, partitionName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTablePartition>): void;
/**
* Retrieves the list of table partitions from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* partitions.
*
* @param {string} schemaName The name of the schema containing the partitions.
*
* @param {string} tableName The name of the table containing the partitions.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<USqlTablePartitionList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTablePartitionsWithHttpOperationResponse(accountName: string, databaseName: string, schemaName: string, tableName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTablePartitionList>>;
/**
* Retrieves the list of table partitions from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* partitions.
*
* @param {string} schemaName The name of the schema containing the partitions.
*
* @param {string} tableName The name of the table containing the partitions.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @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 {USqlTablePartitionList} - 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.
*
* {USqlTablePartitionList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTablePartitionList} 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.
*/
listTablePartitions(accountName: string, databaseName: string, schemaName: string, tableName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTablePartitionList>;
listTablePartitions(accountName: string, databaseName: string, schemaName: string, tableName: string, callback: ServiceCallback<models.USqlTablePartitionList>): void;
listTablePartitions(accountName: string, databaseName: string, schemaName: string, tableName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTablePartitionList>): void;
/**
* Retrieves the list of types within the specified database and schema from
* the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the types.
*
* @param {string} schemaName The name of the schema containing the types.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<USqlTypeList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTypesWithHttpOperationResponse(accountName: string, databaseName: string, schemaName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTypeList>>;
/**
* Retrieves the list of types within the specified database and schema from
* the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the types.
*
* @param {string} schemaName The name of the schema containing the types.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @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 {USqlTypeList} - 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.
*
* {USqlTypeList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTypeList} 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.
*/
listTypes(accountName: string, databaseName: string, schemaName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTypeList>;
listTypes(accountName: string, databaseName: string, schemaName: string, callback: ServiceCallback<models.USqlTypeList>): void;
listTypes(accountName: string, databaseName: string, schemaName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTypeList>): void;
/**
* Retrieves the specified table valued function from the Data Lake Analytics
* catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the table
* valued function.
*
* @param {string} schemaName The name of the schema containing the table
* valued function.
*
* @param {string} tableValuedFunctionName The name of the tableValuedFunction.
*
* @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<USqlTableValuedFunction>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getTableValuedFunctionWithHttpOperationResponse(accountName: string, databaseName: string, schemaName: string, tableValuedFunctionName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTableValuedFunction>>;
/**
* Retrieves the specified table valued function from the Data Lake Analytics
* catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the table
* valued function.
*
* @param {string} schemaName The name of the schema containing the table
* valued function.
*
* @param {string} tableValuedFunctionName The name of the tableValuedFunction.
*
* @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 {USqlTableValuedFunction} - 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.
*
* {USqlTableValuedFunction} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTableValuedFunction} 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.
*/
getTableValuedFunction(accountName: string, databaseName: string, schemaName: string, tableValuedFunctionName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTableValuedFunction>;
getTableValuedFunction(accountName: string, databaseName: string, schemaName: string, tableValuedFunctionName: string, callback: ServiceCallback<models.USqlTableValuedFunction>): void;
getTableValuedFunction(accountName: string, databaseName: string, schemaName: string, tableValuedFunctionName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTableValuedFunction>): void;
/**
* Retrieves the list of table valued functions from the Data Lake Analytics
* catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the table
* valued functions.
*
* @param {string} schemaName The name of the schema containing the table
* valued functions.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<USqlTableValuedFunctionList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTableValuedFunctionsWithHttpOperationResponse(accountName: string, databaseName: string, schemaName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTableValuedFunctionList>>;
/**
* Retrieves the list of table valued functions from the Data Lake Analytics
* catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the table
* valued functions.
*
* @param {string} schemaName The name of the schema containing the table
* valued functions.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @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 {USqlTableValuedFunctionList} - 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.
*
* {USqlTableValuedFunctionList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTableValuedFunctionList} 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.
*/
listTableValuedFunctions(accountName: string, databaseName: string, schemaName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTableValuedFunctionList>;
listTableValuedFunctions(accountName: string, databaseName: string, schemaName: string, callback: ServiceCallback<models.USqlTableValuedFunctionList>): void;
listTableValuedFunctions(accountName: string, databaseName: string, schemaName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTableValuedFunctionList>): void;
/**
* Retrieves the specified assembly from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* assembly.
*
* @param {string} assemblyName The name of the assembly.
*
* @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<USqlAssembly>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getAssemblyWithHttpOperationResponse(accountName: string, databaseName: string, assemblyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlAssembly>>;
/**
* Retrieves the specified assembly from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* assembly.
*
* @param {string} assemblyName The name of the assembly.
*
* @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 {USqlAssembly} - 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.
*
* {USqlAssembly} [result] - The deserialized result object if an error did not occur.
* See {@link USqlAssembly} 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.
*/
getAssembly(accountName: string, databaseName: string, assemblyName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlAssembly>;
getAssembly(accountName: string, databaseName: string, assemblyName: string, callback: ServiceCallback<models.USqlAssembly>): void;
getAssembly(accountName: string, databaseName: string, assemblyName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlAssembly>): void;
/**
* Retrieves the list of assemblies from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* assembly.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<USqlAssemblyList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listAssembliesWithHttpOperationResponse(accountName: string, databaseName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlAssemblyList>>;
/**
* Retrieves the list of assemblies from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the
* assembly.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @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 {USqlAssemblyList} - 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.
*
* {USqlAssemblyList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlAssemblyList} 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.
*/
listAssemblies(accountName: string, databaseName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlAssemblyList>;
listAssemblies(accountName: string, databaseName: string, callback: ServiceCallback<models.USqlAssemblyList>): void;
listAssemblies(accountName: string, databaseName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlAssemblyList>): void;
/**
* Retrieves the specified schema from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the schema.
*
* @param {string} schemaName The name of the schema.
*
* @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<USqlSchema>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getSchemaWithHttpOperationResponse(accountName: string, databaseName: string, schemaName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlSchema>>;
/**
* Retrieves the specified schema from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the schema.
*
* @param {string} schemaName The name of the schema.
*
* @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 {USqlSchema} - 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.
*
* {USqlSchema} [result] - The deserialized result object if an error did not occur.
* See {@link USqlSchema} 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.
*/
getSchema(accountName: string, databaseName: string, schemaName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlSchema>;
getSchema(accountName: string, databaseName: string, schemaName: string, callback: ServiceCallback<models.USqlSchema>): void;
getSchema(accountName: string, databaseName: string, schemaName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlSchema>): void;
/**
* Retrieves the list of schemas from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the schema.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<USqlSchemaList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listSchemasWithHttpOperationResponse(accountName: string, databaseName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlSchemaList>>;
/**
* Retrieves the list of schemas from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the schema.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @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 {USqlSchemaList} - 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.
*
* {USqlSchemaList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlSchemaList} 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.
*/
listSchemas(accountName: string, databaseName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlSchemaList>;
listSchemas(accountName: string, databaseName: string, callback: ServiceCallback<models.USqlSchemaList>): void;
listSchemas(accountName: string, databaseName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlSchemaList>): void;
/**
* Retrieves the list of all statistics in a database from the Data Lake
* Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the table
* statistics.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<USqlTableStatisticsList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTableStatisticsByDatabaseWithHttpOperationResponse(accountName: string, databaseName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTableStatisticsList>>;
/**
* Retrieves the list of all statistics in a database from the Data Lake
* Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the table
* statistics.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @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 {USqlTableStatisticsList} - 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.
*
* {USqlTableStatisticsList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTableStatisticsList} 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.
*/
listTableStatisticsByDatabase(accountName: string, databaseName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTableStatisticsList>;
listTableStatisticsByDatabase(accountName: string, databaseName: string, callback: ServiceCallback<models.USqlTableStatisticsList>): void;
listTableStatisticsByDatabase(accountName: string, databaseName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTableStatisticsList>): void;
/**
* Retrieves the list of all tables in a database from the Data Lake Analytics
* catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the tables.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {boolean} [options.basic] The basic switch indicates what level of
* information to return when listing tables. When basic is true, only
* database_name, schema_name, table_name and version are returned for each
* table, otherwise all table metadata is returned. By default, it is false
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<USqlTableList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTablesByDatabaseWithHttpOperationResponse(accountName: string, databaseName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, basic? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTableList>>;
/**
* Retrieves the list of all tables in a database from the Data Lake Analytics
* catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the tables.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {boolean} [options.basic] The basic switch indicates what level of
* information to return when listing tables. When basic is true, only
* database_name, schema_name, table_name and version are returned for each
* table, otherwise all table metadata is returned. By default, it is false
*
* @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 {USqlTableList} - 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.
*
* {USqlTableList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTableList} 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.
*/
listTablesByDatabase(accountName: string, databaseName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, basic? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTableList>;
listTablesByDatabase(accountName: string, databaseName: string, callback: ServiceCallback<models.USqlTableList>): void;
listTablesByDatabase(accountName: string, databaseName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, basic? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTableList>): void;
/**
* Retrieves the list of all table valued functions in a database from the Data
* Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the table
* valued functions.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<USqlTableValuedFunctionList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTableValuedFunctionsByDatabaseWithHttpOperationResponse(accountName: string, databaseName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTableValuedFunctionList>>;
/**
* Retrieves the list of all table valued functions in a database from the Data
* Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the table
* valued functions.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @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 {USqlTableValuedFunctionList} - 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.
*
* {USqlTableValuedFunctionList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTableValuedFunctionList} 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.
*/
listTableValuedFunctionsByDatabase(accountName: string, databaseName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTableValuedFunctionList>;
listTableValuedFunctionsByDatabase(accountName: string, databaseName: string, callback: ServiceCallback<models.USqlTableValuedFunctionList>): void;
listTableValuedFunctionsByDatabase(accountName: string, databaseName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTableValuedFunctionList>): void;
/**
* Retrieves the list of all views in a database from the Data Lake Analytics
* catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the views.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<USqlViewList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listViewsByDatabaseWithHttpOperationResponse(accountName: string, databaseName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlViewList>>;
/**
* Retrieves the list of all views in a database from the Data Lake Analytics
* catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database containing the views.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @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 {USqlViewList} - 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.
*
* {USqlViewList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlViewList} 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.
*/
listViewsByDatabase(accountName: string, databaseName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlViewList>;
listViewsByDatabase(accountName: string, databaseName: string, callback: ServiceCallback<models.USqlViewList>): void;
listViewsByDatabase(accountName: string, databaseName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlViewList>): void;
/**
* Retrieves the specified database from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database.
*
* @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<USqlDatabase>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
getDatabaseWithHttpOperationResponse(accountName: string, databaseName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlDatabase>>;
/**
* Retrieves the specified database from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {string} databaseName The name of the database.
*
* @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 {USqlDatabase} - 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.
*
* {USqlDatabase} [result] - The deserialized result object if an error did not occur.
* See {@link USqlDatabase} 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.
*/
getDatabase(accountName: string, databaseName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlDatabase>;
getDatabase(accountName: string, databaseName: string, callback: ServiceCallback<models.USqlDatabase>): void;
getDatabase(accountName: string, databaseName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlDatabase>): void;
/**
* Retrieves the list of databases from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @param {object} [options.customHeaders] Headers that will be added to the
* request
*
* @returns {Promise} A promise is returned
*
* @resolve {HttpOperationResponse<USqlDatabaseList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listDatabasesWithHttpOperationResponse(accountName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlDatabaseList>>;
/**
* Retrieves the list of databases from the Data Lake Analytics catalog.
*
* @param {string} accountName The Azure Data Lake Analytics account upon which
* to execute catalog operations.
*
* @param {object} [options] Optional Parameters.
*
* @param {string} [options.filter] OData filter. Optional.
*
* @param {number} [options.top] The number of items to return. Optional.
*
* @param {number} [options.skip] The number of items to skip over before
* returning elements. Optional.
*
* @param {string} [options.select] OData Select statement. Limits the
* properties on each entry to just those requested, e.g.
* Categories?$select=CategoryName,Description. Optional.
*
* @param {string} [options.orderby] OrderBy clause. One or more
* comma-separated expressions with an optional "asc" (the default) or "desc"
* depending on the order you'd like the values sorted, e.g.
* Categories?$orderby=CategoryName desc. Optional.
*
* @param {boolean} [options.count] The Boolean value of true or false to
* request a count of the matching resources included with the resources in the
* response, e.g. Categories?$count=true. Optional.
*
* @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 {USqlDatabaseList} - 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.
*
* {USqlDatabaseList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlDatabaseList} 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.
*/
listDatabases(accountName: string, options?: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlDatabaseList>;
listDatabases(accountName: string, callback: ServiceCallback<models.USqlDatabaseList>): void;
listDatabases(accountName: string, options: { filter? : string, top? : number, skip? : number, select? : string, orderby? : string, count? : boolean, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlDatabaseList>): void;
/**
* Retrieves the list of credentials from the Data Lake Analytics catalog.
*
* @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<USqlCredentialList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listCredentialsNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlCredentialList>>;
/**
* Retrieves the list of credentials from the Data Lake Analytics catalog.
*
* @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 {USqlCredentialList} - 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.
*
* {USqlCredentialList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlCredentialList} 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.
*/
listCredentialsNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlCredentialList>;
listCredentialsNext(nextPageLink: string, callback: ServiceCallback<models.USqlCredentialList>): void;
listCredentialsNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlCredentialList>): void;
/**
* Retrieves the list of external data sources from the Data Lake Analytics
* catalog.
*
* @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<USqlExternalDataSourceList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listExternalDataSourcesNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlExternalDataSourceList>>;
/**
* Retrieves the list of external data sources from the Data Lake Analytics
* catalog.
*
* @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 {USqlExternalDataSourceList} - 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.
*
* {USqlExternalDataSourceList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlExternalDataSourceList} 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.
*/
listExternalDataSourcesNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlExternalDataSourceList>;
listExternalDataSourcesNext(nextPageLink: string, callback: ServiceCallback<models.USqlExternalDataSourceList>): void;
listExternalDataSourcesNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlExternalDataSourceList>): void;
/**
* Retrieves the list of procedures from the Data Lake Analytics catalog.
*
* @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<USqlProcedureList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listProceduresNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlProcedureList>>;
/**
* Retrieves the list of procedures from the Data Lake Analytics catalog.
*
* @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 {USqlProcedureList} - 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.
*
* {USqlProcedureList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlProcedureList} 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.
*/
listProceduresNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlProcedureList>;
listProceduresNext(nextPageLink: string, callback: ServiceCallback<models.USqlProcedureList>): void;
listProceduresNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlProcedureList>): void;
/**
* Retrieves the list of tables from the Data Lake Analytics catalog.
*
* @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<USqlTableList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTablesNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTableList>>;
/**
* Retrieves the list of tables from the Data Lake Analytics catalog.
*
* @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 {USqlTableList} - 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.
*
* {USqlTableList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTableList} 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.
*/
listTablesNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTableList>;
listTablesNext(nextPageLink: string, callback: ServiceCallback<models.USqlTableList>): void;
listTablesNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTableList>): void;
/**
* Retrieves the list of all table statistics within the specified schema from
* the Data Lake Analytics catalog.
*
* @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<USqlTableStatisticsList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTableStatisticsByDatabaseAndSchemaNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTableStatisticsList>>;
/**
* Retrieves the list of all table statistics within the specified schema from
* the Data Lake Analytics catalog.
*
* @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 {USqlTableStatisticsList} - 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.
*
* {USqlTableStatisticsList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTableStatisticsList} 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.
*/
listTableStatisticsByDatabaseAndSchemaNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTableStatisticsList>;
listTableStatisticsByDatabaseAndSchemaNext(nextPageLink: string, callback: ServiceCallback<models.USqlTableStatisticsList>): void;
listTableStatisticsByDatabaseAndSchemaNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTableStatisticsList>): void;
/**
* Retrieves the list of table types from the Data Lake Analytics catalog.
*
* @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<USqlTableTypeList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTableTypesNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTableTypeList>>;
/**
* Retrieves the list of table types from the Data Lake Analytics catalog.
*
* @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 {USqlTableTypeList} - 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.
*
* {USqlTableTypeList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTableTypeList} 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.
*/
listTableTypesNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTableTypeList>;
listTableTypesNext(nextPageLink: string, callback: ServiceCallback<models.USqlTableTypeList>): void;
listTableTypesNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTableTypeList>): void;
/**
* Retrieves the list of packages from the Data Lake Analytics catalog.
*
* @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<USqlPackageList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listPackagesNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlPackageList>>;
/**
* Retrieves the list of packages from the Data Lake Analytics catalog.
*
* @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 {USqlPackageList} - 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.
*
* {USqlPackageList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlPackageList} 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.
*/
listPackagesNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlPackageList>;
listPackagesNext(nextPageLink: string, callback: ServiceCallback<models.USqlPackageList>): void;
listPackagesNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlPackageList>): void;
/**
* Retrieves the list of views from the Data Lake Analytics catalog.
*
* @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<USqlViewList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listViewsNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlViewList>>;
/**
* Retrieves the list of views from the Data Lake Analytics catalog.
*
* @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 {USqlViewList} - 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.
*
* {USqlViewList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlViewList} 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.
*/
listViewsNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlViewList>;
listViewsNext(nextPageLink: string, callback: ServiceCallback<models.USqlViewList>): void;
listViewsNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlViewList>): void;
/**
* Retrieves the list of table statistics from the Data Lake Analytics catalog.
*
* @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<USqlTableStatisticsList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTableStatisticsNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTableStatisticsList>>;
/**
* Retrieves the list of table statistics from the Data Lake Analytics catalog.
*
* @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 {USqlTableStatisticsList} - 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.
*
* {USqlTableStatisticsList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTableStatisticsList} 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.
*/
listTableStatisticsNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTableStatisticsList>;
listTableStatisticsNext(nextPageLink: string, callback: ServiceCallback<models.USqlTableStatisticsList>): void;
listTableStatisticsNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTableStatisticsList>): void;
/**
* Retrieves the list of table partitions from the Data Lake Analytics catalog.
*
* @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<USqlTablePartitionList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTablePartitionsNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTablePartitionList>>;
/**
* Retrieves the list of table partitions from the Data Lake Analytics catalog.
*
* @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 {USqlTablePartitionList} - 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.
*
* {USqlTablePartitionList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTablePartitionList} 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.
*/
listTablePartitionsNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTablePartitionList>;
listTablePartitionsNext(nextPageLink: string, callback: ServiceCallback<models.USqlTablePartitionList>): void;
listTablePartitionsNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTablePartitionList>): void;
/**
* Retrieves the list of types within the specified database and schema from
* the Data Lake Analytics catalog.
*
* @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<USqlTypeList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTypesNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTypeList>>;
/**
* Retrieves the list of types within the specified database and schema from
* the Data Lake Analytics catalog.
*
* @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 {USqlTypeList} - 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.
*
* {USqlTypeList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTypeList} 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.
*/
listTypesNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTypeList>;
listTypesNext(nextPageLink: string, callback: ServiceCallback<models.USqlTypeList>): void;
listTypesNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTypeList>): void;
/**
* Retrieves the list of table valued functions from the Data Lake Analytics
* catalog.
*
* @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<USqlTableValuedFunctionList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTableValuedFunctionsNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTableValuedFunctionList>>;
/**
* Retrieves the list of table valued functions from the Data Lake Analytics
* catalog.
*
* @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 {USqlTableValuedFunctionList} - 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.
*
* {USqlTableValuedFunctionList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTableValuedFunctionList} 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.
*/
listTableValuedFunctionsNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTableValuedFunctionList>;
listTableValuedFunctionsNext(nextPageLink: string, callback: ServiceCallback<models.USqlTableValuedFunctionList>): void;
listTableValuedFunctionsNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTableValuedFunctionList>): void;
/**
* Retrieves the list of assemblies from the Data Lake Analytics catalog.
*
* @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<USqlAssemblyList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listAssembliesNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlAssemblyList>>;
/**
* Retrieves the list of assemblies from the Data Lake Analytics catalog.
*
* @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 {USqlAssemblyList} - 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.
*
* {USqlAssemblyList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlAssemblyList} 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.
*/
listAssembliesNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlAssemblyList>;
listAssembliesNext(nextPageLink: string, callback: ServiceCallback<models.USqlAssemblyList>): void;
listAssembliesNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlAssemblyList>): void;
/**
* Retrieves the list of schemas from the Data Lake Analytics catalog.
*
* @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<USqlSchemaList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listSchemasNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlSchemaList>>;
/**
* Retrieves the list of schemas from the Data Lake Analytics catalog.
*
* @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 {USqlSchemaList} - 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.
*
* {USqlSchemaList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlSchemaList} 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.
*/
listSchemasNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlSchemaList>;
listSchemasNext(nextPageLink: string, callback: ServiceCallback<models.USqlSchemaList>): void;
listSchemasNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlSchemaList>): void;
/**
* Retrieves the list of all statistics in a database from the Data Lake
* Analytics catalog.
*
* @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<USqlTableStatisticsList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTableStatisticsByDatabaseNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTableStatisticsList>>;
/**
* Retrieves the list of all statistics in a database from the Data Lake
* Analytics catalog.
*
* @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 {USqlTableStatisticsList} - 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.
*
* {USqlTableStatisticsList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTableStatisticsList} 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.
*/
listTableStatisticsByDatabaseNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTableStatisticsList>;
listTableStatisticsByDatabaseNext(nextPageLink: string, callback: ServiceCallback<models.USqlTableStatisticsList>): void;
listTableStatisticsByDatabaseNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTableStatisticsList>): void;
/**
* Retrieves the list of all tables in a database from the Data Lake Analytics
* catalog.
*
* @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<USqlTableList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTablesByDatabaseNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTableList>>;
/**
* Retrieves the list of all tables in a database from the Data Lake Analytics
* catalog.
*
* @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 {USqlTableList} - 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.
*
* {USqlTableList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTableList} 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.
*/
listTablesByDatabaseNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTableList>;
listTablesByDatabaseNext(nextPageLink: string, callback: ServiceCallback<models.USqlTableList>): void;
listTablesByDatabaseNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTableList>): void;
/**
* Retrieves the list of all table valued functions in a database from the Data
* Lake Analytics catalog.
*
* @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<USqlTableValuedFunctionList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listTableValuedFunctionsByDatabaseNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlTableValuedFunctionList>>;
/**
* Retrieves the list of all table valued functions in a database from the Data
* Lake Analytics catalog.
*
* @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 {USqlTableValuedFunctionList} - 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.
*
* {USqlTableValuedFunctionList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlTableValuedFunctionList} 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.
*/
listTableValuedFunctionsByDatabaseNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlTableValuedFunctionList>;
listTableValuedFunctionsByDatabaseNext(nextPageLink: string, callback: ServiceCallback<models.USqlTableValuedFunctionList>): void;
listTableValuedFunctionsByDatabaseNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlTableValuedFunctionList>): void;
/**
* Retrieves the list of all views in a database from the Data Lake Analytics
* catalog.
*
* @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<USqlViewList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listViewsByDatabaseNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlViewList>>;
/**
* Retrieves the list of all views in a database from the Data Lake Analytics
* catalog.
*
* @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 {USqlViewList} - 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.
*
* {USqlViewList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlViewList} 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.
*/
listViewsByDatabaseNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlViewList>;
listViewsByDatabaseNext(nextPageLink: string, callback: ServiceCallback<models.USqlViewList>): void;
listViewsByDatabaseNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlViewList>): void;
/**
* Retrieves the list of databases from the Data Lake Analytics catalog.
*
* @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<USqlDatabaseList>} - The deserialized result object.
*
* @reject {Error|ServiceError} - The error object.
*/
listDatabasesNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.USqlDatabaseList>>;
/**
* Retrieves the list of databases from the Data Lake Analytics catalog.
*
* @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 {USqlDatabaseList} - 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.
*
* {USqlDatabaseList} [result] - The deserialized result object if an error did not occur.
* See {@link USqlDatabaseList} 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.
*/
listDatabasesNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.USqlDatabaseList>;
listDatabasesNext(nextPageLink: string, callback: ServiceCallback<models.USqlDatabaseList>): void;
listDatabasesNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.USqlDatabaseList>): void;
} | the_stack |
import {expect} from 'chai';
import {Request, Response} from 'express';
import * as nock from 'nock';
import {describe, it} from 'mocha';
import {createPackument} from '../helpers/create-packument';
import {writePackageRequest} from '../helpers/write-package-request';
import * as datastore from '../../src/lib/datastore';
import {PublishKey, User} from '../../src/lib/datastore';
import {writePackage, WriteResponse} from '../../src/lib/write-package';
nock.disableNetConnect();
function mockResponse() {
return {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
status: (_code: number) => {
return;
},
end: () => {},
json: () => {},
} as Response;
}
describe('writePackage', () => {
it('responds with 401 if publication key not found in datastore', async () => {
writePackage.datastore = Object.assign({}, datastore, {
getPublishKey: async (): Promise<PublishKey | false> => {
return false;
},
});
const req = {headers: {authorization: 'token: abc123'}} as Request;
const res = mockResponse();
const ret = await writePackage('@soldair/foo', req, res);
expect(ret.statusCode).to.equal(401);
expect(ret.error).to.match(/publish key not found/);
});
it('responds with 400 if packument has no repository field', async () => {
// Fake that there's a releaseAs2FA key in datastore:
writePackage.datastore = Object.assign({}, datastore, {
getPublishKey: async (): Promise<PublishKey | false> => {
return {
username: 'bcoe',
created: 1578630249529,
value: 'deadbeef',
releaseAs2FA: true,
};
},
getUser: async (): Promise<false | User> => {
return {name: 'bcoe', token: 'deadbeef'};
},
});
// Simulate a publication request to the proxy:
const req = writePackageRequest(
{authorization: 'token: abc123'},
createPackument('@soldair/foo').addVersion('1.0.0').packument()
);
const res = mockResponse();
// A 404 while fetching the packument indicates that the package
// has not yet been created:
const npmRequest = nock('https://registry.npmjs.org')
.get('/@soldair%2ffoo')
.reply(404);
const ret = await writePackage('@soldair/foo', req, res);
npmRequest.done();
expect(ret.error).to.match(/must have a repository/);
expect(ret.statusCode).to.equal(400);
});
describe('releaseAs2FA', () => {
it('appropriately routes initial package publication', async () => {
// Fake that there's a releaseAs2FA key in datastore:
writePackage.datastore = Object.assign({}, datastore, {
getPublishKey: async (): Promise<PublishKey | false> => {
return {
username: 'bcoe',
created: 1578630249529,
value: 'deadbeef',
releaseAs2FA: true,
};
},
getUser: async (): Promise<false | User> => {
return {name: 'bcoe', token: 'deadbeef'};
},
});
writePackage.pipeToNpm = (
req: Request,
res: Response,
drainedBody: false | Buffer,
newPackage: boolean
): Promise<WriteResponse> => {
return Promise.resolve({statusCode: 200, newPackage});
};
// Simulate a publication request to the proxy:
const req = writePackageRequest(
{authorization: 'token: abc123'},
createPackument('@soldair/foo')
.addVersion('1.0.0', 'https://github.com/foo/bar')
.packument()
);
const res = mockResponse();
// A 404 while fetching the packument indicates that the package
// has not yet been created:
const npmRequest = nock('https://registry.npmjs.org')
.get('/@soldair%2ffoo')
.reply(404);
const githubRequest = nock('https://api.github.com')
// user has push access to repo in package.json
.get('/repos/foo/bar')
.reply(200, {permissions: {push: true}})
// most recent release tag on GitHub is v1.0.0
.get('/repos/foo/bar/tags?per_page=100&page=1')
.reply(200, [{name: 'v1.0.0'}]);
const ret = await writePackage('@soldair/foo', req, res);
npmRequest.done();
githubRequest.done();
expect(ret.newPackage).to.equal(true);
expect(ret.statusCode).to.equal(200);
});
it('allows a package to be updated', async () => {
// Fake that there's a releaseAs2FA key in datastore:
writePackage.datastore = Object.assign({}, datastore, {
getPublishKey: async (): Promise<PublishKey | false> => {
return {
username: 'bcoe',
created: 1578630249529,
value: 'deadbeef',
releaseAs2FA: true,
};
},
getUser: async (): Promise<false | User> => {
return {name: 'bcoe', token: 'deadbeef'};
},
});
writePackage.pipeToNpm = (
req: Request,
res: Response,
drainedBody: false | Buffer,
newPackage: boolean
): Promise<WriteResponse> => {
return Promise.resolve({statusCode: 200, newPackage});
};
// Simulate a publication request to the proxy:
const req = writePackageRequest(
{authorization: 'token: abc123'},
createPackument('@soldair/foo')
.addVersion('1.0.0', 'https://github.com/foo/bar')
.packument()
);
const res = mockResponse();
const npmRequest = nock('https://registry.npmjs.org')
.get('/@soldair%2ffoo')
.reply(
200,
createPackument('@soldair/foo')
.addVersion('0.1.0', 'https://github.com/foo/bar')
.packument()
);
const githubRequest = nock('https://api.github.com')
// user has push access to repo in package.json
.get('/repos/foo/bar')
.reply(200, {permissions: {push: true}})
// most recent release tag on GitHub is v1.0.0
.get('/repos/foo/bar/tags?per_page=100&page=1')
.reply(200, [{name: 'v1.0.0'}]);
const ret = await writePackage('@soldair/foo', req, res);
npmRequest.done();
githubRequest.done();
expect(ret.newPackage).to.equal(false);
expect(ret.statusCode).to.equal(200);
});
it('supports publication to next tag', async () => {
// Fake that there's a releaseAs2FA key in datastore:
writePackage.datastore = Object.assign({}, datastore, {
getPublishKey: async (): Promise<PublishKey | false> => {
return {
username: 'bcoe',
created: 1578630249529,
value: 'deadbeef',
releaseAs2FA: true,
};
},
getUser: async (): Promise<false | User> => {
return {name: 'bcoe', token: 'deadbeef'};
},
});
writePackage.pipeToNpm = (
req: Request,
res: Response,
drainedBody: false | Buffer,
newPackage: boolean
): Promise<WriteResponse> => {
return Promise.resolve({statusCode: 200, newPackage});
};
// Simulate a publication request to the proxy:
const req = writePackageRequest(
{authorization: 'token: abc123'},
createPackument('@soldair/foo', 'next')
.addVersion('1.0.0', 'https://github.com/foo/bar')
.packument()
);
const res = mockResponse();
const npmRequest = nock('https://registry.npmjs.org')
.get('/@soldair%2ffoo')
.reply(
200,
createPackument('@soldair/foo')
.addVersion('0.1.0', 'https://github.com/foo/bar')
.packument()
);
const githubRequest = nock('https://api.github.com')
// user has push access to repo in package.json
.get('/repos/foo/bar')
.reply(200, {permissions: {push: true}})
// most recent release tag on GitHub is v1.0.0
.get('/repos/foo/bar/tags?per_page=100&page=1')
.reply(200, [{name: 'v1.0.0'}]);
const ret = await writePackage('@soldair/foo', req, res);
npmRequest.done();
githubRequest.done();
expect(ret.newPackage).to.equal(false);
expect(ret.statusCode).to.equal(200);
});
it("does not allow PUTs that aren't publications, e.g., dist-tag updates", async () => {
// Fake that there's a releaseAs2FA key in datastore:
writePackage.datastore = Object.assign({}, datastore, {
getPublishKey: async (): Promise<PublishKey | false> => {
return {
username: 'bcoe',
created: 1578630249529,
value: 'deadbeef',
releaseAs2FA: true,
};
},
getUser: async (): Promise<false | User> => {
return {name: 'bcoe', token: 'deadbeef'};
},
});
writePackage.pipeToNpm = (
req: Request,
res: Response,
drainedBody: false | Buffer,
newPackage: boolean
): Promise<WriteResponse> => {
return Promise.resolve({statusCode: 200, newPackage});
};
// simulate a dist-tag update:
const req = writePackageRequest(
{authorization: 'token: abc123'},
'0.2.3'
);
const res = mockResponse();
// A 404 while fetching the packument indicates that the package
// has not yet been created:
const npmRequest = nock('https://registry.npmjs.org')
.get('/@soldair%2ffoo')
.reply(
200,
createPackument('@soldair/foo')
.addVersion('1.0.0', 'https://github.com/foo/bar')
.packument()
);
const githubRequest = nock('https://api.github.com')
// user has push access to repo in package.json
.get('/repos/foo/bar')
.reply(200, {permissions: {push: true}});
const ret = await writePackage('@soldair/foo', req, res);
npmRequest.done();
githubRequest.done();
expect(ret.error).to.match(/used exclusively for publication/);
expect(ret.statusCode).to.equal(400);
});
it('rejects publication if no corresponding release found on GitHub', async () => {
// Fake that there's a releaseAs2FA key in datastore:
writePackage.datastore = Object.assign({}, datastore, {
getPublishKey: async (): Promise<PublishKey | false> => {
return {
username: 'bcoe',
created: 1578630249529,
value: 'deadbeef',
releaseAs2FA: true,
};
},
getUser: async (): Promise<false | User> => {
return {name: 'bcoe', token: 'deadbeef'};
},
});
writePackage.pipeToNpm = (
req: Request,
res: Response,
drainedBody: false | Buffer,
newPackage: boolean
): Promise<WriteResponse> => {
return Promise.resolve({statusCode: 200, newPackage});
};
// Simulate a publication request to the proxy:
const req = writePackageRequest(
{authorization: 'token: abc123'},
createPackument('@soldair/foo')
.addVersion('1.0.0', 'https://github.com/foo/bar')
.packument()
);
const res = mockResponse();
const npmRequest = nock('https://registry.npmjs.org')
.get('/@soldair%2ffoo')
.reply(
200,
createPackument('@soldair/foo')
.addVersion('0.1.0', 'https://github.com/foo/bar')
.packument()
);
const githubRequest = nock('https://api.github.com')
// user has push access to repo in package.json
.get('/repos/foo/bar')
.reply(200, {permissions: {push: true}})
// most recent release tag on GitHub is v0.1.0
.get('/repos/foo/bar/tags?per_page=100&page=1')
.reply(200, [{name: 'v0.1.0'}])
.get('/repos/foo/bar/tags?per_page=100&page=2')
.reply(200, [{name: 'v0.1.0'}])
.get('/repos/foo/bar/tags?per_page=100&page=3')
.reply(200, [{name: 'v0.1.0'}])
.get('/repos/foo/bar/tags?per_page=100&page=4')
.reply(200, [{name: 'v0.1.0'}])
.get('/repos/foo/bar/tags?per_page=100&page=5')
.reply(200, [{name: 'v0.1.0'}])
.get('/repos/foo/bar/tags?per_page=100&page=6')
.reply(200, [{name: 'v0.1.0'}])
.get('/repos/foo/bar/tags?per_page=100&page=7')
.reply(200, [{name: 'v0.1.0'}])
.get('/repos/foo/bar/tags?per_page=100&page=8')
.reply(200, [{name: 'v0.1.0'}])
.get('/repos/foo/bar/tags?per_page=100&page=9')
.reply(200, [{name: 'v0.1.0'}])
.get('/repos/foo/bar/tags?per_page=100&page=10')
.reply(200, [{name: 'v0.1.0'}])
.get('/repos/foo/bar/tags?per_page=100&page=11')
.reply(200, [{name: 'v0.1.0'}]);
const ret = await writePackage('@soldair/foo', req, res);
npmRequest.done();
githubRequest.done();
expect(ret.error).to.match(/matching release v1.0.0 not found/);
expect(ret.statusCode).to.equal(400);
});
it('rejects publication if listing tags rerturns non-200', async () => {
// Fake that there's a releaseAs2FA key in datastore:
writePackage.datastore = Object.assign({}, datastore, {
getPublishKey: async (): Promise<PublishKey | false> => {
return {
username: 'bcoe',
created: 1578630249529,
value: 'deadbeef',
releaseAs2FA: true,
};
},
getUser: async (): Promise<false | User> => {
return {name: 'bcoe', token: 'deadbeef'};
},
});
writePackage.pipeToNpm = (
req: Request,
res: Response,
drainedBody: false | Buffer,
newPackage: boolean
): Promise<WriteResponse> => {
return Promise.resolve({statusCode: 200, newPackage});
};
// Simulate a publication request to the proxy:
const req = writePackageRequest(
{authorization: 'token: abc123'},
createPackument('@soldair/foo')
.addVersion('1.0.0', 'https://github.com/foo/bar')
.packument()
);
const res = mockResponse();
const npmRequest = nock('https://registry.npmjs.org')
.get('/@soldair%2ffoo')
.reply(
200,
createPackument('@soldair/foo')
.addVersion('0.1.0', 'https://github.com/foo/bar')
.packument()
);
const githubRequest = nock('https://api.github.com')
// user has push access to repo in package.json
.get('/repos/foo/bar')
.reply(200, {permissions: {push: true}})
// most recent release tag on GitHub is v0.1.0
.get('/repos/foo/bar/tags?per_page=100&page=1')
.reply(500);
const ret = await writePackage('@soldair/foo', req, res);
npmRequest.done();
githubRequest.done();
expect(ret.error).to.match(/unknown error/);
expect(ret.statusCode).to.equal(500);
});
it('allows package with monorepo token to be updated', async () => {
// Fake that there's a releaseAs2FA key in datastore:
writePackage.datastore = Object.assign({}, datastore, {
getPublishKey: async (): Promise<PublishKey | false> => {
return {
username: 'bcoe',
created: 1578630249529,
value: 'deadbeef',
releaseAs2FA: true,
monorepo: true,
};
},
getUser: async (): Promise<false | User> => {
return {name: 'bcoe', token: 'deadbeef'};
},
});
writePackage.pipeToNpm = (
req: Request,
res: Response,
drainedBody: false | Buffer,
newPackage: boolean
): Promise<WriteResponse> => {
return Promise.resolve({statusCode: 200, newPackage});
};
// Simulate a publication request to the proxy:
const req = writePackageRequest(
{authorization: 'token: abc123'},
createPackument('@soldair/foo')
.addVersion('1.0.0', 'https://github.com/foo/bar')
.packument()
);
const res = mockResponse();
const npmRequest = nock('https://registry.npmjs.org')
.get('/@soldair%2ffoo')
.reply(
200,
createPackument('@soldair/foo')
.addVersion('0.1.0', 'https://github.com/foo/bar')
.packument()
);
const githubRequest = nock('https://api.github.com')
// user has push access to repo in package.json
.get('/repos/foo/bar')
.reply(200, {permissions: {push: true}})
// most recent release tag on GitHub is v1.0.0
.get('/repos/foo/bar/tags?per_page=100&page=1')
.reply(200, [{name: 'foo-v1.0.0'}]);
const ret = await writePackage('@soldair/foo', req, res);
npmRequest.done();
githubRequest.done();
expect(ret.statusCode).to.equal(200);
expect(ret.newPackage).to.equal(false);
});
});
}); | the_stack |
import { css, html, LitElement } from '../deps_app.ts';
import { FilterState, WebtailAppVM } from '../webtail_app_vm.ts';
import { actionIcon, CLEAR_ICON } from './icons.ts';
export const CONSOLE_HTML = html`
<div id="console">
<div id="console-header">
<div id="console-header-filters" class="body2"></div>
<div id="console-header-status">
<div id="console-header-tails" class="overline medium-emphasis-text"></div>
<div id="console-header-qps" class="overline medium-emphasis-text"></div>
<div id="console-header-clear"></div>
</div>
</div>
<code id="console-last-line" class="line">spacer</code>
</div>
`;
export const CONSOLE_CSS = css`
#console {
color: var(--high-emphasis-text-color);
height: 100vh;
width: 100%;
background-color: var(--background-color);
overflow-y: scroll;
overflow-x: hidden;
flex-grow: 1;
}
#console::-webkit-scrollbar {
width: 1rem;
height: 3rem;
background-color: var(--background-color);
}
#console::-webkit-scrollbar-thumb {
background-color: var(--medium-emphasis-text-color);
}
#console-header {
position: sticky;
top: 0;
height: 3.75rem;
background-color: var(--background-color);
display: flex;
padding: 1.25rem 1rem 1rem 0;
}
#console-header-filters {
flex-grow: 1;
color: var(--medium-emphasis-text-color);
font-family: var(--sans-serif-font-family);
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
#console-header-status {
height: 1rem;
display: flex;
flex-direction: column;
min-width: 6rem;
text-align: right;
padding-top: 0.25rem;
user-select: none; -webkit-user-select: none;
}
#console-header-tails {
white-space: nowrap;
}
#console-header-clear {
margin-right: -0.5rem;
margin-left: 1rem;
visibility: hidden;
}
#console-header-clear .action-icon {
padding-right: 0.5rem;
padding-left: 0.5rem;
}
#console .line {
display: block;
font-size: 0.75rem; /* 12px */
line-height: 1.1rem;
font-family: var(--monospace-font-family);
white-space: pre-wrap;
}
#console-last-line {
visibility: hidden;
}
`;
export function initConsole(document: HTMLDocument, vm: WebtailAppVM): () => void {
const consoleDiv = document.getElementById('console') as HTMLDivElement;
const consoleHeaderFiltersDiv = document.getElementById('console-header-filters') as HTMLDivElement;
const consoleHeaderTailsElement = document.getElementById('console-header-tails') as HTMLElement;
const consoleHeaderQpsElement = document.getElementById('console-header-qps') as HTMLElement;
const consoleHeaderClearElement = document.getElementById('console-header-clear') as HTMLElement;
const consoleLastLineElement = document.getElementById('console-last-line') as HTMLElement;
let showingClearButton = false;
vm.logger = (...data) => {
const lineElement = document.createElement('code');
lineElement.className = 'line';
let pos = 0;
while (pos < data.length) {
if (pos > 0) {
lineElement.appendChild(document.createTextNode(', '));
}
const msg = data[pos];
if (typeof msg === 'string') {
const tokens = msg.split('%c');
for (let i = 0; i < tokens.length; i++) {
const span = document.createElement('span');
let rendered = false;
if (i > 0 && i < tokens.length - 1) {
const style = data[pos + i];
span.setAttribute('style', style);
// set special do filter links if applicable
if (typeof style === 'string') {
if (style.includes('x-')) {
const m = /x-durable-object-(class|name|id)\s*:\s*'(.*?)'/.exec(style);
if (m) {
const type = m[1];
const value = m[2];
const logpropName = 'durableObject' + type.substring(0, 1).toUpperCase() + type.substring(1);
const a = document.createElement('a');
a.href = '#';
a.onclick = () => {
vm.setLogpropFilter([ logpropName + ':' + value ]);
vm.onChange();
};
a.appendChild(document.createTextNode(tokens[i]));
span.appendChild(a);
rendered = true;
}
}
}
}
if (!rendered) renderTextIntoSpan(tokens[i], span);
lineElement.appendChild(span);
}
pos += 1 + tokens.length - 1;
} else {
lineElement.appendChild(document.createTextNode(JSON.stringify(msg)));
pos++;
}
}
consoleDiv.insertBefore(lineElement, consoleLastLineElement);
const { scrollHeight, scrollTop, clientHeight } = consoleDiv;
const diff = scrollHeight - scrollTop;
const autoscroll = diff - 16 * 4 <= clientHeight;
// console.log({scrollHeight, scrollTop, clientHeight, diff, autoscroll });
if (autoscroll) {
consoleLastLineElement.scrollIntoView(false /* alignToTop */);
}
if (!showingClearButton) {
consoleHeaderClearElement.style.visibility = 'visible';
showingClearButton = true;
}
};
vm.onResetOutput = () => {
const lines = consoleDiv.querySelectorAll('.line');
lines.forEach(line => {
if (line.id !== 'console-last-line') consoleDiv.removeChild(line);
});
consoleHeaderClearElement.style.visibility = 'hidden';
showingClearButton = false;
};
consoleHeaderQpsElement.textContent = computeQpsText(0);
vm.onQpsChange = qps => {
consoleHeaderQpsElement.textContent = computeQpsText(qps);
};
LitElement.render(actionIcon(CLEAR_ICON, { text: 'Clear', onclick: () => vm.resetOutput() }), consoleHeaderClearElement);
// for (let i = 0; i < 100; i++) vm.logger(`line ${i}`); // generate a bunch of lines to test scrolling
// setInterval(() => { vm.logger(`line ${new Date().toISOString()}`); }, 1000); // generate a line every second to test autoscroll
return () => {
consoleDiv.style.display = vm.selectedAnalyticId ? 'none' : 'block';
consoleHeaderFiltersDiv.style.visibility = vm.profiles.length > 0 ? 'visible' : 'hidden';
consoleHeaderTailsElement.textContent = computeTailsText(vm.tails.size);
LitElement.render(FILTERS_HTML(vm), consoleHeaderFiltersDiv);
};
}
//
const FILTERS_HTML = (vm: WebtailAppVM) => {
return html`Showing <a href="#" @click=${(e: Event) => { e.preventDefault(); vm.editSelectionFields(); }}>${vm.computeSelectionFieldsText()}</a>
for <a href="#" @click=${(e: Event) => { e.preventDefault(); vm.editEventFilter(); }}>${computeEventFilterText(vm.filter)}</a>
with <a href="#" @click=${(e: Event) => { e.preventDefault(); vm.editStatusFilter(); }}>${computeStatusFilterText(vm.filter)}</a>,
<a href="#" @click=${(e: Event) => { e.preventDefault(); vm.editIpAddressFilter(); }}>${computeIpAddressFilterText(vm.filter)}</a>,
<a href="#" @click=${(e: Event) => { e.preventDefault(); vm.editMethodFilter(); }}>${computeMethodFilterText(vm.filter)}</a>,
<a href="#" @click=${(e: Event) => { e.preventDefault(); vm.editSamplingRateFilter(); }}>${computeSamplingRateFilterText(vm.filter)}</a>,
<a href="#" @click=${(e: Event) => { e.preventDefault(); vm.editSearchFilter(); }}>${computeSearchFilterText(vm.filter)}</a>,
<a href="#" @click=${(e: Event) => { e.preventDefault(); vm.editHeaderFilter(); }}>${computeHeaderFilterText(vm.filter)}</a>,
and <a href="#" @click=${(e: Event) => { e.preventDefault(); vm.editLogpropFilter(); }}>${computeLogpropFilterText(vm.filter)}</a>.
${vm.hasAnyFilters() ? html`(<a href="#" @click=${(e: Event) => { e.preventDefault(); vm.resetFilters(); }}>reset</a>)` : ''}`;
};
function computeEventFilterText(filter: FilterState): string {
const { event1 } = filter;
return event1 === 'cron' ? 'CRON trigger events'
: event1 === 'http' ? 'HTTP request events'
: 'all events';
}
function computeStatusFilterText(filter: FilterState): string {
const { status1 } = filter;
return status1 === 'error' ? 'error status'
: status1 === 'success' ? 'success status'
: 'any status';
}
function computeIpAddressFilterText(filter: FilterState): string {
const ipAddress1 = filter.ipAddress1 || [];
return ipAddress1.length === 0 ? 'any IP address'
: ipAddress1.length === 1 ? `IP address of ${ipAddress1[0]}`
: `IP address in [${ipAddress1.join(', ')}]`;
}
function computeMethodFilterText(filter: FilterState): string {
const method1 = filter.method1 || [];
return method1.length === 0 ? 'any method'
: method1.length === 1 ? `method of ${method1[0]}`
: `method in [${method1.join(', ')}]`;
}
function computeSamplingRateFilterText(filter: FilterState): string {
const samplingRate1 = typeof filter.samplingRate1 === 'number' ? filter.samplingRate1 : 1;
return samplingRate1 >= 1 ? 'no sampling'
: `${(Math.max(0, samplingRate1) * 100).toFixed(2)}% sampling rate`;
}
function computeSearchFilterText(filter: FilterState): string {
const { search1 } = filter;
return typeof search1 === 'string' && search1.length > 0 ? `console logs containing "${search1}"`
: 'no search filter';
}
function computeHeaderFilterText(filter: FilterState): string {
const header1 = filter.header1 || [];
return header1.length === 0 ? 'no header filter'
: header1.length === 1 ? `header filter of ${header1[0]}`
: `header filters of [${header1.join(', ')}]`;
}
function computeLogpropFilterText(filter: FilterState): string {
const logprop1 = filter.logprop1 || [];
return logprop1.length === 0 ? 'no logprop filter'
: logprop1.length === 1 ? `logprop filter of ${logprop1[0]}`
: `logprop filters of [${logprop1.join(', ')}]`;
}
function computeTailsText(tailCount: number): string {
return tailCount === 0 ? 'no tails'
: tailCount === 1 ? '1 tail'
: `${tailCount} tails`;
}
function computeQpsText(qps: number): string {
return `${qps.toFixed(2)} qps`;
}
function renderTextIntoSpan(text: string, span: HTMLSpanElement) {
const pattern = /(https:\/\/[^\s)]+|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|[\d0-f]+(:([\d0-f]{0,4})?){5,7})/g;
let m: RegExpExecArray | null;
let i = 0;
while(null !== (m = pattern.exec(text))) {
if (m.index > i) {
span.appendChild(document.createTextNode(text.substring(i, m.index)));
}
const urlOrIp = m[0];
const a = document.createElement('a');
a.href = urlOrIp.startsWith('https://') ? urlOrIp : `https://ipinfo.io/${urlOrIp}`;
a.target = '_blank';
a.rel = 'noreferrer noopener nofollow';
a.appendChild(document.createTextNode(urlOrIp));
span.appendChild(a);
i = m.index + urlOrIp.length;
}
if (i < text.length) {
span.appendChild(document.createTextNode(text.substring(i)));
}
} | the_stack |
import { PagedAsyncIterableIterator } from "@azure/core-paging";
import { TenantAccess } from "../operationsInterfaces";
import * as coreClient from "@azure/core-client";
import * as Mappers from "../models/mappers";
import * as Parameters from "../models/parameters";
import { ApiManagementClient } from "../apiManagementClient";
import {
AccessInformationContract,
TenantAccessListByServiceNextOptionalParams,
TenantAccessListByServiceOptionalParams,
TenantAccessListByServiceResponse,
AccessIdName,
TenantAccessGetEntityTagOptionalParams,
TenantAccessGetEntityTagResponse,
TenantAccessGetOptionalParams,
TenantAccessGetResponse,
AccessInformationCreateParameters,
TenantAccessCreateOptionalParams,
TenantAccessCreateResponse,
AccessInformationUpdateParameters,
TenantAccessUpdateOptionalParams,
TenantAccessUpdateResponse,
TenantAccessRegeneratePrimaryKeyOptionalParams,
TenantAccessRegenerateSecondaryKeyOptionalParams,
TenantAccessListSecretsOptionalParams,
TenantAccessListSecretsResponse,
TenantAccessListByServiceNextResponse
} from "../models";
/// <reference lib="esnext.asynciterable" />
/** Class containing TenantAccess operations. */
export class TenantAccessImpl implements TenantAccess {
private readonly client: ApiManagementClient;
/**
* Initialize a new instance of the class TenantAccess class.
* @param client Reference to the service client
*/
constructor(client: ApiManagementClient) {
this.client = client;
}
/**
* Returns list of access infos - for Git and Management endpoints.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param options The options parameters.
*/
public listByService(
resourceGroupName: string,
serviceName: string,
options?: TenantAccessListByServiceOptionalParams
): PagedAsyncIterableIterator<AccessInformationContract> {
const iter = this.listByServicePagingAll(
resourceGroupName,
serviceName,
options
);
return {
next() {
return iter.next();
},
[Symbol.asyncIterator]() {
return this;
},
byPage: () => {
return this.listByServicePagingPage(
resourceGroupName,
serviceName,
options
);
}
};
}
private async *listByServicePagingPage(
resourceGroupName: string,
serviceName: string,
options?: TenantAccessListByServiceOptionalParams
): AsyncIterableIterator<AccessInformationContract[]> {
let result = await this._listByService(
resourceGroupName,
serviceName,
options
);
yield result.value || [];
let continuationToken = result.nextLink;
while (continuationToken) {
result = await this._listByServiceNext(
resourceGroupName,
serviceName,
continuationToken,
options
);
continuationToken = result.nextLink;
yield result.value || [];
}
}
private async *listByServicePagingAll(
resourceGroupName: string,
serviceName: string,
options?: TenantAccessListByServiceOptionalParams
): AsyncIterableIterator<AccessInformationContract> {
for await (const page of this.listByServicePagingPage(
resourceGroupName,
serviceName,
options
)) {
yield* page;
}
}
/**
* Returns list of access infos - for Git and Management endpoints.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param options The options parameters.
*/
private _listByService(
resourceGroupName: string,
serviceName: string,
options?: TenantAccessListByServiceOptionalParams
): Promise<TenantAccessListByServiceResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, options },
listByServiceOperationSpec
);
}
/**
* Tenant access metadata
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param accessName The identifier of the Access configuration.
* @param options The options parameters.
*/
getEntityTag(
resourceGroupName: string,
serviceName: string,
accessName: AccessIdName,
options?: TenantAccessGetEntityTagOptionalParams
): Promise<TenantAccessGetEntityTagResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, accessName, options },
getEntityTagOperationSpec
);
}
/**
* Get tenant access information details without secrets.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param accessName The identifier of the Access configuration.
* @param options The options parameters.
*/
get(
resourceGroupName: string,
serviceName: string,
accessName: AccessIdName,
options?: TenantAccessGetOptionalParams
): Promise<TenantAccessGetResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, accessName, options },
getOperationSpec
);
}
/**
* Update tenant access information details.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param accessName The identifier of the Access configuration.
* @param ifMatch ETag of the Entity. ETag should match the current entity state from the header
* response of the GET request or it should be * for unconditional update.
* @param parameters Parameters supplied to retrieve the Tenant Access Information.
* @param options The options parameters.
*/
create(
resourceGroupName: string,
serviceName: string,
accessName: AccessIdName,
ifMatch: string,
parameters: AccessInformationCreateParameters,
options?: TenantAccessCreateOptionalParams
): Promise<TenantAccessCreateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
serviceName,
accessName,
ifMatch,
parameters,
options
},
createOperationSpec
);
}
/**
* Update tenant access information details.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param accessName The identifier of the Access configuration.
* @param ifMatch ETag of the Entity. ETag should match the current entity state from the header
* response of the GET request or it should be * for unconditional update.
* @param parameters Parameters supplied to retrieve the Tenant Access Information.
* @param options The options parameters.
*/
update(
resourceGroupName: string,
serviceName: string,
accessName: AccessIdName,
ifMatch: string,
parameters: AccessInformationUpdateParameters,
options?: TenantAccessUpdateOptionalParams
): Promise<TenantAccessUpdateResponse> {
return this.client.sendOperationRequest(
{
resourceGroupName,
serviceName,
accessName,
ifMatch,
parameters,
options
},
updateOperationSpec
);
}
/**
* Regenerate primary access key
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param accessName The identifier of the Access configuration.
* @param options The options parameters.
*/
regeneratePrimaryKey(
resourceGroupName: string,
serviceName: string,
accessName: AccessIdName,
options?: TenantAccessRegeneratePrimaryKeyOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, accessName, options },
regeneratePrimaryKeyOperationSpec
);
}
/**
* Regenerate secondary access key
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param accessName The identifier of the Access configuration.
* @param options The options parameters.
*/
regenerateSecondaryKey(
resourceGroupName: string,
serviceName: string,
accessName: AccessIdName,
options?: TenantAccessRegenerateSecondaryKeyOptionalParams
): Promise<void> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, accessName, options },
regenerateSecondaryKeyOperationSpec
);
}
/**
* Get tenant access information details.
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param accessName The identifier of the Access configuration.
* @param options The options parameters.
*/
listSecrets(
resourceGroupName: string,
serviceName: string,
accessName: AccessIdName,
options?: TenantAccessListSecretsOptionalParams
): Promise<TenantAccessListSecretsResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, accessName, options },
listSecretsOperationSpec
);
}
/**
* ListByServiceNext
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param nextLink The nextLink from the previous successful call to the ListByService method.
* @param options The options parameters.
*/
private _listByServiceNext(
resourceGroupName: string,
serviceName: string,
nextLink: string,
options?: TenantAccessListByServiceNextOptionalParams
): Promise<TenantAccessListByServiceNextResponse> {
return this.client.sendOperationRequest(
{ resourceGroupName, serviceName, nextLink, options },
listByServiceNextOperationSpec
);
}
}
// Operation Specifications
const serializer = coreClient.createSerializer(Mappers, /* isXml */ false);
const listByServiceOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/tenant",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.AccessInformationCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.filter, Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId
],
headerParameters: [Parameters.accept],
serializer
};
const getEntityTagOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/tenant/{accessName}",
httpMethod: "HEAD",
responses: {
200: {
headersMapper: Mappers.TenantAccessGetEntityTagHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.accessName
],
headerParameters: [Parameters.accept],
serializer
};
const getOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/tenant/{accessName}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.AccessInformationContract,
headersMapper: Mappers.TenantAccessGetHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.accessName
],
headerParameters: [Parameters.accept],
serializer
};
const createOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/tenant/{accessName}",
httpMethod: "PUT",
responses: {
200: {
bodyMapper: Mappers.AccessInformationContract,
headersMapper: Mappers.TenantAccessCreateHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters55,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.accessName
],
headerParameters: [
Parameters.accept,
Parameters.contentType,
Parameters.ifMatch1
],
mediaType: "json",
serializer
};
const updateOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/tenant/{accessName}",
httpMethod: "PATCH",
responses: {
200: {
bodyMapper: Mappers.AccessInformationContract,
headersMapper: Mappers.TenantAccessUpdateHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
requestBody: Parameters.parameters56,
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.accessName
],
headerParameters: [
Parameters.accept,
Parameters.contentType,
Parameters.ifMatch1
],
mediaType: "json",
serializer
};
const regeneratePrimaryKeyOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/tenant/{accessName}/regeneratePrimaryKey",
httpMethod: "POST",
responses: {
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.accessName
],
headerParameters: [Parameters.accept],
serializer
};
const regenerateSecondaryKeyOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/tenant/{accessName}/regenerateSecondaryKey",
httpMethod: "POST",
responses: {
204: {},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.accessName
],
headerParameters: [Parameters.accept],
serializer
};
const listSecretsOperationSpec: coreClient.OperationSpec = {
path:
"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/tenant/{accessName}/listSecrets",
httpMethod: "POST",
responses: {
200: {
bodyMapper: Mappers.AccessInformationSecretsContract,
headersMapper: Mappers.TenantAccessListSecretsHeaders
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.accessName
],
headerParameters: [Parameters.accept],
serializer
};
const listByServiceNextOperationSpec: coreClient.OperationSpec = {
path: "{nextLink}",
httpMethod: "GET",
responses: {
200: {
bodyMapper: Mappers.AccessInformationCollection
},
default: {
bodyMapper: Mappers.ErrorResponse
}
},
queryParameters: [Parameters.filter, Parameters.apiVersion],
urlParameters: [
Parameters.$host,
Parameters.resourceGroupName,
Parameters.serviceName,
Parameters.subscriptionId,
Parameters.nextLink
],
headerParameters: [Parameters.accept],
serializer
}; | the_stack |
import { AfterViewInit, Component, EventEmitter, Input, OnInit, Output, ViewChild } from '@angular/core';
import { AmexioMultipleDatePickerComponent } from '../multidatepicker/multidatepicker.component';
import { MultiDateRangePicker } from './multirangedatepicker.component.model';
@Component({
selector: 'amexio-date-range-picker',
templateUrl: './multirangedatepicker.component.html',
})
export class AmexioMultiRangePickerComponent implements OnInit, AfterViewInit {
dateRangePickerFlag = true;
@Input('from-date') newFromDate = new Date();
@Input('to-date') newToDate = new Date();
customRange: any[];
fromCardSelected = false;
toCardSelected = false;
daysOptionToday: any;
daysOptionYesterday: any;
todayIconFlag = false;
yesterdayIconFlag = false;
disabledChkedIndex = 0;
showMultiRangePicker = false;
multiDateRangePickerModel: MultiDateRangePicker;
@Input('disabled-date') disabledDates: any = [];
@Output() change: EventEmitter<any> = new EventEmitter<any>();
@ViewChild(AmexioMultipleDatePickerComponent) child: any;
constructor() {
this.multiDateRangePickerModel = new MultiDateRangePicker();
this.customRange = ['Today', 'Yesterday', 'This week (sun - sat)', 'Last 14 days',
'This month', 'Last 30 days', 'Last month', 'All time',
];
}
ngOnInit() {
}
ngAfterViewInit() {
this.fromCardSelected = this.child.fromcardselected;
this.toCardSelected = this.child.tocardselected;
this.child.altercompleteDaysArray();
if (this.disabledDates) {
// chk if today or yesterday are in list of disabled dates
this.disabledDates.forEach((element: any) => {
const dfrom = new Date(element.from);
const dto = new Date(element.to);
const currentd = new Date();
const yesterdayd = new Date(currentd.getFullYear(), currentd.getMonth(), currentd.getDate() - 1);
if ((currentd <= dto) && (currentd >= dfrom)) {
this.todayIconFlag = true;
}
if ((yesterdayd <= dto) && (yesterdayd >= dfrom)) {
this.yesterdayIconFlag = true;
}
});
if (this.todayIconFlag) {
// update default frmdate and todate
this.updateFromTodate();
}
}
}
updateFromTodate() {
// increment and send date as argument to fun
let flag = false;
// store returned value = call function()
// if returned value is false call fun agn
let incdate = new Date();
do {
incdate = new Date(incdate.getFullYear(), incdate.getMonth(), incdate.getDate() + 1);
flag = this.chkDisableddate(incdate);
} while (!flag);
if (flag) {
// update from to date
this.child.fromdate = incdate;
this.child.todate = incdate;
// update selected date in completeDaysArray
this.alterCompleteDaysArray(incdate);
}
}
chkDisableddate(incrementedDate: Date): boolean {
// loop disabled days and if match found return true
let retflag = false;
this.disabledDates.forEach((element: any, index: number) => {
const dfrom = new Date(element.from);
const dto = new Date(element.to);
// chk for match
if (!(incrementedDate >= dfrom && incrementedDate <= dto)) {
retflag = true;
}
});
return retflag;
}
clearSelectedFlag() {
this.child.completeDaysArray.forEach((month: any) => {
month.montharray.forEach((monthrowarray: any) => {
monthrowarray.forEach((individualday: any) => {
if (individualday.selected || individualday.from || individualday.to) {
individualday.selected = false;
individualday.from = false;
individualday.to = false;
}
});
});
});
}
alterCompleteDaysArray(incdate: Date) {
this.clearSelectedFlag();
this.child.completeDaysArray.forEach((month: any) => {
month.montharray.forEach((monthrowarray: any) => {
// monthrow.mon
// monthrowarray.forEach(monthrow => {
monthrowarray.forEach((individualday: any) => {
if ((individualday.date.getFullYear() === incdate.getFullYear()) &&
(individualday.date.getMonth() === incdate.getMonth()) &&
(individualday.date.getDate() === incdate.getDate())) {
individualday.selected = true;
individualday.from = true;
individualday.to = true;
}
});
// });
});
});
}
selectRangeOption(option: any) {
switch (option) {
case 'Today':
const currentdate = new Date();
if (this.child.fromcardselected) {
// set fromdate to currentdate
this.child.fromdate = currentdate;
}
if (this.child.tocardselected) {
// set todate to currentdate
this.child.todate = currentdate;
}
this.newFromDate = this.child.fromdate;
this.newToDate = this.child.todate;
this.change.emit({ fromDate: this.child.fromdate, toDate: this.child.todate });
break;
case 'Yesterday':
const yesterdaydate = new Date();
yesterdaydate.setDate(yesterdaydate.getDate() - 1);
if (this.child.fromcardselected) {
// reinitialize fromdate to yesterday date
this.child.fromdate = yesterdaydate;
}
if (this.child.tocardselected) {
// reinitialize todate to yesterday date
this.child.todate = yesterdaydate;
}
this.newFromDate = this.child.fromdate;
this.newToDate = this.child.todate;
this.change.emit({ fromDate: this.child.fromdate, toDate: this.child.todate });
break;
case 'This week (sun - sat)':
// find index of day of currentdate
// and substract tht index frm current day
const startdate = new Date();
const dayindex = startdate.getDay();
const enddate = new Date();
startdate.setDate(startdate.getDate() - dayindex);
// set frmdate
this.child.fromdate = startdate;
// set todate
enddate.setDate(enddate.getDate() - dayindex + 6);
this.child.todate = enddate;
this.newFromDate = this.child.fromdate;
this.newToDate = this.child.todate;
this.change.emit({ fromDate: this.child.fromdate, toDate: this.child.todate });
break;
case 'Last 14 days':
const lastday = new Date();
this.child.todate = lastday;
const firstday = new Date();
firstday.setDate(firstday.getDate() - 14);
this.child.fromdate = firstday;
this.newFromDate = this.child.fromdate;
this.newToDate = this.child.todate;
this.change.emit({ fromDate: this.child.fromdate, toDate: this.child.todate });
break;
case 'This month':
const d1 = new Date();
const firstmonthday = new Date(d1.getFullYear(), d1.getMonth(), 1);
this.child.fromdate = firstmonthday;
const lastmonthday = new Date(d1.getFullYear(), d1.getMonth() + 1, 0);
this.child.todate = lastmonthday;
this.newFromDate = this.child.fromdate;
this.newToDate = this.child.todate;
this.change.emit({ fromDate: this.child.fromdate, toDate: this.child.todate });
break;
case 'Last 30 days':
const d2 = new Date();
const first30thdate = new Date();
const last30thdate = new Date();
this.child.todate = last30thdate;
first30thdate.setDate(d2.getDate() - 29);
this.child.fromdate = first30thdate;
this.newFromDate = this.child.fromdate;
this.newToDate = this.child.todate;
this.change.emit({ fromDate: this.child.fromdate, toDate: this.child.todate });
break;
case 'Last month':
const d3 = new Date();
const fday = new Date(d3.getFullYear(), d3.getMonth() - 1, 1);
const lday = new Date(d3.getFullYear(), d3.getMonth(), 0);
this.child.fromdate = fday;
this.child.todate = lday;
this.newFromDate = this.child.fromdate;
this.newToDate = this.child.todate;
this.change.emit({ fromDate: this.child.fromdate, toDate: this.child.todate });
break;
case 'All time':
const d4 = new Date();
d4.setFullYear(1970);
d4.setMonth(0);
d4.setDate(1);
this.child.fromdate = d4;
this.child.todate = new Date();
this.newFromDate = this.child.fromdate;
this.newToDate = this.child.todate;
this.change.emit({ fromDate: this.child.fromdate, toDate: this.child.todate });
break;
case '30 Days upto today':
break;
case '30 Days upto yesterday':
break;
}
this.child.altercompleteDaysArray();
}
ResetDaysTillToday() {
// change fromdate
const d = new Date();
const newfrm = new Date(d.getFullYear(), d.getMonth(), (d.getDate() - this.multiDateRangePickerModel.daysOptionToday + 1));
this.child.fromdate = newfrm;
// change todate
const newto = new Date();
this.child.todate = newto;
this.child.altercompleteDaysArray();
this.change.emit({ fromDate: this.child.fromdate, toDate: this.child.todate });
}
ResetDaysTillYesterday() {
// change fromdate
const d = new Date();
const newfrm = new Date(d.getFullYear(), d.getMonth(), d.getDate() - this.multiDateRangePickerModel.daysOptionYesterday);
this.child.fromdate = newfrm;
// change todate
const newto = new Date(d.getFullYear(), d.getMonth(), d.getDate() - 1);
this.child.todate = newto;
this.child.altercompleteDaysArray();
this.change.emit({ fromDate: this.child.fromdate, toDate: this.child.todate });
}
onDateClick(event: any) {
this.newFromDate = this.child.fromdate;
this.newToDate = this.child.todate;
this.change.emit({ fromDate: this.child.fromdate, toDate: this.child.todate });
}
openPicker() {
this.showMultiRangePicker = !this.showMultiRangePicker;
}
} | the_stack |
import { Sortable } from '../src/sortable/index';
import { createElement, remove, EventHandler, getComponent, Draggable } from '@syncfusion/ej2-base';
import { profile , inMB, getMemoryProfile } from './common.spec';
interface EventOptions {
name: String;
listener: Function;
debounce?: Function;
}
interface EventData extends Element {
__eventList: EventList;
}
interface EventList {
events?: EventOptions[];
}
function setMouseCordinates(eventarg: any, x: number, y: number): Object {
eventarg.pageX = x;
eventarg.pageY = y;
eventarg.clientX = x;
eventarg.clientY = y;
return eventarg;
}
function copyObject(source: any, destination: any): Object {
for (let prop in source) {
destination[prop] = source[prop];
}
return destination;
}
function getEventObject(eventType: string, eventName: string): Object {
let tempEvent: any = document.createEvent(eventType);
tempEvent.initEvent(eventName, true, true);
let returnObject: any = copyObject(tempEvent, {}) as any;
returnObject.preventDefault = () => { return true; };
return returnObject;
}
function getEventList(element: any): EventOptions[] {
if ('__eventList' in element) {
return (<EventData>element).__eventList.events;
} else {
(<EventData>element).__eventList = {};
return (<EventData>element).__eventList.events = [];
}
}
/**
* @param {} 'Sortable'
* @param {} function(
*/
describe('Sortable', () => {
beforeAll(() => {
const isDef: any = (o: any) => o !== undefined && o !== null;
if (!isDef(window.performance)) {
console.log('Unsupported environment, window.performance.memory is unavailable');
this.skip(); // skips test (in Chai)
return;
}
});
afterAll(() => {
document.body.innerHTML = null;
})
let sortable: any;
let element: HTMLElement = createElement('div');
for (let i: number = 0; i < 8; i++) {
element.appendChild(createElement('div'));
}
document.body.appendChild(element);
describe('DOM', () => {
afterEach(() => {
sortable.destroy();
});
it('Default - without item class', () => {
sortable = new Sortable(element, {});
expect(element.classList.contains('e-sortable')).toBeTruthy();
expect(element.firstElementChild.classList.contains('e-sort-item')).toBeTruthy();
});
it('Default - with item class', () => {
for (let i: number = 0; i < 8; i++) {
element.children[i].classList.add('e-item');
}
sortable = new Sortable(element, { itemClass: 'e-item' });
expect(element.firstElementChild.classList.contains('e-item')).toBeTruthy();
expect(element.firstElementChild.getAttribute('tabindex')).toEqual(null);
});
});
describe('Property', () => {
afterEach(() => {
sortable.destroy();
});
it('itemClass', () => {
sortable = new Sortable(element, { itemClass: 'e-item' });
expect(element.firstElementChild.classList.contains('e-item')).toBeTruthy();
expect(sortable.itemClass).toEqual('e-item');
});
it('enableAnimation', () => {
sortable = new Sortable(element, { enableAnimation: true });
expect(sortable.enableAnimation).toEqual(true);
});
it('scope', () => {
sortable = new Sortable(element, { scope: 'list' });
expect(sortable.scope).toEqual('list');
});
});
describe('Actions', () => {
afterEach(() => {
sortable.destroy();
let elemEvent: EventOptions[] = getEventList(element);
elemEvent.splice(0, elemEvent.length);
let docEvent: EventOptions[] = getEventList((<any>document));
docEvent.splice(0, docEvent.length);
});
let mousedown: any; let mousemove: any; let mouseUp: any; let dragStartEvent: jasmine.Spy;
beforeEach(() => {
mousedown= getEventObject('MouseEvents', 'mousedown');
mousedown = setMouseCordinates(mousedown, 17, 13);
mousemove = getEventObject('MouseEvents', 'mousemove');
mousemove = setMouseCordinates(mousemove, 17, 40);
mousedown.target = mousedown.currentTarget = element;
});
it('Sorting from different target', () => {
sortable = new Sortable(element, { itemClass: 'e-item' });
EventHandler.trigger(element, 'mousedown', mousedown);
mousemove.srcElement = mousemove.target = mousemove.toElement = document.body;
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mousemove.srcElement = mousemove.target = mousemove.toElement = document.body;
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mouseUp = getEventObject('MouseEvents', 'mouseup');
mouseUp.srcElement = mouseUp.target = mouseUp.toElement = document.body;
EventHandler.trigger(<any>(document), 'mouseup', mouseUp);
});
it('Sorting within same element', () => {
sortable = new Sortable(element, { itemClass: 'e-item' });
EventHandler.trigger(element, 'mousedown', mousedown);
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[0];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mousemove = setMouseCordinates(mousemove, 50, 50);
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[0];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mouseUp = getEventObject('MouseEvents', 'mouseup');
mouseUp.srcElement = mouseUp.target = mouseUp.toElement = element.children[0];
EventHandler.trigger(<any>(document), 'mouseup', mouseUp);
});
it('Sorting mulitiple times', () => {
sortable = new Sortable(element, { itemClass: 'e-item', placeHolder: function(args: any) {
return args.target.cloneNode(true);
} });
EventHandler.trigger(element, 'mousedown', mousedown);
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[0];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mousemove = setMouseCordinates(mousemove, 50, 50);
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[3];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mousemove = setMouseCordinates(mousemove, 40, 70);
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[2];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mousemove = setMouseCordinates(mousemove, 60, 90);
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[5];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mouseUp = getEventObject('MouseEvents', 'mouseup');
mouseUp.srcElement = mouseUp.target = mouseUp.toElement = element.children[5];
EventHandler.trigger(<any>(document), 'mouseup', mouseUp);
});
});
describe('Property - callback functions', () => {
let mousedown: any; let mousemove: any; let mouseUp: any; let dragStartEvent: jasmine.Spy;
beforeEach(() => {
mousedown= getEventObject('MouseEvents', 'mousedown');
mousedown = setMouseCordinates(mousedown, 17, 13);
mousemove = getEventObject('MouseEvents', 'mousemove');
mousemove = setMouseCordinates(mousemove, 17, 40);
mousedown.target = mousedown.currentTarget = element;
dragStartEvent = jasmine.createSpy('dragStart');
});
afterEach(() => {
sortable.destroy();
let elemEvent: EventOptions[] = getEventList(element);
elemEvent.splice(0, elemEvent.length);
let docEvent: EventOptions[] = getEventList((<any>document));
docEvent.splice(0, docEvent.length);
});
it('helper', () => {
sortable = new Sortable(element, { itemClass: 'e-item', dragStart: dragStartEvent });
EventHandler.trigger(element, 'mousedown', mousedown);
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[1];
sortable.helper = (args: any): HTMLElement => {
(args.sender as HTMLElement).style.width = args.element.offsetWidth + 'px';
expect(args.element).toEqual(sortable.element);
expect(args.sender).toEqual(element.children[1]);
return args.sender.cloneNode(true) as HTMLElement;
}
EventHandler.trigger(element, 'mousedown', mousedown);
mousemove.srcElement = mousemove.target = mousemove.toElement = element;
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[1];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
expect(dragStartEvent).toHaveBeenCalled();
mouseUp = getEventObject('MouseEvents', 'mouseup');
mouseUp.srcElement = mouseUp.target = mouseUp.toElement = element.children[1];
EventHandler.trigger(<any>(document), 'mouseup', mouseUp);
});
it('placeHolder', () => {
sortable = new Sortable(element, { itemClass: 'e-item', dragStart: dragStartEvent, placeHolder: (args: any): HTMLElement => {
(args.target as HTMLElement).style.width = args.element.offsetWidth + 'px';
expect(args.element).toEqual(sortable.element);
expect(args.grabbedElement).toEqual(element.children[1]);
expect(args.target).toEqual(mousemove.toElement);
return args.target.cloneNode(true);
} });
EventHandler.trigger(element, 'mousedown', mousedown);
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[1];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mousemove = setMouseCordinates(mousemove, 50, 50);
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[0];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
expect(dragStartEvent).toHaveBeenCalled();
mouseUp = getEventObject('MouseEvents', 'mouseup');
mouseUp.srcElement = mouseUp.target = mouseUp.toElement = element.children[0];
EventHandler.trigger(<any>(document), 'mouseup', mouseUp);
});
});
describe('Combined sortable', () => {
let mousedown: any; let mousemove: any; let mouseUp: any; let dragEndEvent: jasmine.Spy;
let element2: HTMLElement = createElement('div', { id: 'sortable2' });
document.body.appendChild(element2);
beforeEach(() => {
mousedown= getEventObject('MouseEvents', 'mousedown');
mousedown = setMouseCordinates(mousedown, 17, 13);
mousemove = getEventObject('MouseEvents', 'mousemove');
mousemove = setMouseCordinates(mousemove, 17, 40);
mousedown.target = mousedown.currentTarget = element;
dragEndEvent = jasmine.createSpy('dragEnd');
});
afterEach(() => {
sortable.destroy();
let elemEvent: EventOptions[] = getEventList(element);
elemEvent.splice(0, elemEvent.length);
let docEvent: EventOptions[] = getEventList((<any>document));
docEvent.splice(0, docEvent.length);
});
it('With empty sortable', () => {
sortable = new Sortable(element, { itemClass: 'e-item', drop: dragEndEvent, scope: 'combined' });
let sortable2: any = new Sortable(element2, { itemClass: 'e-item2', scope: 'combined' });
expect(sortable2.element.childElementCount).toEqual(0);
EventHandler.trigger(element, 'mousedown', mousedown);
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[1];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mousemove = setMouseCordinates(mousemove, 50, 50);
mousemove.srcElement = mousemove.target = mousemove.toElement = element2;
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mouseUp = getEventObject('MouseEvents', 'mouseup');
mouseUp.srcElement = mouseUp.target = mouseUp.toElement = element2;
EventHandler.trigger(<any>(document), 'mouseup', mouseUp);
expect(dragEndEvent).toHaveBeenCalled();
expect(sortable2.element.childElementCount).toEqual(1);
sortable2.destroy();
});
it('Between two sortables', () => {
sortable = new Sortable(element, { itemClass: 'e-item', dragStart: dragEndEvent, scope: 'combined' });
for (let i: number = 0; i < 5; i++) {
element2.appendChild(createElement('div', { className: 'e-item2' }));
}
let sortable2: any = new Sortable(element2, { itemClass: 'e-item2', scope: 'combined' });
expect(sortable2.element.childElementCount).toEqual(6);
EventHandler.trigger(element, 'mousedown', mousedown);
let target: Element = element.children[1];
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[1];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mousemove = setMouseCordinates(mousemove, 50, 50);
mousemove.srcElement = mousemove.target = mousemove.toElement = element2.children[2];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mouseUp = getEventObject('MouseEvents', 'mouseup');
mouseUp.srcElement = mouseUp.target = mouseUp.toElement = element2.children[2];
EventHandler.trigger(<any>(document), 'mouseup', mouseUp);
expect(sortable2.element.childElementCount).toEqual(7);
expect(sortable2.element.children[2]).toEqual(target);
expect(dragEndEvent).toHaveBeenCalled();
element.appendChild(createElement('div'));
sortable2.destroy();
});
it('Between two sortables - append to last element', () => {
sortable = new Sortable(element, { itemClass: 'e-item', dragStart: dragEndEvent, scope: 'combined', placeHolder: function(args: any) {
return args.target.cloneNode(true);
} });
let sortable2: any = new Sortable(element2, { itemClass: 'e-item2', scope: 'combined', placeHolder: function(args: any) {
return args.target.cloneNode(true);
}});
EventHandler.trigger(element, 'mousedown', mousedown);
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[1];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mousemove = setMouseCordinates(mousemove, 50, 50);
mousemove.srcElement = mousemove.target = mousemove.toElement = element2.children[6];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mouseUp = getEventObject('MouseEvents', 'mouseup');
mousemove = setMouseCordinates(mousemove, 100, 100);
mousemove.srcElement = mousemove.target = mousemove.toElement = document.body;
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mouseUp.srcElement = mouseUp.target = mouseUp.toElement = document.body;
EventHandler.trigger(<any>(document), 'mouseup', mouseUp);
expect(dragEndEvent).toHaveBeenCalled();
sortable2.destroy();
remove(element2);
});
});
describe('Disabled support', () => {
let mousedown: any; let mousemove: any; let mouseUp: any; let dragEndEvent: jasmine.Spy;
let element2: HTMLElement = createElement('div', { id: 'sortable2' });
it('With empty sortable', () => {
element.appendChild(createElement('div'));
for (let i: number = 0; i < 7; i++) {
element.children[i].classList.remove('e-item');
if (i === 2 || i === 4 || i === 6) {
element.children[i].classList.add('e-disabled');
}
}
mousedown= getEventObject('MouseEvents', 'mousedown');
mousedown = setMouseCordinates(mousedown, 17, 13);
mousemove = getEventObject('MouseEvents', 'mousemove');
mousemove = setMouseCordinates(mousemove, 17, 40);
mousedown.target = mousedown.currentTarget = element;
dragEndEvent = jasmine.createSpy('dragEnd');
sortable = new Sortable(element, { drop: dragEndEvent });
EventHandler.trigger(element, 'mousedown', mousedown);
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[1];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mousemove = setMouseCordinates(mousemove, 50, 50);
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[5];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mouseUp = getEventObject('MouseEvents', 'mouseup');
mouseUp.srcElement = mouseUp.target = mouseUp.toElement = element.children[5];
EventHandler.trigger(<any>(document), 'mouseup', mouseUp);
expect(dragEndEvent).toHaveBeenCalled();
sortable.destroy();
[2, 4, 6].forEach((idx: number) => {
element.children[idx].classList.remove('e-disabled');
});
});
});
describe('Events', () => {
let mousedown: any; let mousemove: any; let mouseUp: any;
beforeEach(() => {
mousedown= getEventObject('MouseEvents', 'mousedown');
mousedown = setMouseCordinates(mousedown, 17, 13);
mousemove = getEventObject('MouseEvents', 'mousemove');
mousemove = setMouseCordinates(mousemove, 17, 40);
mousedown.target = mousedown.currentTarget = element;
});
afterEach(() => {
sortable.destroy();
});
it('dragStart', () => {
sortable = new Sortable(element, {
dragStart: (args: any) => {
expect(args.element).toEqual(sortable.element);
expect(args.event.type).toEqual('mousemove');
expect(args.target).toEqual(mousemove.toElement);
}
});
EventHandler.trigger(element, 'mousedown', mousedown);
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[3];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mouseUp = getEventObject('MouseEvents', 'mouseup');
mouseUp.srcElement = mouseUp.target = mouseUp.toElement = element.children[2];
EventHandler.trigger(<any>(document), 'mouseup', mouseUp);
});
it('drag', () => {
sortable = new Sortable(element, {
drag: (args: any) => {
expect(args.element).toEqual(sortable.element);
expect(args.event.type).toEqual('mousemove');
expect(args.target).toEqual(mousemove.toElement);
}
});
EventHandler.trigger(element, 'mousedown', mousedown);
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[1];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mousemove = setMouseCordinates(mousemove, 50, 50);
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[2];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mouseUp = getEventObject('MouseEvents', 'mouseup');
mouseUp.srcElement = mouseUp.target = mouseUp.toElement = element.children[2];
EventHandler.trigger(<any>(document), 'mouseup', mouseUp);
});
it('Drop - without placeholder', () => {
sortable = new Sortable(element, {
drop: (args: any) => {
expect(args.element).toEqual(sortable.element);
expect(args.event.type).toEqual('mousemove');
expect(args.target).toEqual(mousemove.toElement);
expect(args.previousIndex).toEqual(1);
expect(args.currentIndex).toEqual(2);
expect(args.helper).toEqual(element.querySelector('.e-sortableclone'));
expect(args.droppedElement).toEqual(element.children[2]);
expect(args.scope).toEqual(null);
}
});
EventHandler.trigger(element, 'mousedown', mousedown);
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[1];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mousemove = setMouseCordinates(mousemove, 50, 50);
mousemove.srcElement = mousemove.target = mousemove.toElement = element.children[2];
EventHandler.trigger(<any>(document), 'mousemove', mousemove);
mouseUp = getEventObject('MouseEvents', 'mouseup');
mouseUp.srcElement = mouseUp.target = mouseUp.toElement = element.children[2];
EventHandler.trigger(<any>(document), 'mouseup', mouseUp);
(getComponent(element, Draggable) as any).intDestroy(mousemove);
});
});
describe('onPropertyChanged', () => {
it('itemClass', () => {
sortable = new Sortable(element);
expect(element.firstElementChild.classList.contains('e-sort-item')).toBeTruthy();
sortable.itemClass = 'new-item';
sortable.dataBind();
expect(element.firstElementChild.classList.contains('e-sort-item')).toBeFalsy();
expect(element.firstElementChild.classList.contains('new-item')).toBeTruthy();
sortable.itemClass = '';
sortable.dataBind();
expect(element.firstElementChild.classList.contains('new-item')).toBeFalsy();
sortable.destroy();
});
});
describe('methods', () => {
it('destroy method', () => {
sortable = new Sortable(element, {});
sortable.destroy();
expect(element.classList.contains('e-sortable')).toBeFalsy();
});
it('getModuleName method', () => {
sortable = new Sortable(element, {});
expect(sortable.getModuleName()).toEqual('sortable');
sortable.destroy();
});
it('moveTo - Within element', () => {
sortable = new Sortable(element, {});
let targetElement: Element = sortable.element.firstElementChild;
// Before sorted.
expect(sortable.getIndex(targetElement)).toEqual(0);
sortable.moveTo(null, [0, 3, 6]);
// After sorted.
expect(sortable.getIndex(targetElement)).toEqual(5);
targetElement = sortable.element.children[5];
// Before sorted.
expect(sortable.getIndex(targetElement)).toEqual(5);
sortable.moveTo(null, [5, 7], 2);
expect(sortable.getIndex(targetElement)).toEqual(2);
// After sorted.
sortable.destroy();
});
it('moveTo - Between different element', () => {
let element2: any = createElement('div');
document.body.appendChild(element2);
sortable = new Sortable(element, {});
let sortable2 = new Sortable(element2, {});
expect(sortable.element.childElementCount).toEqual(8);
expect(sortable2.element.childElementCount).toEqual(0);
sortable.moveTo(sortable2.element);
expect(sortable.element.childElementCount).toEqual(0);
expect(sortable2.element.childElementCount).toEqual(8);
sortable.destroy(); sortable2.destroy();
remove(element2);
});
});
it('memory leak', () => {
profile.sample();
let average: any = inMB(profile.averageChange);
// check average change in memory samples to not be over 10MB
expect(average).toBeLessThan(10);
let memory: any = inMB(getMemoryProfile());
// check the final memory usage against the first usage, there should be little change if everything was properly deallocated
expect(memory).toBeLessThan(profile.samples[0] + 0.25);
});
}); | the_stack |
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField,
PropertyPaneSlider,
PropertyPaneToggle,
IWebPartContext
} from '@microsoft/sp-webpart-base';
import { Version } from '@microsoft/sp-core-library';
import * as strings from 'NewsTickerStrings';
import { INewsTickerWebPartProps } from './INewsTickerWebPartProps';
//Imports property pane custom fields
import { PropertyFieldCustomList, CustomListFieldType } from 'sp-client-custom-fields/lib/PropertyFieldCustomList';
import { PropertyFieldColorPickerMini } from 'sp-client-custom-fields/lib/PropertyFieldColorPickerMini';
import { PropertyFieldFontPicker } from 'sp-client-custom-fields/lib/PropertyFieldFontPicker';
import { PropertyFieldFontSizePicker } from 'sp-client-custom-fields/lib/PropertyFieldFontSizePicker';
export default class NewsTickerWebPart extends BaseClientSideWebPart<INewsTickerWebPartProps> {
private guid: string;
/**
* @function
* Web part contructor.
*/
public constructor(context?: IWebPartContext) {
super();
this.guid = this.getGuid();
//Hack: to invoke correctly the onPropertyChange function outside this class
//we need to bind this object on it first
this.onPropertyPaneFieldChanged = this.onPropertyPaneFieldChanged.bind(this);
}
/**
* @function
* Gets WP data version
*/
protected get dataVersion(): Version {
return Version.parse('1.0');
}
/**
* @function
* Renders HTML code
*/
public render(): void {
var html = '';
html += `
<div class="news-${this.guid} color-${this.guid}">
<span>${this.properties.title}</span>
<ul>
`;
for (var i = 0; i < this.properties.items.length; i++) {
var item = this.properties.items[i];
if (item['Enable'] != 'false') {
html += '<li><a href="' + item['Link Url'] + '">' + item['Title'] + '</li>';
}
}
var paused = 'paused';
if (this.properties.pausedMouseHover === false)
paused = 'running';
html += `
</ul>
</div>
<style>
@keyframes ticker {
0% {margin-top: 0}
25% {margin-top: -30px}
50% {margin-top: -60px}
75% {margin-top: -90px}
100% {margin-top: 0}
}
.news-${this.guid} {
box-shadow: inset 0 -15px 30px rgba(0,0,0,0.4), 0 5px 10px rgba(0,0,0,0.5);
width: ${this.properties.width};
height: ${this.properties.height};
overflow: hidden;
border-radius: ${this.properties.borderRadius}px;
padding: 3px;
-webkit-user-select: none
}
.news-${this.guid} span {
float: left;
color: ${this.properties.fontColor};
padding: 6px;
position: relative;
top: 1%;
border-radius: ${this.properties.borderRadius}px;
box-shadow: inset 0 -15px 30px rgba(0,0,0,0.4);
font: ${this.properties.fontSize} ${this.properties.font};
-webkit-font-smoothing: antialiased;
-webkit-user-select: none;
cursor: pointer
}
.news-${this.guid} ul {
float: left;
padding-left: 20px;
animation: ticker ${this.properties.speed}s cubic-bezier(1, 0, .5, 0) infinite;
-webkit-user-select: none
}
.news-${this.guid} ul li {line-height: ${this.properties.height}; list-style: none }
.news-${this.guid} ul li a {
color: ${this.properties.fontColorMssg};
text-decoration: none;
font: ${this.properties.fontSizeMssg} ${this.properties.fontMssg};
-webkit-font-smoothing: antialiased;
-webkit-user-select: none
}
.news-${this.guid} ul:hover { animation-play-state: ${paused} }
.news-${this.guid} span:hover+ul { animation-play-state: ${paused} }
/* OTHER COLORS */
.color-${this.guid} { background: ${this.properties.backgroundColor} }
</style>
`;
this.domElement.innerHTML = html;
}
/**
* @function
* Generates a GUID
*/
private getGuid(): string {
return this.s4() + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' +
this.s4() + '-' + this.s4() + this.s4() + this.s4();
}
/**
* @function
* Generates a GUID part
*/
private s4(): string {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
/**
* @function
* PropertyPanel settings definition
*/
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
displayGroupsAsAccordion: true,
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyFieldCustomList('items', {
label: strings.Items,
value: this.properties.items,
headerText: strings.ManageItems,
fields: [
{ id: 'Title', title: 'Title', required: true, type: CustomListFieldType.string },
{ id: 'Enable', title: 'Enable', required: true, type: CustomListFieldType.boolean },
{ id: 'Link Url', title: 'Link Url', required: true, hidden: true, type: CustomListFieldType.string }
],
onPropertyChange: this.onPropertyPaneFieldChanged,
render: this.render.bind(this),
disableReactivePropertyChanges: this.disableReactivePropertyChanges,
context: this.context,
properties: this.properties,
key: 'newsTickerListField'
}),
PropertyPaneSlider('speed', {
label: strings.Speed,
min: 1,
max: 20,
step: 1
}),
PropertyPaneToggle('pausedMouseHover', {
label: strings.PausedMouseHover
})
]
},
{
groupName: strings.LayoutGroupName,
groupFields: [
PropertyPaneTextField('width', {
label: strings.Width
}),
PropertyPaneTextField('height', {
label: strings.Height
}),
PropertyPaneSlider('borderRadius', {
label: strings.BorderRadius,
min: 0,
max: 10,
step: 1
}),
PropertyFieldColorPickerMini('backgroundColor', {
label: strings.BackgroundColor,
initialColor: this.properties.backgroundColor,
onPropertyChange: this.onPropertyPaneFieldChanged,
render: this.render.bind(this),
disableReactivePropertyChanges: this.disableReactivePropertyChanges,
properties: this.properties,
key: 'newsTickerBgColorField'
})
]
},
{
groupName: strings.TitleGroupName,
groupFields: [
PropertyPaneTextField('title', {
label: strings.Title
}),
PropertyFieldFontPicker('font', {
label: strings.Font,
initialValue: this.properties.font,
onPropertyChange: this.onPropertyPaneFieldChanged,
render: this.render.bind(this),
disableReactivePropertyChanges: this.disableReactivePropertyChanges,
properties: this.properties,
key: 'newsTickerFontField'
}),
PropertyFieldFontSizePicker('fontSize', {
label: strings.FontSize,
initialValue: this.properties.fontSize,
usePixels: true,
preview: true,
onPropertyChange: this.onPropertyPaneFieldChanged,
render: this.render.bind(this),
disableReactivePropertyChanges: this.disableReactivePropertyChanges,
properties: this.properties,
key: 'newsTickerFontSizeField'
}),
PropertyFieldColorPickerMini('fontColor', {
label: strings.FontColor,
initialColor: this.properties.fontColor,
onPropertyChange: this.onPropertyPaneFieldChanged,
render: this.render.bind(this),
disableReactivePropertyChanges: this.disableReactivePropertyChanges,
properties: this.properties,
key: 'newsTickerFontColorField'
})
]
},
{
groupName: strings.ItemsGroupName,
groupFields: [
PropertyFieldFontPicker('fontMssg', {
label: strings.Font,
initialValue: this.properties.fontMssg,
onPropertyChange: this.onPropertyPaneFieldChanged,
render: this.render.bind(this),
disableReactivePropertyChanges: this.disableReactivePropertyChanges,
properties: this.properties,
key: 'newsTickerFontMssgField'
}),
PropertyFieldFontSizePicker('fontSizeMssg', {
label: strings.FontSize,
initialValue: this.properties.fontSizeMssg,
usePixels: true,
preview: true,
onPropertyChange: this.onPropertyPaneFieldChanged,
render: this.render.bind(this),
disableReactivePropertyChanges: this.disableReactivePropertyChanges,
properties: this.properties,
key: 'newsTickerFontSizeMssgField'
}),
PropertyFieldColorPickerMini('fontColorMssg', {
label: strings.FontColor,
initialColor: this.properties.fontColorMssg,
onPropertyChange: this.onPropertyPaneFieldChanged,
render: this.render.bind(this),
disableReactivePropertyChanges: this.disableReactivePropertyChanges,
properties: this.properties,
key: 'newsTickerFontColorMssgField'
})
]
}
]
}
]
};
}
} | the_stack |
import * as vscode from 'vscode';
import { sendToServer, ServerCommand, HelpServerResponse, TemplateServerResponse, sendToRepl, IdsServerResponse, HotloadClientRequest, HelpClientRequest, TemplateClientRequest, TemplateScope, AproposServerResponse, IdsClientRequest } from './net';
import { uriToLuaPath } from './util';
import { plainToClass } from 'class-transformer';
import { QuickPickItem } from 'vscode';
import * as fs from "fs";
import * as util from "util";
import { stringify } from 'querystring';
export async function requireThisFileInRepl() {
let editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
let uri = editor.document.uri;
let luaPath = uriToLuaPath(uri);
let name = luaPath.substr(luaPath.lastIndexOf(".") + 1);
var code = `${name} = require("${luaPath}")`;
await sendToRepl(code, true);
}
var pathCache: Map<vscode.Uri, string> = new Map();
class FileItem implements QuickPickItem {
label: string;
description: string;
constructor(public uri: vscode.Uri) {
var label = pathCache.get(uri);
if (label === undefined) {
label = uriToLuaPath(uri);
pathCache.set(uri, label);
}
this.label = label;
this.description = uri.path;
}
}
export async function insertRequireStatement() {
let selection = vscode.workspace.findFiles("**/*.lua")
.then((cands) => vscode.window.showQuickPick(cands.map((c) => new FileItem(c)), {}))
.then((file) => {
if (file === undefined) {
return;
}
let luaPath = uriToLuaPath(file.uri);
let name = luaPath.substr(luaPath.lastIndexOf(".") + 1);
var code = `local ${name} = require("${luaPath}")\n`;
vscode.window.activeTextEditor?.insertSnippet(new vscode.SnippetString(code));
});
}
var OutputTerminal: vscode.Terminal;
export async function launchGame() {
if (OutputTerminal === undefined) {
OutputTerminal = vscode.window.createTerminal("OpenNefia Output");
if (process.platform === "win32") {
OutputTerminal.sendText("$cd = Split-Path (Get-Location); $env:PATH = \"$cd\\lib\\libvips;$env:PATH\"", true);
}
}
OutputTerminal.sendText("taskkill /F /FI \"WINDOWTITLE eq OpenNefia\" /T | Out-Null; love --console .", true);
OutputTerminal.show();
}
var DocumentationWindow: vscode.OutputChannel;
function showHelpWindow(helpResponse: HelpServerResponse) {
if (helpResponse.doc === "") {
vscode.window.showInformationMessage(helpResponse.message!!);
} else {
if (DocumentationWindow === undefined) {
DocumentationWindow = vscode.window.createOutputChannel("OpenNefia Help");
}
DocumentationWindow.clear();
DocumentationWindow.append(helpResponse.doc);
DocumentationWindow.show();
}
}
export async function describeAtPoint() {
let editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
let wordRange = editor.document.getWordRangeAtPosition(editor.selection.start, /[_\w][_\w\.:]*/g)!!;
let dottedSymbol = editor.document.getText(wordRange);
await sendToServer(ServerCommand.Help, new HelpClientRequest(dottedSymbol))
.then((json) => {
let helpResponse = plainToClass(HelpServerResponse, json);
showHelpWindow(helpResponse);
});
}
function unescapeString(str: string) {
return str
.replace(/\\\\/g, '\\')
.replace(/\\\"/g, '\"')
.replace(/\\\//g, '\/')
.replace(/\\b/g, '\b')
.replace(/\\f/g, '\f')
.replace(/\\n/g, '\n')
.replace(/\\r/g, '\r')
.replace(/\\t/g, '\t')
.replace(/\\{/g, '{')
.replace(/\\}/g, '}')
.replace(/^['"]/, '')
.replace(/['"]$/, '');
};
export async function insertTemplate() {
await sendToServer(ServerCommand.Template, new TemplateClientRequest("", true, true, TemplateScope.OptionalCommented))
.then((json) => {
let templateResponse = plainToClass(TemplateServerResponse, json);
vscode.window.activeTextEditor?.insertSnippet(new vscode.SnippetString(unescapeString(templateResponse.template)));
});
}
export async function insertId() {
await sendToServer(ServerCommand.Ids, new IdsClientRequest(""))
.then((json) => {
let idsResponse = plainToClass(IdsServerResponse, json);
return vscode.window.showQuickPick(idsResponse.ids);
})
.then((id) => { if (id) { vscode.window.activeTextEditor?.insertSnippet(new vscode.SnippetString(`"${id}"`)); } });
}
export async function hotloadThisFile() {
let editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
let openFile = editor.document.uri;
let luaPath = uriToLuaPath(openFile);
await vscode.commands.executeCommand('workbench.action.files.save');
await sendToServer(ServerCommand.Hotload, new HotloadClientRequest(luaPath))
.then(() => vscode.window.showInformationMessage("Hotloaded path " + luaPath + "."));
}
export async function resetDrawLayers() {
await sendToRepl("Input.back_to_field()");
}
export async function sendSelectionToRepl() {
let editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
let selection = editor.selection;
if (selection.isEmpty) {
return;
}
let code = editor.document.getText(selection);
await sendToRepl(code);
}
export async function sendFileToRepl() {
let editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
let code = editor.document.getText();
await sendToRepl(code);
}
class AproposItem implements QuickPickItem {
label: string;
description: string;
constructor(data: any) {
this.label = data[0];
this.description = data[1];
}
}
export async function searchDocumentation() {
await sendToServer(ServerCommand.Apropos, new HelpClientRequest(""))
.then(async (json) => {
let response = plainToClass(AproposServerResponse, json);
let read = util.promisify(fs.readFile);
let buffer = await read(response.path);
let candidates = JSON.parse(buffer.toString());
return vscode.window.showQuickPick<AproposItem>(candidates.map((c: any) => new AproposItem(c)), {});
})
.then((cand) => {
if (cand) {
return sendToServer(ServerCommand.Help, new HelpClientRequest(cand.label));
}
})
.then((json) => {
let helpResponse = plainToClass(HelpServerResponse, json);
showHelpWindow(helpResponse);
});
}
export async function makeScratchBuffer() {
let date = new Date(); "%Y-%m-%d_%H-%M-%S.lua"
let filename = `${date.getFullYear()}-${date.getMonth()}-${date.getDay()}_${date.getHours()}-${date.getMinutes()}-${date.getSeconds()}.lua`;
let root = vscode.workspace.rootPath;
let fullPath = vscode.Uri.file(root + "/scratch/" + filename);
let content = `-- Write some code here, then send it to the REPL with Ctrl+Shift+S (default).
`;
let workspaceEdit = new vscode.WorkspaceEdit();
workspaceEdit.createFile(fullPath, { ignoreIfExists: true });
await vscode.workspace.applyEdit(workspaceEdit)
.then(() => vscode.workspace.openTextDocument(fullPath))
.then((document) => vscode.window.showTextDocument(document, 1, false))
.then((editor) => editor.edit(edit => edit.insert(new vscode.Position(0, 0), content)));
}
function validateModId(name: string): string | null {
if (!name.match(/^[_a-zA-Z][_a-zA-Z0-9]*$/)) {
return `'${name}' is not a valid identifier (must consist of lowercase letters, numbers and underscores only, cannot start with a number)`;
}
return null;
}
function createFile(workspaceEdit: vscode.WorkspaceEdit, path: vscode.Uri, content: string) {
workspaceEdit.createFile(path, { ignoreIfExists: true });
let edit = new vscode.TextEdit(new vscode.Range(0, 0, 0, 0), content);
workspaceEdit.set(path, [edit]);
}
export async function createNewMod() {
let root = vscode.workspace.rootPath;
await vscode.window.showInputBox({ validateInput: validateModId, prompt: "Mod ID (must be a Lua identifier)" })
.then(async (modId) => {
if (modId) {
let workspaceEdit = new vscode.WorkspaceEdit();
let modFile = vscode.Uri.file(root + `/mod/${modId}/mod.lua`);
let modFileContent =
`return {
id = "${modId}",
version = "0.1.0",
dependencies = {
elona = ">= 0.1.0"
}
}`;
createFile(workspaceEdit, modFile, modFileContent);
let initFile = vscode.Uri.file(root + `/mod/${modId}/init.lua`);
let initFileContent =
`-- Load this mod in-game with Ctrl+Shift+R.
local Log = require ("api.Log")
Log.info("Hello from %s!", _MOD_ID)`;
createFile(workspaceEdit, initFile, initFileContent);
await vscode.workspace.applyEdit(workspaceEdit);
return vscode.workspace.openTextDocument(initFile)
.then(() => vscode.window.showTextDocument(modFile))
.then(() => vscode.window.showTextDocument(initFile))
.then(() => vscode.workspace.saveAll());
}
});
}
function validateEventHandlerDescription(desc: string): string | null {
if (desc.length === 0) {
return "Description cannot be empty."
}
return null;
}
export async function insertEventHandler() {
await sendToServer(ServerCommand.Ids, new IdsClientRequest("base.event"))
.then((json) => {
let idsResponse = plainToClass(IdsServerResponse, json);
return vscode.window.showQuickPick(idsResponse.ids);
})
.then(async (eventId) => {
if (eventId) {
let description = await vscode.window.showInputBox({ prompt: "Event handler description", validateInput: validateEventHandlerDescription });
if (description) {
// TODO: There's some room for IDE smartness here, like
// inserting placeholders for the valid arguments in "params".
let code =
`Event.register("${eventId}", "${description}",
function(receiver, params, result)
\${0}
end)`;
vscode.window.activeTextEditor?.insertSnippet(new vscode.SnippetString(code));
}
}
});
} | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type OnboardingPersonalizationModalTestsQueryVariables = {
query: string;
count: number;
};
export type OnboardingPersonalizationModalTestsQueryResponse = {
readonly " $fragmentRefs": FragmentRefs<"OnboardingPersonalizationModal_artists">;
};
export type OnboardingPersonalizationModalTestsQuery = {
readonly response: OnboardingPersonalizationModalTestsQueryResponse;
readonly variables: OnboardingPersonalizationModalTestsQueryVariables;
};
/*
query OnboardingPersonalizationModalTestsQuery(
$query: String!
$count: Int!
) {
...OnboardingPersonalizationModal_artists_1bcUq5
}
fragment OnboardingPersonalizationModal_artists_1bcUq5 on Query {
searchConnection(query: $query, mode: AUTOSUGGEST, first: $count, entities: [ARTIST]) {
edges {
node {
__typename
imageUrl
href
displayLabel
... on Artist {
id
internalID
slug
name
initials
href
is_followed: isFollowed
nationality
birthday
deathday
image {
url
}
}
... on Node {
__isNode: __typename
id
}
}
cursor
}
pageInfo {
endCursor
hasNextPage
}
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = {
"defaultValue": null,
"kind": "LocalArgument",
"name": "count"
},
v1 = {
"defaultValue": null,
"kind": "LocalArgument",
"name": "query"
},
v2 = {
"kind": "Variable",
"name": "query",
"variableName": "query"
},
v3 = [
{
"kind": "Literal",
"name": "entities",
"value": [
"ARTIST"
]
},
{
"kind": "Variable",
"name": "first",
"variableName": "count"
},
{
"kind": "Literal",
"name": "mode",
"value": "AUTOSUGGEST"
},
(v2/*: any*/)
],
v4 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
v5 = {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "String"
},
v6 = {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "String"
},
v7 = {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "ID"
};
return {
"fragment": {
"argumentDefinitions": [
(v0/*: any*/),
(v1/*: any*/)
],
"kind": "Fragment",
"metadata": null,
"name": "OnboardingPersonalizationModalTestsQuery",
"selections": [
{
"args": [
{
"kind": "Variable",
"name": "count",
"variableName": "count"
},
(v2/*: any*/)
],
"kind": "FragmentSpread",
"name": "OnboardingPersonalizationModal_artists"
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": [
(v1/*: any*/),
(v0/*: any*/)
],
"kind": "Operation",
"name": "OnboardingPersonalizationModalTestsQuery",
"selections": [
{
"alias": null,
"args": (v3/*: any*/),
"concreteType": "SearchableConnection",
"kind": "LinkedField",
"name": "searchConnection",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "SearchableEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "imageUrl",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "href",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "displayLabel",
"storageKey": null
},
{
"kind": "InlineFragment",
"selections": [
(v4/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "internalID",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "slug",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "name",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "initials",
"storageKey": null
},
{
"alias": "is_followed",
"args": null,
"kind": "ScalarField",
"name": "isFollowed",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "nationality",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "birthday",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "deathday",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "image",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "url",
"storageKey": null
}
],
"storageKey": null
}
],
"type": "Artist",
"abstractKey": null
},
{
"kind": "InlineFragment",
"selections": [
(v4/*: any*/)
],
"type": "Node",
"abstractKey": "__isNode"
}
],
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "cursor",
"storageKey": null
}
],
"storageKey": null
},
{
"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
}
],
"storageKey": null
},
{
"alias": null,
"args": (v3/*: any*/),
"filters": [
"query",
"mode",
"entities"
],
"handle": "connection",
"key": "OnboardingPersonalizationModal__searchConnection",
"kind": "LinkedHandle",
"name": "searchConnection"
}
]
},
"params": {
"id": "28169aba4b9650853f5af5c1f06860cd",
"metadata": {
"relayTestingSelectionTypeInfo": {
"searchConnection": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "SearchableConnection"
},
"searchConnection.edges": {
"enumValues": null,
"nullable": true,
"plural": true,
"type": "SearchableEdge"
},
"searchConnection.edges.cursor": (v5/*: any*/),
"searchConnection.edges.node": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Searchable"
},
"searchConnection.edges.node.__isNode": (v5/*: any*/),
"searchConnection.edges.node.__typename": (v5/*: any*/),
"searchConnection.edges.node.birthday": (v6/*: any*/),
"searchConnection.edges.node.deathday": (v6/*: any*/),
"searchConnection.edges.node.displayLabel": (v6/*: any*/),
"searchConnection.edges.node.href": (v6/*: any*/),
"searchConnection.edges.node.id": (v7/*: any*/),
"searchConnection.edges.node.image": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Image"
},
"searchConnection.edges.node.image.url": (v6/*: any*/),
"searchConnection.edges.node.imageUrl": (v6/*: any*/),
"searchConnection.edges.node.initials": (v6/*: any*/),
"searchConnection.edges.node.internalID": (v7/*: any*/),
"searchConnection.edges.node.is_followed": {
"enumValues": null,
"nullable": true,
"plural": false,
"type": "Boolean"
},
"searchConnection.edges.node.name": (v6/*: any*/),
"searchConnection.edges.node.nationality": (v6/*: any*/),
"searchConnection.edges.node.slug": (v7/*: any*/),
"searchConnection.pageInfo": {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "PageInfo"
},
"searchConnection.pageInfo.endCursor": (v6/*: any*/),
"searchConnection.pageInfo.hasNextPage": {
"enumValues": null,
"nullable": false,
"plural": false,
"type": "Boolean"
}
}
},
"name": "OnboardingPersonalizationModalTestsQuery",
"operationKind": "query",
"text": null
}
};
})();
(node as any).hash = '5ef54bc3ac986956677b92498b3e86c1';
export default node; | the_stack |
// @noLib: true
//// interface Foo {
//// _0: 0;
//// _1: 1;
//// _2: 2;
//// _3: 3;
//// _4: 4;
//// _5: 5;
//// _6: 6;
//// _7: 7;
//// _8: 8;
//// _9: 9;
//// _10: 10;
//// _11: 11;
//// _12: 12;
//// _13: 13;
//// _14: 14;
//// _15: 15;
//// _16: 16;
//// _17: 17;
//// _18: 18;
//// _19: 19;
//// _20: 20;
//// _21: 21;
//// _22: 22;
//// _23: 23;
//// _24: 24;
//// _25: 25;
//// _26: 26;
//// _27: 27;
//// _28: 28;
//// _29: 29;
//// _30: 30;
//// _31: 31;
//// _32: 32;
//// _33: 33;
//// _34: 34;
//// _35: 35;
//// _36: 36;
//// _37: 37;
//// _38: 38;
//// _39: 39;
//// _40: 40;
//// _41: 41;
//// _42: 42;
//// _43: 43;
//// _44: 44;
//// _45: 45;
//// _46: 46;
//// _47: 47;
//// _48: 48;
//// _49: 49;
//// _50: 50;
//// _51: 51;
//// _52: 52;
//// _53: 53;
//// _54: 54;
//// _55: 55;
//// _56: 56;
//// _57: 57;
//// _58: 58;
//// _59: 59;
//// _60: 60;
//// _61: 61;
//// _62: 62;
//// _63: 63;
//// _64: 64;
//// _65: 65;
//// _66: 66;
//// _67: 67;
//// _68: 68;
//// _69: 69;
//// _70: 70;
//// _71: 71;
//// _72: 72;
//// _73: 73;
//// _74: 74;
//// _75: 75;
//// _76: 76;
//// _77: 77;
//// _78: 78;
//// _79: 79;
//// _80: 80;
//// _81: 81;
//// _82: 82;
//// _83: 83;
//// _84: 84;
//// _85: 85;
//// _86: 86;
//// _87: 87;
//// _88: 88;
//// _89: 89;
//// _90: 90;
//// _91: 91;
//// _92: 92;
//// _93: 93;
//// _94: 94;
//// _95: 95;
//// _96: 96;
//// _97: 97;
//// _98: 98;
//// _99: 99;
//// _100: 100;
//// _101: 101;
//// _102: 102;
//// _103: 103;
//// _104: 104;
//// _105: 105;
//// _106: 106;
//// _107: 107;
//// _108: 108;
//// _109: 109;
//// _110: 110;
//// _111: 111;
//// _112: 112;
//// _113: 113;
//// _114: 114;
//// _115: 115;
//// _116: 116;
//// _117: 117;
//// _118: 118;
//// _119: 119;
//// _120: 120;
//// _121: 121;
//// _122: 122;
//// _123: 123;
//// _124: 124;
//// _125: 125;
//// _126: 126;
//// _127: 127;
//// _128: 128;
//// _129: 129;
//// _130: 130;
//// _131: 131;
//// _132: 132;
//// _133: 133;
//// _134: 134;
//// _135: 135;
//// _136: 136;
//// _137: 137;
//// _138: 138;
//// _139: 139;
//// _140: 140;
//// _141: 141;
//// _142: 142;
//// _143: 143;
//// _144: 144;
//// _145: 145;
//// _146: 146;
//// _147: 147;
//// _148: 148;
//// _149: 149;
//// _150: 150;
//// _151: 151;
//// _152: 152;
//// _153: 153;
//// _154: 154;
//// _155: 155;
//// _156: 156;
//// _157: 157;
//// _158: 158;
//// _159: 159;
//// _160: 160;
//// _161: 161;
//// _162: 162;
//// _163: 163;
//// _164: 164;
//// _165: 165;
//// _166: 166;
//// _167: 167;
//// _168: 168;
//// _169: 169;
//// _170: 170;
//// _171: 171;
//// _172: 172;
//// _173: 173;
//// _174: 174;
//// _175: 175;
//// _176: 176;
//// _177: 177;
//// _178: 178;
//// _179: 179;
//// _180: 180;
//// _181: 181;
//// _182: 182;
//// _183: 183;
//// _184: 184;
//// _185: 185;
//// _186: 186;
//// _187: 187;
//// _188: 188;
//// _189: 189;
//// _190: 190;
//// _191: 191;
//// _192: 192;
//// _193: 193;
//// _194: 194;
//// _195: 195;
//// _196: 196;
//// _197: 197;
//// _198: 198;
//// _199: 199;
//// _200: 200;
//// _201: 201;
//// _202: 202;
//// _203: 203;
//// _204: 204;
//// _205: 205;
//// _206: 206;
//// _207: 207;
//// _208: 208;
//// _209: 209;
//// _210: 210;
//// _211: 211;
//// _212: 212;
//// _213: 213;
//// _214: 214;
//// _215: 215;
//// _216: 216;
//// _217: 217;
//// _218: 218;
//// _219: 219;
//// _220: 220;
//// _221: 221;
//// _222: 222;
//// _223: 223;
//// _224: 224;
//// _225: 225;
//// _226: 226;
//// _227: 227;
//// _228: 228;
//// _229: 229;
//// _230: 230;
//// _231: 231;
//// _232: 232;
//// _233: 233;
//// _234: 234;
//// _235: 235;
//// _236: 236;
//// _237: 237;
//// _238: 238;
//// _239: 239;
//// _240: 240;
//// _241: 241;
//// _242: 242;
//// _243: 243;
//// _244: 244;
//// _245: 245;
//// _246: 246;
//// _247: 247;
//// _248: 248;
//// _249: 249;
//// _250: 250;
//// _251: 251;
//// _252: 252;
//// _253: 253;
//// _254: 254;
//// _255: 255;
//// _256: 256;
//// _257: 257;
//// _258: 258;
//// _259: 259;
//// _260: 260;
//// _261: 261;
//// _262: 262;
//// _263: 263;
//// _264: 264;
//// _265: 265;
//// _266: 266;
//// _267: 267;
//// _268: 268;
//// _269: 269;
//// _270: 270;
//// _271: 271;
//// _272: 272;
//// _273: 273;
//// _274: 274;
//// _275: 275;
//// _276: 276;
//// _277: 277;
//// _278: 278;
//// _279: 279;
//// _280: 280;
//// _281: 281;
//// _282: 282;
//// _283: 283;
//// _284: 284;
//// _285: 285;
//// _286: 286;
//// _287: 287;
//// _288: 288;
//// _289: 289;
//// _290: 290;
//// _291: 291;
//// _292: 292;
//// _293: 293;
//// _294: 294;
//// _295: 295;
//// _296: 296;
//// _297: 297;
//// _298: 298;
//// _299: 299;
//// _300: 300;
//// _301: 301;
//// _302: 302;
//// _303: 303;
//// _304: 304;
//// _305: 305;
//// _306: 306;
//// _307: 307;
//// _308: 308;
//// _309: 309;
//// _310: 310;
//// _311: 311;
//// _312: 312;
//// _313: 313;
//// _314: 314;
//// _315: 315;
//// _316: 316;
//// _317: 317;
//// _318: 318;
//// _319: 319;
//// _320: 320;
//// _321: 321;
//// _322: 322;
//// _323: 323;
//// _324: 324;
//// _325: 325;
//// _326: 326;
//// _327: 327;
//// _328: 328;
//// _329: 329;
//// _330: 330;
//// _331: 331;
//// _332: 332;
//// _333: 333;
//// _334: 334;
//// _335: 335;
//// _336: 336;
//// _337: 337;
//// _338: 338;
//// _339: 339;
//// _340: 340;
//// _341: 341;
//// _342: 342;
//// _343: 343;
//// _344: 344;
//// _345: 345;
//// _346: 346;
//// _347: 347;
//// _348: 348;
//// _349: 349;
//// _350: 350;
//// _351: 351;
//// _352: 352;
//// _353: 353;
//// _354: 354;
//// _355: 355;
//// _356: 356;
//// _357: 357;
//// _358: 358;
//// _359: 359;
//// _360: 360;
//// _361: 361;
//// _362: 362;
//// _363: 363;
//// _364: 364;
//// _365: 365;
//// _366: 366;
//// _367: 367;
//// _368: 368;
//// _369: 369;
//// _370: 370;
//// _371: 371;
//// _372: 372;
//// _373: 373;
//// _374: 374;
//// _375: 375;
//// _376: 376;
//// _377: 377;
//// _378: 378;
//// _379: 379;
//// _380: 380;
//// _381: 381;
//// _382: 382;
//// _383: 383;
//// _384: 384;
//// _385: 385;
//// _386: 386;
//// _387: 387;
//// _388: 388;
//// _389: 389;
//// _390: 390;
//// _391: 391;
//// _392: 392;
//// _393: 393;
//// _394: 394;
//// _395: 395;
//// _396: 396;
//// _397: 397;
//// _398: 398;
//// _399: 399;
//// _400: 400;
//// _401: 401;
//// _402: 402;
//// _403: 403;
//// _404: 404;
//// _405: 405;
//// _406: 406;
//// _407: 407;
//// _408: 408;
//// _409: 409;
//// _410: 410;
//// _411: 411;
//// _412: 412;
//// _413: 413;
//// _414: 414;
//// _415: 415;
//// _416: 416;
//// _417: 417;
//// _418: 418;
//// _419: 419;
//// _420: 420;
//// _421: 421;
//// _422: 422;
//// _423: 423;
//// _424: 424;
//// _425: 425;
//// _426: 426;
//// _427: 427;
//// _428: 428;
//// _429: 429;
//// _430: 430;
//// _431: 431;
//// _432: 432;
//// _433: 433;
//// _434: 434;
//// _435: 435;
//// _436: 436;
//// _437: 437;
//// _438: 438;
//// _439: 439;
//// _440: 440;
//// _441: 441;
//// _442: 442;
//// _443: 443;
//// _444: 444;
//// _445: 445;
//// _446: 446;
//// _447: 447;
//// _448: 448;
//// _449: 449;
//// _450: 450;
//// _451: 451;
//// _452: 452;
//// _453: 453;
//// _454: 454;
//// _455: 455;
//// _456: 456;
//// _457: 457;
//// _458: 458;
//// _459: 459;
//// _460: 460;
//// _461: 461;
//// _462: 462;
//// _463: 463;
//// _464: 464;
//// _465: 465;
//// _466: 466;
//// _467: 467;
//// _468: 468;
//// _469: 469;
//// _470: 470;
//// _471: 471;
//// _472: 472;
//// _473: 473;
//// _474: 474;
//// _475: 475;
//// _476: 476;
//// _477: 477;
//// _478: 478;
//// _479: 479;
//// _480: 480;
//// _481: 481;
//// _482: 482;
//// _483: 483;
//// _484: 484;
//// _485: 485;
//// _486: 486;
//// _487: 487;
//// _488: 488;
//// _489: 489;
//// _490: 490;
//// _491: 491;
//// _492: 492;
//// _493: 493;
//// _494: 494;
//// _495: 495;
//// _496: 496;
//// _497: 497;
//// _498: 498;
//// _499: 499;
//// }
//// type A/*1*/ = keyof Foo;
//// type Exclude<T, U> = T extends U ? never : T;
//// type Less/*2*/ = Exclude<A, "_0">;
//// function f<T extends A>(s: T, x: Exclude<A, T>, y: string) {}
//// f("_499", /*3*/);
//// type Decomposed/*4*/ = {[K in A]: Foo[K]}
//// type LongTuple/*5*/ = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17.18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70];
//// type DeeplyMapped/*6*/ = {[K in keyof Foo]: {[K2 in keyof Foo]: [K, K2, Foo[K], Foo[K2]]}}
goTo.marker("1");
verify.quickInfoIs(`type A = "_0" | "_1" | "_2" | "_3" | "_4" | "_5" | "_6" | "_7" | "_8" | "_9" | "_10" | "_11" | "_12" | "_13" | "_14" | "_15" | "_16" | "_17" | "_18" | "_19" | "_20" | "_21" | "_22" | "_23" | "_24" | ... 474 more ... | "_499"`);
goTo.marker("2");
verify.quickInfoIs(`type Less = "_1" | "_2" | "_3" | "_4" | "_5" | "_6" | "_7" | "_8" | "_9" | "_10" | "_11" | "_12" | "_13" | "_14" | "_15" | "_16" | "_17" | "_18" | "_19" | "_20" | "_21" | "_22" | "_23" | "_24" | "_25" | ... 473 more ... | "_499"`);
goTo.marker("3");
verify.signatureHelp({
marker: "3",
text: `f(s: "_499", x: "_0" | "_1" | "_2" | "_3" | "_4" | "_5" | "_6" | "_7" | "_8" | "_9" | "_10" | "_11" | "_12" | "_13" | "_14" | "_15" | "_16" | "_17" | "_18" | "_19" | "_20" | "_21" | "_22" | "_23" | "_24" | ... 473 more ... | "_498", y: string): void`
});
goTo.marker("4");
verify.quickInfoIs(`type Decomposed = {
_0: 0;
_1: 1;
_2: 2;
_3: 3;
_4: 4;
_5: 5;
_6: 6;
_7: 7;
_8: 8;
_9: 9;
_10: 10;
_11: 11;
_12: 12;
_13: 13;
_14: 14;
_15: 15;
_16: 16;
_17: 17;
_18: 18;
_19: 19;
_20: 20;
_21: 21;
_22: 22;
_23: 23;
_24: 24;
_25: 25;
_26: 26;
_27: 27;
_28: 28;
_29: 29;
_30: 30;
... 468 more ...;
_499: 499;
}`);
goTo.marker("5");
verify.quickInfoIs(`type LongTuple = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17.18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, ... 27 more ..., 70]`);
goTo.marker("6");
verify.quickInfoIs(`type DeeplyMapped = {
_0: {
_0: ["_0", "_0", 0, 0];
_1: ["_0", "_1", 0, 1];
_2: ["_0", "_2", 0, 2];
_3: ["_0", "_3", 0, 3];
_4: ["_0", "_4", 0, 4];
_5: ["_0", "_5", 0, 5];
_6: ["_0", "_6", 0, 6];
_7: ["_0", "_7", 0, 7];
... 491 more ...;
_499: [...];
};
... 498 more ...;
_499: {
...;
};
}`); | the_stack |
export enum Types {
AUTO,
FULL,
PIXEL,
PERCENT,
MINUS,
INHERIT,
VALUE,
THIN, // 100
ULTRALIGHT, // 200
LIGHT, // 300
REGULAR, // 400
MEDIUM, // 500
SEMIBOLD, // 600
BOLD, // 700
HEAVY, // 800
BLACK, // 900
THIN_ITALIC, // 100
ULTRALIGHT_ITALIC, // 200
LIGHT_ITALIC, // 300
ITALIC, // 400
MEDIUM_ITALIC, // 500
SEMIBOLD_ITALIC, // 600
BOLD_ITALIC, // 700
HEAVY_ITALIC, // 800
BLACK_ITALIC, // 900
OTHER,
NONE,
OVERLINE,
LINE_THROUGH,
UNDERLINE,
LEFT,
CENTER,
RIGHT,
LEFT_REVERSE,
CENTER_REVERSE,
RIGHT_REVERSE,
TOP,
BOTTOM,
MIDDLE,
REPEAT,
REPEAT_X,
REPEAT_Y,
MIRRORED_REPEAT,
MIRRORED_REPEAT_X,
MIRRORED_REPEAT_Y,
NORMAL,
CLIP,
ELLIPSIS,
CENTER_ELLIPSIS,
NO_WRAP,
NO_SPACE,
PRE,
PRE_LINE,
WRAP,
// keyboard type
ASCII,
NUMBER,
URL,
NUMBER_PAD,
PHONE,
NAME_PHONE,
EMAIL,
DECIMAL,
TWITTER,
SEARCH,
ASCII_NUMBER,
// keyboard return type
GO,
JOIN,
NEXT,
ROUTE,
// SEARCH,
SEND,
DONE,
EMERGENCY,
CONTINUE,
}
export enum ValueType {
AUTO = Types.AUTO,
FULL = Types.FULL,
PIXEL = Types.PIXEL,
PERCENT = Types.PERCENT,
MINUS = Types.MINUS,
}
export enum TextValueType {
INHERIT = Types.INHERIT,
VALUE = Types.VALUE,
}
export enum BackgroundPositionType {
PIXEL = Types.PIXEL,
PERCENT = Types.PERCENT,
LEFT = Types.LEFT,
RIGHT = Types.RIGHT,
CENTER = Types.CENTER,
TOP = Types.TOP,
BOTTOM = Types.BOTTOM,
}
export enum BackgroundSizeType {
AUTO = Types.AUTO,
PIXEL = Types.PIXEL,
PERCENT = Types.PERCENT,
}
export enum TextStyleEnum {
THIN = Types.THIN, // 100
ULTRALIGHT = Types.ULTRALIGHT, // 200
LIGHT = Types.LIGHT, // 300
REGULAR = Types.REGULAR, // 400
MEDIUM = Types.MEDIUM, // 500
SEMIBOLD = Types.SEMIBOLD, // 600
BOLD = Types.BOLD, // 700
HEAVY = Types.HEAVY, // 800
BLACK = Types.BLACK, // 900
THIN_ITALIC = Types.THIN_ITALIC, // 100
ULTRALIGHT_ITALIC = Types.ULTRALIGHT_ITALIC, // 200
LIGHT_ITALIC = Types.LIGHT_ITALIC, // 300
ITALIC = Types.ITALIC, // 400
MEDIUM_ITALIC = Types.MEDIUM_ITALIC, // 500
SEMIBOLD_ITALIC = Types.SEMIBOLD_ITALIC, // 600
BOLD_ITALIC = Types.BOLD_ITALIC, // 700
HEAVY_ITALIC = Types.HEAVY_ITALIC, // 800
BLACK_ITALIC = Types.BLACK_ITALIC, // 900
OTHER = Types.OTHER,
}
export enum TextDecorationEnum {
NONE = Types.NONE,
OVERLINE = Types.OVERLINE,
LINE_THROUGH = Types.LINE_THROUGH,
UNDERLINE = Types.UNDERLINE,
}
export enum TextAlign {
LEFT = Types.LEFT,
CENTER = Types.CENTER,
RIGHT = Types.RIGHT,
LEFT_REVERSE = Types.LEFT_REVERSE,
CENTER_REVERSE = Types.CENTER_REVERSE,
RIGHT_REVERSE = Types.RIGHT_REVERSE,
}
export enum TextOverflowEnum {
NORMAL = Types.NORMAL,
CLIP = Types.CLIP,
ELLIPSIS = Types.ELLIPSIS,
CENTER_ELLIPSIS = Types.CENTER_ELLIPSIS,
}
export enum Align {
LEFT = Types.LEFT,
RIGHT = Types.RIGHT,
CENTER = Types.CENTER,
TOP = Types.TOP,
BOTTOM = Types.BOTTOM,
NONE = Types.NONE,
}
export enum ContentAlign {
LEFT = Types.LEFT,
RIGHT = Types.RIGHT,
TOP = Types.TOP,
BOTTOM = Types.BOTTOM,
}
export enum Repeat {
NONE = Types.NONE,
REPEAT = Types.REPEAT,
REPEAT_X = Types.REPEAT_X,
REPEAT_Y = Types.REPEAT_Y,
MIRRORED_REPEAT = Types.MIRRORED_REPEAT,
MIRRORED_REPEAT_X = Types.MIRRORED_REPEAT_X,
MIRRORED_REPEAT_Y = Types.MIRRORED_REPEAT_Y,
}
export enum Direction {
NONE = Types.NONE,
LEFT = Types.LEFT,
RIGHT = Types.RIGHT,
TOP = Types.TOP,
BOTTOM = Types.BOTTOM,
}
export enum TextWhiteSpaceEnum {
NORMAL = Types.NORMAL,
NO_WRAP = Types.NO_WRAP,
NO_SPACE = Types.NO_SPACE,
PRE = Types.PRE,
PRE_LINE = Types.PRE_LINE,
WRAP = Types.WRAP,
}
export enum KeyboardType {
NORMAL = Types.NORMAL,
ASCII = Types.ASCII,
NUMBER = Types.NUMBER,
URL = Types.URL,
NUMBER_PAD = Types.NUMBER_PAD,
PHONE = Types.PHONE,
NAME_PHONE = Types.NAME_PHONE,
EMAIL = Types.EMAIL,
DECIMAL = Types.DECIMAL,
TWITTER = Types.TWITTER,
SEARCH = Types.SEARCH,
ASCII_NUMBER = Types.ASCII_NUMBER,
}
export enum KeyboardReturnType {
NORMAL = Types.NORMAL,
GO = Types.GO,
JOIN = Types.JOIN,
NEXT = Types.NEXT,
ROUTE = Types.ROUTE,
SEARCH = Types.SEARCH,
SEND = Types.SEND,
DONE = Types.DONE,
EMERGENCY = Types. EMERGENCY,
CONTINUE = Types.CONTINUE,
}
const enum_object: Dict<number> = {};
Object.entries(Types).forEach(function([key,val]) {
if (typeof val == 'number') {
enum_object[key.toLowerCase()] = val;
}
});
export declare class Background {
next: Background | null;
}
export interface BackgroundOptions {
image?: {
src?: string;
repeat?: Repeat;
position?: BackgroundPositionCollection;
positionX?: BackgroundPosition;
positionY?: BackgroundPosition;
size?: BackgroundSizeCollection;
sizeX?: BackgroundSize;
sizeY?: BackgroundSize;
};
gradient?: {}
}
export declare class BackgroundImage extends Background {
src: string;
// readonly hasBase64: boolean;
repeat: Repeat;
position: BackgroundPositionCollection;
positionX: BackgroundPosition;
positionY: BackgroundPosition;
size: BackgroundSizeCollection;
sizeX: BackgroundSize;
sizeY: BackgroundSize;
}
// export declare class BackgroundGradient extends Background {
// }
export class BackgroundPositionCollection {
x: BackgroundPosition;
y: BackgroundPosition;
}
export class BackgroundSizeCollection {
x: BackgroundSize;
y: BackgroundSize;
}
function check_uinteger(value: any) {
return Number.isInteger(value) ? value >= 0 : false;
}
function check_unsigned_number(value: any) {
return Number.isFinite(value) ? value >= 0 : false;
}
function check_number(value: any) {
return Number.isFinite(value);
}
function check_enum(enum_obj: any, value: any) {
return Number.isInteger(value) && enum_obj[value];
}
function check_string(value: any) {
return typeof value == 'string';
}
function check_integer_ret(value: any) {
if (!check_uinteger(value)) {
throw new Error('Bad argument.');
}
return value;
}
function check_number_ret(value: any) {
if (!check_number(value)) {
throw new Error('Bad argument.');
}
return value;
}
function check_unsigned_number_ret(value: any) {
if (!check_unsigned_number(value)) {
throw new Error('Bad argument.');
}
return value;
}
function check_is_null_ret(value: any) {
if (value === null) {
throw new Error('Bad argument.');
}
return value;
}
function check_enum_ret(enum_obj: any, value: any) {
if (Number.isInteger(value) && enum_obj[value]) {
return value;
} else {
throw new Error('Bad argument.');
}
}
function check_string_ret(value: any) {
if (typeof value == 'string') {
return value;
} else {
throw new Error('Bad argument.');
}
}
function get_help(reference?: any[], enum_value?: any) {
var message = '';
if ( reference ) {
for ( var val of reference ) {
if ( val ) message += ', ' + JSON.stringify(val);
}
}
if ( enum_value ) {
for (var i of Object.values(enum_value)) {
if (typeof i == 'string') {
message += ', ' + i.toLowerCase();
}
}
}
return message;
}
class Base {
toString() {
return '[object]';
}
}
export class Border extends Base {
private _width: number;
private _color: Color;
get width() { return this._width; }
get color() { return this._color; }
get r() { return (this._color as any)._r; }
get g() { return (this._color as any)._g as number; }
get b() { return (this._color as any)._b as number; }
get a() { return (this._color as any)._a as number; }
set width(value) {
this._width = check_number_ret(value);
}
set color(value) {
if (value instanceof Color) {
this._color = value;
} else if (typeof value == 'string') { // 解析字符串
this._color = check_is_null_ret(parseColor(value));
} else {
throw new Error('Bad argument.');
}
}
constructor(width?: number, color?: Color) {
super();
if (arguments.length > 0) {
if (check_number(width)) this._width = width as number;
this._color = color instanceof Color ? color : new Color();
} else {
this._color = new Color();
}
}
toString() {
return `${this._width} ${this._color}`;
}
}
(Border.prototype as any)._width = 0;
(Border.prototype as any)._color = null;
export class Shadow extends Base {
private _offset_x: number;
private _offset_y: number;
private _size: number;
private _color: Color;
get offsetX() { return this._offset_x; }
get offsetY() { return this._offset_y; }
get size() { return this._size; }
get color() { return this._color; }
get r() { return (this._color as any)._r; }
get g() { return (this._color as any)._g; }
get b() { return (this._color as any)._b; }
get a() { return (this._color as any)._a; }
set offsetX(value) { this._offset_x = check_number_ret(value); }
set offsetY(value) { this._offset_y = check_number_ret(value); }
set size(value) { this._size = check_unsigned_number_ret(value); }
set color(value) {
if (value instanceof Color) {
this._color = value;
} else if (typeof value == 'string') { // 解析字符串
this._color = check_is_null_ret(parseColor(value));
} else {
throw new Error('Bad argument.');
}
}
constructor(offset_x?: number, offset_y?: number, size?: number, color?: Color) {
super();
if (arguments.length > 0) {
if (check_number(offset_x)) this._offset_x = offset_x as number;
if (check_number(offset_y)) this._offset_y = offset_y as number;
if (check_unsigned_number(size)) this._size = size as number;
this._color = color instanceof Color ? color : new Color();
} else {
this._color = new Color();
}
}
toString() {
return `${this._offset_x} ${this._offset_y} ${this._size} ${this._color}`;
}
}
(Shadow.prototype as any)._offset_x = 0;
(Shadow.prototype as any)._offset_y = 0;
(Shadow.prototype as any)._size = 0;
(Shadow.prototype as any)._color = null;
function to_hex_string(num: number) {
if (num < 16) {
return '0' + num.toString(16);
} else {
return num.toString(16);
}
}
export class Color extends Base {
private _r: number;
private _g: number;
private _b: number;
private _a: number;
get r() { return this._r; }
get g() { return this._g; }
get b() { return this._b; }
get a() { return this._a; }
set r(value) {
this._r = check_number_ret(value) % 256;
}
set g(value) {
this._g = check_number_ret(value) % 256;
}
set b(value) {
this._b = check_number_ret(value) % 256;
}
set a(value) {
this._a = check_number_ret(value) % 256;
}
constructor(r?: number, g?: number, b?: number, a?: number) {
super();
if (arguments.length > 0) {
if (check_uinteger(r)) this._r = r as number % 256;
if (check_uinteger(g)) this._g = g as number % 256;
if (check_uinteger(b)) this._b = b as number % 256;
if (check_uinteger(a)) this._a = a as number % 256;
}
}
reverse() {
return new Color(255 - this._r, 255 - this._g, 255 - this._b, this._a);
}
toRGBString() {
return `rgb(${this._r}, ${this._g}, ${this._b})`;
}
toRGBAString() {
return `rgba(${this._r}, ${this._g}, ${this._b}, ${this._a})`;
}
toString() {
return `#${to_hex_string(this._r)}${to_hex_string(this._g)}${to_hex_string(this._b)}`;
}
toHex32String() {
return `#${to_hex_string(this._r)}${to_hex_string(this._g)}${to_hex_string(this._b)}${to_hex_string(this._a)}`;
}
}
(Color.prototype as any)._r = 0;
(Color.prototype as any)._g = 0;
(Color.prototype as any)._b = 0;
(Color.prototype as any)._a = 255;
export class Vec2 extends Base {
private _x: number;
private _y: number;
get x() { return this._x; }
get y() { return this._y; }
set x(value) { this._x = check_number_ret(value); }
set y(value) { this._y = check_number_ret(value); }
constructor(x?: number, y?: number) {
super();
if (arguments.length > 0) {
if (check_number(x)) this._x = x as number;
if (check_number(y)) this._y = y as number;
}
}
toString() {
return `vec2(${this._x}, ${this._y})`;
}
}
(Vec2.prototype as any)._x = 0;
(Vec2.prototype as any)._y = 0;
export class Vec3 extends Base {
private _x: number;
private _y: number;
private _z: number;
get x() { return this._x; }
get y() { return this._y; }
get z() { return this._x; }
set x(value) { this._x = check_number_ret(value); }
set y(value) { this._y = check_number_ret(value); }
set z(value) { this._z = check_number_ret(value); }
constructor(x?: number, y?: number, z?: number) {
super();
if (arguments.length > 0) {
if (check_number(x)) this._x = x as number;
if (check_number(y)) this._y = y as number;
if (check_number(z)) this._z = z as number;
}
}
toString() {
return `vec3(${this._x}, ${this._y}, ${this._z})`;
}
}
(Vec3.prototype as any)._x = 0;
(Vec3.prototype as any)._y = 0;
(Vec3.prototype as any)._z = 0;
export class Vec4 extends Base {
private _x: number;
private _y: number;
private _z: number;
private _w: number;
get x() { return this._x; }
get y() { return this._y; }
get z() { return this._x; }
get w() { return this._w; }
set x(value) { this._x = check_number_ret(value); }
set y(value) { this._y = check_number_ret(value); }
set z(value) { this._z = check_number_ret(value); }
set w(value) { this._w = check_number_ret(value); }
constructor(x?: number, y?: number, z?: number, w?: number) {
super();
if (arguments.length > 0) {
if (check_number(x)) this._x = x as number;
if (check_number(y)) this._y = y as number;
if (check_number(z)) this._z = z as number;
if (check_number(w)) this._w = w as number;
}
}
toString() {
return `vec4(${this._x}, ${this._y}, ${this._z}, ${this._w})`;
}
}
(Vec4.prototype as any)._x = 0;
(Vec4.prototype as any)._y = 0;
(Vec4.prototype as any)._z = 0;
(Vec4.prototype as any)._w = 0;
export class Curve extends Base {
private _p1_x: number;
private _p1_y: number;
private _p2_x: number;
private _p2_y: number;
constructor(p1_x?: number, p1_y?: number, p2_x?: number, p2_y?: number) {
super();
if (arguments.length > 0) {
if (check_number(p1_x)) this._p1_x = p1_x as number;
if (check_number(p1_y)) this._p1_y = p1_y as number;
if (check_number(p2_x)) this._p2_x = p2_x as number;
if (check_number(p2_y)) this._p2_y = p2_y as number;
}
}
get point1X() { return this._p1_x; }
get point1Y() { return this._p1_y; }
get point2X() { return this._p2_x; }
get point2Y() { return this._p2_y; }
toString() {
return `curve(${this._p1_x}, ${this._p1_y}, ${this._p2_x}, ${this._p2_y})`;
}
}
(Curve.prototype as any)._p1_x = 0;
(Curve.prototype as any)._p1_y = 0;
(Curve.prototype as any)._p2_x = 1;
(Curve.prototype as any)._p2_y = 1;
export class Rect extends Base {
private _x: number;
private _y: number;
private _width: number;
private _height: number;
get x() { return this._x; }
get y() { return this._y; }
get width() { return this._width; }
get height() { return this._height; }
set x(value) { this._x = check_number_ret(value); }
set y(value) { this._y = check_number_ret(value); }
set width(value) { this._width = check_number_ret(value); }
set height(value) { this._height = check_number_ret(value); }
constructor(x?: number, y?: number, width?: number, height?: number) {
super();
if (arguments.length > 0) {
if (check_number(x)) this._x = x as number;
if (check_number(y)) this._y = y as number;
if (check_number(width)) this._width = width as number;
if (check_number(height)) this._height = height as number;
}
}
toString() {
return `rect(${this._x}, ${this._y}, ${this._width}, ${this._height})`;
}
}
(Rect.prototype as any)._x = 0;
(Rect.prototype as any)._y = 0;
(Rect.prototype as any)._width = 0;
(Rect.prototype as any)._height = 0;
export class Mat extends Base {
private _value: number[];
get value() { return this._value; }
get m0() { return this._value[0]; }
get m1() { return this._value[1]; }
get m2() { return this._value[2]; }
get m3() { return this._value[3]; }
get m4() { return this._value[4]; }
get m5() { return this._value[5]; }
set m0(value) { this._value[0] = check_number_ret(value); }
set m1(value) { this._value[1] = check_number_ret(value); }
set m2(value) { this._value[2] = check_number_ret(value); }
set m3(value) { this._value[3] = check_number_ret(value); }
set m4(value) { this._value[4] = check_number_ret(value); }
set m5(value) { this._value[5] = check_number_ret(value); }
constructor(...m: number[]) {
super();
var value = [1, 0, 0, 0, 1, 0];
if (m.length > 0) {
if (m.length == 1) {
var m0 = m[0];
if (check_number(m0)) {
value[0] = m0 as number;
value[4] = m0 as number;
}
} else {
var j = 0;
for (var i of m) {
if (check_number(i))
value[j++] = i;
}
}
}
this._value = value;
}
toString() {
var value = this._value;
return `mat(${value[0]}, ${value[1]}, ${value[2]}, ${value[3]}, ${value[4]}, ${value[5]})`;
}
}
export class Mat4 extends Base {
private _value: number[];
get value() { return this._value; }
get m0() { return this._value[0]; }
get m1() { return this._value[1]; }
get m2() { return this._value[2]; }
get m3() { return this._value[3]; }
get m4() { return this._value[4]; }
get m5() { return this._value[5]; }
get m6() { return this._value[6]; }
get m7() { return this._value[7]; }
get m8() { return this._value[8]; }
get m9() { return this._value[9]; }
get m10() { return this._value[10]; }
get m11() { return this._value[11]; }
get m12() { return this._value[12]; }
get m13() { return this._value[13]; }
get m14() { return this._value[14]; }
get m15() { return this._value[15]; }
set m0(value) { this._value[0] = check_number_ret(value); }
set m1(value) { this._value[1] = check_number_ret(value); }
set m2(value) { this._value[2] = check_number_ret(value); }
set m3(value) { this._value[3] = check_number_ret(value); }
set m4(value) { this._value[4] = check_number_ret(value); }
set m5(value) { this._value[5] = check_number_ret(value); }
set m6(value) { this._value[6] = check_number_ret(value); }
set m7(value) { this._value[7] = check_number_ret(value); }
set m8(value) { this._value[8] = check_number_ret(value); }
set m9(value) { this._value[9] = check_number_ret(value); }
set m10(value) { this._value[10] = check_number_ret(value); }
set m11(value) { this._value[11] = check_number_ret(value); }
set m12(value) { this._value[12] = check_number_ret(value); }
set m13(value) { this._value[13] = check_number_ret(value); }
set m14(value) { this._value[14] = check_number_ret(value); }
set m15(value) { this._value[15] = check_number_ret(value); }
constructor(...m: number[]) {
super();
var value = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
if (m.length > 0) {
if (m.length == 1) {
var m0 = m[0];
if (check_number(m0)) {
value[0] = m0;
value[5] = m0;
value[10] = m0;
value[15] = m0;
}
} else {
var j = 0;
for (var i of m) {
if (check_number(i))
value[j++] = i;
}
}
}
this._value = value;
}
toString() {
var value = this._value;
return `mat4(\
${value[0]}, ${value[1]}, ${value[2]}, ${value[3]}, \
${value[4]}, ${value[5]}, ${value[6]}, ${value[7]}, \
${value[8]}, ${value[9]}, ${value[10]}, ${value[11]}, \
${value[12]}, ${value[13]}, ${value[14]}, ${value[15]})`;
}
}
export class Value extends Base {
private _type: ValueType;
private _value: number;
get type() { return this._type; }
get value() { return this._value; }
set type(value) { this._type = check_enum_ret(ValueType, value); }
set value(val) { this._value = check_number_ret(val); }
constructor(type?: ValueType, value?: number) {
super();
if (arguments.length > 0) {
if (check_enum(ValueType, type)) this._type = type as ValueType;
if (check_number(value)) this._value = value as number;
}
}
toString() {
switch (this._type) {
case enum_object.auto: return 'auto';
case enum_object.full: return 'full';
case enum_object.pixel: return this._value.toString();
case enum_object.percent: return this._value * 100 + '%';
default: return this._value + '!';
}
}
}
(Value.prototype as any)._type = ValueType.AUTO;
(Value.prototype as any)._value = 0;
export class BackgroundPosition extends Base {
private _type: BackgroundPositionType;
private _value: number;
get type() { return this._type; }
get value() { return this._value; }
set type(value) { this._type = check_enum_ret(BackgroundPositionType, value); }
set value(val) { this._value = check_number_ret(val); }
constructor(type?: BackgroundPositionType, value?: number) {
super();
if (arguments.length > 0) {
if (check_enum(BackgroundPositionType, type)) this._type = type as BackgroundPositionType;
if (check_number(value)) this._value = value as number;
}
}
toString() {
switch (this._type) {
case enum_object.pixel: return this._value.toString();
case enum_object.percent: return this._value * 100 + '%';
case enum_object.left: return 'left';
case enum_object.right: return 'right';
case enum_object.top: return 'top';
case enum_object.bottom: return 'bottom';
default: return 'center';
}
}
}
(BackgroundPosition.prototype as any)._type = BackgroundPositionType.PIXEL;
(BackgroundPosition.prototype as any)._value = 0;
export class BackgroundSize extends Base {
private _type: BackgroundSizeType;
private _value: number;
get type() { return this._type; }
get value() { return this._value; }
set type(value) { this._type = check_enum_ret(BackgroundSizeType, value); }
set value(val) { this._value = check_number_ret(val); }
constructor(type?: BackgroundSizeType, value?: number) {
super();
if (arguments.length > 0) {
if (check_enum(BackgroundSizeType, type)) this._type = type as BackgroundSizeType;
if (check_number(value)) this._value = value as number;
}
}
toString() {
switch (this._type) {
case enum_object.auto: return 'auto';
case enum_object.pixel: return this._value.toString();
default: return this._value * 100 + '%';
}
}
}
(BackgroundSize.prototype as any)._type = BackgroundSizeType.AUTO;
(BackgroundSize.prototype as any)._value = 0;
class TextValue extends Base {
protected _type: TextValueType;
get type() { return this._type; }
set type(value) {
this._type = check_enum_ret(TextValueType, value);
}
constructor(type?: TextValueType) {
super();
if ( check_enum(TextValueType, type) ) this._type = type as TextValueType;
}
}
(TextValue.prototype as any)._type = TextValueType.INHERIT;
export class TextColor extends TextValue {
private _value: Color;
get value() { return this._value; }
get r() { return (this._value as any)._r; }
get g() { return (this._value as any)._g; }
get b() { return (this._value as any)._b; }
get a() { return (this._value as any)._a; }
set value(val) {
if (val instanceof Color) {
this._value = val;
} else if (typeof val == 'string') { // 解析字符串
this._value = check_is_null_ret(parseColor(val));
} else {
throw new Error('Bad argument.');
}
}
constructor(type?: TextValueType, value?: Color) {
super(type);
this._value = arguments.length > 1 && value instanceof Color ? value : new Color();
}
toString() {
return this._type == TextValueType.INHERIT ? 'inherit' : this._value.toString();
}
}
(TextColor.prototype as any)._value = null;
export class TextSize extends TextValue {
private _value: number;
get value() { return this._value; }
set value(val) { this._value = check_unsigned_number_ret(val); }
constructor(type?: TextValueType, value?: number) {
super(type);
if (arguments.length > 1) {
if (check_unsigned_number(value)) this._value = value as number;
}
}
toString() {
return this._type == TextValueType.INHERIT ? 'inherit' : this._value.toString();
}
}
(TextSize.prototype as any)._value = 12;
export class TextFamily extends TextValue {
private _value: string;
get value() { return this._value; }
set value(val) { this._value = check_string_ret(val); }
constructor(type?: TextValueType, value?: string) {
super(type);
if (arguments.length > 1) {
if (check_string(value)) this._value = value as string;
}
}
toString() {
return this._type == TextValueType.INHERIT ? 'inherit' : this._value;
}
}
(TextFamily.prototype as any)._value = '';
export class TextStyle extends TextValue {
private _value: TextStyleEnum;
get value() { return this._value; }
set value(val) { this._value = check_enum_ret(TextStyleEnum, val); }
constructor(type?: TextValueType, value?: TextStyleEnum) {
super(type);
if (arguments.length > 1) {
if (check_enum(TextStyleEnum, value)) this._value = value as TextStyleEnum;
}
}
toString() {
return this._type == TextValueType.INHERIT ? 'inherit' : TextStyleEnum[this._value].toLowerCase();
}
}
(TextStyle.prototype as any)._value = TextStyleEnum.REGULAR;
export class TextShadow extends TextValue {
private _value: Shadow;
get value() { return this._value; }
get offsetX() { return (this._value as any)._offset_x; }
get offsetY() { return (this._value as any)._offset_y; }
get size() { return (this._value as any)._size; }
get color() { return (this._value as any)._color; }
get r() { return (this as any)._value._color._r; }
get g() { return (this as any)._value._color._g; }
get b() { return (this as any)._value._color._b; }
get a() { return (this as any)._value._color._a; }
set value(val) {
if (val instanceof Shadow) {
this._value = val;
} else if (typeof val == 'string') {
this._value = check_is_null_ret(parseShadow(val));
} else {
throw new Error('Bad argument.');
}
}
constructor(type?: TextValueType, value?: Shadow) {
super(type);
this._value = arguments.length > 1 && value instanceof Shadow ? value: new Shadow();
}
toString() {
return this._type == TextValueType.INHERIT ? 'inherit' : this._value.toString();
}
}
(TextShadow.prototype as any)._value = null;
export class TextLineHeight extends TextValue {
private _height: number;
get isAuto() { return this._height <= 0; }
get height() { return this._height; }
set height(value) {
this._height = check_unsigned_number_ret(value);
}
constructor(type?: TextValueType, height?: number) {
super(type);
if (arguments.length > 1) {
if (check_unsigned_number(height)) this._height = height as number;
}
}
toString() {
if (this._type == TextValueType.INHERIT) {
return 'inherit';
} else if (this._height <= 0) {
return 'auto';
} else {
return this._height.toString();
}
}
}
(TextLineHeight as any).prototype._height = 0;
export class TextDecoration extends TextValue {
private _value: TextDecorationEnum;
get value() { return this._value; }
set value(val) { this._value = check_enum_ret(TextDecoration, val); }
constructor(type?: TextValueType, value?: TextDecorationEnum) {
super(type);
if (arguments.length > 1) {
if (check_enum(TextDecorationEnum, value)) this._value = value as TextDecorationEnum;
}
}
toString() {
return this._type == TextValueType.INHERIT ? 'inherit' : TextDecorationEnum[this._value].toLowerCase();
}
}
(TextDecoration as any).prototype._value = TextDecorationEnum.NONE;
export class TextOverflow extends TextValue {
private _value: TextOverflowEnum;
get value() { return this._value; }
set value(val) { this._value = check_enum_ret(TextDecoration, val); }
constructor(type?: TextValueType, value?: TextOverflowEnum) {
super(type);
if (arguments.length > 1) {
if (check_enum(TextOverflowEnum, value)) this._value = value as TextOverflowEnum;
}
}
toString() {
return this._type == TextValueType.INHERIT ? 'inherit' : TextOverflowEnum[this._value].toLowerCase();
}
}
(TextOverflow as any).prototype._value = TextOverflowEnum.NORMAL;
export class TextWhiteSpace extends TextValue {
private _value: TextWhiteSpaceEnum;
get value() { return this._value; }
set value(val) { this._value = check_enum_ret(TextDecoration, val); }
constructor(type?: TextValueType, value?: TextWhiteSpaceEnum) {
super(type);
if (arguments.length > 1) {
if (check_enum(TextWhiteSpaceEnum, value)) this._value = value as TextWhiteSpaceEnum;
}
}
toString() {
return this._type == TextValueType.INHERIT ? 'inherit' : TextWhiteSpaceEnum[this._value].toLowerCase();
}
}
(TextWhiteSpace as any).prototype._value = TextWhiteSpaceEnum.NORMAL;
// ----------------------------
function _text_align(value: any) {
return value as TextAlign;
}
function _align(value: any) {
return value as Align;
}
function _content_align(value: any) {
return value as ContentAlign;
}
function _repeat(value: any) {
return value as Repeat;
}
function _direction(value: any) {
return value as Direction;
}
function _keyboard_type(value: any) {
return value as KeyboardType;
}
function _keyboard_return_type(value: any) {
return value as KeyboardReturnType;
}
function _border(width: number, r: number, g: number, b: number, a: number) {
return {
__proto__: Border.prototype,
_width: width,
_color: _color(r, g, b, a),
} as unknown as Border;
}
function _shadow(offset_x: number, offset_y: number, size: number, r: number, g: number, b: number, a: number) {
return {
__proto__: Shadow.prototype,
_offset_x: offset_x,
_offset_y: offset_y,
_size: size,
_color: _color(r, g, b, a),
} as unknown as Shadow;
}
function _color(r: number, g: number, b: number, a: number) {
return {
__proto__: Color.prototype,
_r: r,
_g: g,
_b: b,
_a: a,
} as unknown as Color;
}
function _vec2(x: number, y: number) {
return {
__proto__: Vec2.prototype,
_x: x,
_y: y,
} as unknown as Vec2;
}
function _vec3(x: number, y: number, z: number) {
return {
__proto__: Vec3.prototype,
_x: x,
_y: y,
_z: z,
} as unknown as Vec3;
}
function _vec4(x: number, y: number, z: number, w: number) {
return {
__proto__: Vec4.prototype,
_x: x,
_y: y,
_z: z,
_w: w,
} as unknown as Vec4;
}
function _curve(p1_x: number, p1_y: number, p2_x: number, p2_y: number) {
return {
__proto__: Curve.prototype,
_p1_x: p1_x,
_p1_y: p1_y,
_p2_x: p2_x,
_p2_y: p2_y,
} as unknown as Curve;
}
function _rect(x: number, y: number, width: number, height: number) {
return {
__proto__: Rect.prototype,
_x: x,
_y: y,
_width: width,
_height: height,
} as unknown as Rect;
}
function _mat(...value: any[]) {
return {
__proto__: Mat.prototype,
_value: value,
} as unknown as Mat;
}
function _mat4(...value: any[]) {
return {
__proto__: Mat4.prototype,
_value: value,
} as unknown as Mat4;
}
function _value(type: ValueType, value: number) {
return {
__proto__: Value.prototype,
_type: type,
_value: value,
} as unknown as Value;
}
function _background_position(type: BackgroundPositionType, value: number) {
return {
__proto__: BackgroundPosition.prototype,
_type: type,
_value: value,
} as unknown as BackgroundPosition;
}
function _background_size(type: BackgroundSizeType, value: number) {
return {
__proto__: BackgroundSize.prototype,
_type: type,
_value: value,
} as unknown as BackgroundSize;
}
function _background_position_collection(type: BackgroundPositionType, value: number, type_y: BackgroundPositionType, value_y: number) {
return {
__proto__: BackgroundPositionCollection.prototype,
x: _background_position(type, value),
y: _background_position(type_y, value_y),
} as BackgroundPositionCollection;
}
function _background_size_collection(type: BackgroundSizeType, value: number, type_y: BackgroundSizeType, value_y: number) {
return {
__proto__: BackgroundSizeCollection.prototype,
x: _background_size(type, value),
y: _background_size(type_y, value_y),
} as BackgroundSizeCollection;
}
function _text_color(type: TextValueType, r: number, g: number, b: number, a: number) {
return {
__proto__: TextColor.prototype,
_type: type,
_value: _color(r, g, b, a),
} as unknown as TextColor;
}
function _text_size(type: TextValueType, value: number) {
return {
__proto__: TextSize.prototype,
_type: type,
_value: value,
} as unknown as TextSize;
}
function _text_family(type: TextValueType, value: string) {
return {
__proto__: TextFamily.prototype,
_type: type,
_value: value,
} as unknown as TextFamily;
}
function _text_style(type: TextValueType, value: TextStyleEnum) {
return {
__proto__: TextStyle.prototype,
_type: type,
_value: value,
} as unknown as TextStyle;
}
function _text_shadow(type: TextValueType, offset_x: number, offset_y: number, size: number, r: number, g: number, b: number, a: number) {
return {
__proto__: TextShadow.prototype,
_type: type,
_value: _shadow(offset_x, offset_y, size, r, g, b, a),
} as unknown as TextShadow;
}
function _text_line_height(type: TextValueType, height: number) {
return {
__proto__: TextLineHeight.prototype,
_type: type,
_height: height,
} as unknown as TextLineHeight;
}
function _text_decoration(type: TextValueType, value: TextDecorationEnum) {
return {
__proto__: TextDecoration.prototype,
_type: type,
_value: value,
} as unknown as TextDecoration;
}
function _text_overflow(type: TextValueType, value: TextOverflowEnum) {
return {
__proto__: TextOverflow.prototype,
_type: type,
_value: value,
} as unknown as TextOverflow;
}
function _text_white_space(type: TextValueType, value: TextWhiteSpaceEnum) {
return {
__proto__: TextWhiteSpace.prototype,
_type: type,
_value: value,
} as unknown as TextWhiteSpace;
}
// parse
export type TextAlignIn = string | TextAlign | number;
export type AlignIn = string | Align | number;
export type ContentAlignIn = string | ContentAlign | number;
export type RepeatIn = string | Repeat | number;
export type DirectionIn = string | Direction | number;
export type KeyboardTypeIn = string | KeyboardType | number;
export type KeyboardReturnTypeIn = string | KeyboardReturnType | number;
export type BorderIn = string | Border;
export type ShadowIn = string | Shadow;
export type ColorIn = string | Color | number;
export type Vec2In = string | Vec2 | number | [number, number?];
export type Vec3In = string | Vec3 | number | [number, number?, number?];
export type Vec4In = string | Vec4 | number | [number, number?, number?, number?];
export type CurveIn = 'linear' | 'ease' | 'ease_in' | 'ease_out' | 'ease_in_out' | string | Curve;
export type RectIn = string | Rect | number;
export type MatIn = string | Mat | number;
export type Mat4In = string | Mat4 | number;
export type ValueIn = 'auto' | 'full' | string | Value | number;
export type BackgroundPositionIn = 'left' | 'right' | 'center' | 'top' | 'bottom' | string | BackgroundPosition | number;
export type BackgroundSizeIn = 'auto' | string | BackgroundSize | number;
export type BackgroundIn = string | Background | BackgroundOptions;
export type ValuesIn = string | Value[] | Value | number;
export type AlignsIn = string | Align[] | Align | number;
export type FloatsIn = string | number[] | number;
export type BackgroundPositionCollectionIn = string | BackgroundPositionCollection | BackgroundPosition;
export type BackgroundSizeCollectionIn = string | BackgroundSizeCollection | BackgroundSize;
export type TextColorIn = string | TextColor | Color;
export type TextSizeIn = string | TextSize | number;
export type TextFamilyIn = string | TextFamily;
export type TextStyleIn = string | TextStyle | TextStyleEnum | number;
export type TextShadowIn = string | TextShadow | Shadow;
export type TextLineHeightIn = string | TextLineHeight | number;
export type TextDecorationIn = string | TextDecoration | TextDecorationEnum | number;
export type TextOverflowIn = string | TextOverflow | TextOverflowEnum | number;
export type TextWhiteSpaceIn = string | TextWhiteSpace | TextWhiteSpaceEnum | number;
function error(value: any, desc?: string, reference?: any[], enum_value?: any){
var err: string;
var msg = String(desc || '%s').replace(/\%s/g, '`' + value + '`');
var help = get_help(reference, enum_value);
if (help) {
err = `Bad argument. \`${msg}\`. Examples: ${help}`;
} else {
err = `Bad argument. \`${msg}\`.`;
}
return new Error(err);
}
export function parseTextAlign(str: TextAlignIn, desc?: string) {
if (typeof str == 'string') {
var value = enum_object[str];
if (check_enum(TextAlign, value)) {
return value as TextAlign;
}
} else if (check_enum(TextAlign, str)) {
return str as TextAlign;
}
throw error(str, desc, undefined, TextAlign);
}
export function parseAlign(str: AlignIn, desc?: string) {
if (typeof str == 'string') {
var value = enum_object[str];
if (check_enum(Align, value)) {
return value as Align;
}
} else if (check_enum(Align, str)) {
return str as Align;
}
throw error(str, desc, undefined, Align);
}
export function parseContentAlign(str: ContentAlignIn, desc?: string) {
if (typeof str == 'string') {
var value = enum_object[str];
if (check_enum(ContentAlign, value)) {
return value as ContentAlign;
}
} else if (check_enum(ContentAlign, str)) {
return str as ContentAlign;
}
throw error(str, desc, undefined, ContentAlign);
}
export function parseRepeat(str: RepeatIn, desc?: string) {
if (typeof str == 'string') {
var value = enum_object[str];
if (check_enum(Repeat, value)) {
return value as Repeat;
}
} else if (check_enum(Repeat, str)) {
return str as Repeat;
}
throw error(str, desc, undefined, Repeat);
}
export function parseDirection(str: DirectionIn, desc?: string) {
if (typeof str == 'string') {
var value = enum_object[str];
if (check_enum(Direction, value)) {
return value as Direction;
}
} else if (check_enum(Direction, str)) {
return str as Direction;
}
throw error(str, desc, undefined, Direction);
}
export function parseKeyboardType(str: KeyboardTypeIn, desc?: string) {
if (typeof str == 'string') {
var value = enum_object[str];
if (check_enum(KeyboardType, value)) {
return value as KeyboardType;
}
} else if (check_enum(KeyboardType, str)) {
return str as KeyboardType;
}
throw error(str, desc, undefined, KeyboardType);
}
export function parseKeyboardReturnType(str: KeyboardReturnTypeIn, desc?: string) {
if (typeof str == 'string') {
var value = enum_object[str];
if (check_enum(KeyboardReturnType, value)) {
return value as KeyboardReturnType;
}
} else if (check_enum(KeyboardReturnType, str)) {
return str as KeyboardReturnType;
}
throw error(str, desc, undefined, KeyboardReturnType);
}
export function parseBorder(str: BorderIn, desc?: string) {
if (typeof str == 'string') {
// 10 #ff00ff
var m = str.match(/^ *((?:\d+)?\.?\d+)/);
if (m) {
var rev = new Border();
(rev as any)._width = parseFloat(m[1]);
var color = parseColor(str.substr(m[0].length + 1));
if (color) {
(rev as any)._color = color;
}
return rev;
}
} else if (str instanceof Border) {
return str;
}
throw error(str, desc, ['10 #ff00aa', '10 rgba(255,255,0,255)']);
}
export function parseShadow(str: ShadowIn, desc?: string) {
if (typeof str == 'string') {
// 10 10 2 #ff00aa
var m = str.match(/^ *(-?(?:\d+)?\.?\d+) +(-?(?:\d+)?\.?\d+) +((?:\d+)?\.?\d+)/);
if (m) {
var rev = new Shadow();
(rev as any)._offset_x = parseFloat(m[1]);
(rev as any)._offset_y = parseFloat(m[2]);
(rev as any)._size = parseFloat(m[3]);
var color = parseColor(str.substr(m[0].length + 1));
if (color) {
(rev as any)._color = color;
}
return rev;
}
} else if (str instanceof Shadow) {
return str;
}
throw error(str, desc, ['10 10 2 #ff00aa', '10 10 2 rgba(255,255,0,255)']);
}
export function parseColor(str: ColorIn, desc?: string) {
if (typeof str == 'string') {
if (/^ *none *$/.test(str)) {
return _color(0, 0, 0, 0);
}
var m = str.match(/^#([0-9a-f]{3}([0-9a-f])?([0-9a-f]{2})?([0-9a-f]{2})?)$/i);
if (m) {
if (m[4]) { // 8
return _color(parseInt(m[1].substr(0, 2), 16),
parseInt(m[1].substr(2, 2), 16),
parseInt(m[1].substr(4, 2), 16),
parseInt(m[1].substr(6, 2), 16));
} else if (m[3]) { // 6
return _color(parseInt(m[1].substr(0, 2), 16),
parseInt(m[1].substr(2, 2), 16),
parseInt(m[1].substr(4, 2), 16), 255);
} else if (m[2]) { // 4
return _color(parseInt(m[1].substr(0, 1), 16) * 17,
parseInt(m[1].substr(1, 1), 16) * 17,
parseInt(m[1].substr(2, 1), 16) * 17,
parseInt(m[1].substr(3, 1), 16) * 17);
} else { // 3
return _color(parseInt(m[1].substr(0, 1), 16) * 17,
parseInt(m[1].substr(1, 1), 16) * 17,
parseInt(m[1].substr(2, 1), 16) * 17, 255);
}
}
var m = str.match(/^ *rgb(a)?\( *(\d{1,3}) *, *(\d{1,3}) *, *(\d{1,3})( *, *(\d{1,3}))? *\) *$/);
if (m) {
if (m[1] == 'a') { // rgba
if (m[5]) { // a
return _color(parseInt(m[2]) % 256,
parseInt(m[3]) % 256,
parseInt(m[4]) % 256,
parseInt(m[6]) % 256);
}
} else { // rgb
if (!m[5]) {
return _color(parseInt(m[2]) % 256,
parseInt(m[3]) % 256,
parseInt(m[4]) % 256, 255);
}
}
}
} else if (str instanceof Color) {
return str;
} else if (typeof str == 'number') {
_color(str >> 24 & 255, // r
str >> 16 & 255, // g
str >> 8 & 255, // b
str >> 0 & 255); // a
}
throw error(str, desc, ['rgba(255,255,255,255)', 'rgb(255,255,255)', '#ff0', '#ff00', '#ff00ff', '#ff00ffff']);
}
export function parseVec2(str: Vec2In, desc?: string) {
if (typeof str == 'string') {
var m = str.match(/^ *(-?(?:\d+)?\.?\d+) +(-?(?:\d+)?\.?\d+) *$/) ||
str.match(/^ *vec2\( *(-?(?:\d+)?\.?\d+) *, *(-?(?:\d+)?\.?\d+) *\) *$/);
if (m) {
return _vec2(parseFloat(m[1]), parseFloat(m[2]));
}
} else if (str instanceof Vec2) {
return str;
} else if (typeof str == 'number') {
return _vec2(str, str);
} else if (Array.isArray(str)) {
var x = Number(str[0]) || 0;
var y = Number(str[1]) || x;
return _vec2(x, y);
}
throw error(str, desc, ['vec2(1,1)', '1 1']);
}
export function parseVec3(str: Vec3In, desc?: string) {
if (typeof str == 'string') {
var m = str.match(/^ *(-?(?:\d+)?\.?\d+) +(-?(?:\d+)?\.?\d+) +(-?(?:\d+)?\.?\d+) *$/) ||
str.match(/^ *vec3\( *(-?(?:\d+)?\.?\d+) *, *(-?(?:\d+)?\.?\d+) *, *(-?(?:\d+)?\.?\d+) *\) *$/);
if (m) {
return _vec3(parseFloat(m[1]), parseFloat(m[2]), parseFloat(m[3]));
}
} else if (str instanceof Vec3) {
return str;
} else if (typeof str == 'number') {
return _vec3(str, str, str);
} else if (Array.isArray(str)) {
var x = Number(str[0]) || 0;
var y = Number(str[1]) || x;
var z = Number(str[2]) || y;
return _vec3(x, y, z);
}
throw error(str, desc, ['vec3(0,0,1)', '0 0 1']);
}
export function parseVec4(str: Vec4In, desc?: string) {
if (typeof str == 'string') {
var m = str.match(/^ *(-?(?:\d+)?\.?\d+) +(-?(?:\d+)?\.?\d+) +(-?(?:\d+)?\.?\d+) +(-?(?:\d+)?\.?\d+) *$/) ||
str.match(/^ *vec4\( *(-?(?:\d+)?\.?\d+) *, *(-?(?:\d+)?\.?\d+) *, *(-?(?:\d+)?\.?\d+) *, *(-?(?:\d+)?\.?\d+) *\) *$/);
if (m) {
return _vec4(parseFloat(m[1]), parseFloat(m[2]), parseFloat(m[3]), parseFloat(m[4]));
}
} else if (str instanceof Vec4) {
return str;
} else if (typeof str == 'number') {
return _vec4(str, str, str, str);
} else if (Array.isArray(str)) {
var x = Number(str[0]) || 0;
var y = Number(str[1]) || x;
var z = Number(str[2]) || y;
var w = Number(str[3]) || z;
return _vec4(x, y, z, w);
}
throw error(str, desc, ['vec4(0,0,1,1)', '0 0 1 1']);
}
export function parseCurve(str: CurveIn, desc?: string) {
if (typeof str == 'string') {
var s = ({
linear: [0, 0, 1, 1],
ease: [0.25, 0.1, 0.25, 1],
ease_in: [0.42, 0, 1, 1],
ease_out: [0, 0, 0.58, 1],
ease_in_out: [0.42, 0, 0.58, 1],
} as Dict<number[]>)[str];
if (s) {
return _curve(s[0], s[1], s[2], s[3]);
}
var m = str.match(/^ *(-?(?:\d+)?\.?\d+) +(-?(?:\d+)?\.?\d+) +(-?(?:\d+)?\.?\d+) +(-?(?:\d+)?\.?\d+) *$/) ||
str.match(/^ *curve\( *(-?(?:\d+)?\.?\d+) *, *(-?(?:\d+)?\.?\d+) *, *(-?(?:\d+)?\.?\d+) *, *(-?(?:\d+)?\.?\d+) *\) *$/);
if (m) {
return _curve(parseFloat(m[1]), parseFloat(m[2]), parseFloat(m[3]), parseFloat(m[4]));
}
} else if (str instanceof Curve) {
return str;
}
throw error(str, desc, ['curve(0,0,1,1)', '0 0 1 1', 'linear', 'ease', 'ease_in', 'ease_out', 'ease_in_out']);
}
export function parseRect(str: RectIn, desc?: string) {
if (typeof str == 'string') {
var m = str.match(/^ *(-?(?:\d+)?\.?\d+) +(-?(?:\d+)?\.?\d+) +(-?(?:\d+)?\.?\d+) +(-?(?:\d+)?\.?\d+) *$/) ||
str.match(/^ *rect\( *(-?(?:\d+)?\.?\d+) *, *(-?(?:\d+)?\.?\d+) *, *(-?(?:\d+)?\.?\d+) *, *(-?(?:\d+)?\.?\d+) *\) *$/);
if (m) {
return _rect(parseFloat(m[1]), parseFloat(m[2]), parseFloat(m[3]), parseFloat(m[4]));
}
} else if (str instanceof Rect) {
return str;
} else if (typeof str == 'number') {
return _rect(str, str, str, str);
}
throw error(str, desc, ['rect(0,0,-100,200)', '0 0 -100 200']);
}
const parse_mat_reg = new RegExp(`^ *mat\\( *${new Array(6).join('(-?(?:\\d+)?\\.?\\d+) *, *')}(-?(?:\\d+)?\\.?\\d+) *\\) *$`);
const parse_mat4_reg = new RegExp(`^ *mat4\\( *${new Array(16).join('(-?(?:\\d+)?\\.?\\d+) *, *')}(-?(?:\\d+)?\\.?\\d+) *\\) *$`);
export function parseMat(str: MatIn, desc?: string) {
if (typeof str == 'string') {
var m = parse_mat_reg.exec(str);
if (m) {
var value = [
parseFloat(m[1]),
parseFloat(m[2]),
parseFloat(m[6]),
parseFloat(m[4]),
parseFloat(m[5]),
parseFloat(m[6]),
];
return _mat(value);
}
} else if (str instanceof Mat) {
return str;
} else if (typeof str == 'number') {
return new Mat(str);
}
throw error(str, desc, ['mat(1,0,0,1,0,1)']);
}
export function parseMat4(str: Mat4In, desc?: string) {
if (typeof str == 'string') {
var m = parse_mat4_reg.exec(str);
if (m) {
var value = [
parseFloat(m[1]),
parseFloat(m[2]),
parseFloat(m[6]),
parseFloat(m[4]),
parseFloat(m[5]),
parseFloat(m[6]),
parseFloat(m[7]),
parseFloat(m[8]),
parseFloat(m[9]),
parseFloat(m[10]),
parseFloat(m[11]),
parseFloat(m[12]),
parseFloat(m[13]),
parseFloat(m[14]),
parseFloat(m[15]),
parseFloat(m[16]),
];
return _mat4(value);
}
} else if (str instanceof Mat4) {
return str;
} else if (typeof str == 'number') {
return new Mat4(str);
}
throw error(str, desc, ['mat4(1,0,0,1,0,1,0,1,0,0,1,1,0,0,0,1)']);
}
export function parseValue(str: ValueIn, desc?: string) {
if (typeof str == 'string') {
// auto | full | 10.1 | 20% | 60!
var m = str.match(/^((auto)|(full)|(-?(?:\d+)?\.?\d+)(%|!)?)$/);
if (m) {
if (m[2]) { // auto
return _value(enum_object.auto, 0);
} else if (m[3]) { // full
return _value(enum_object.full, 0);
} else { //
var type = enum_object.pixel;
var value = parseFloat(m[4]);
if (m[5]) {
if ( m[5] == '%' ) {
type = enum_object.percent;
value /= 100; // %
} else { // 10!
type = enum_object.minus;
}
}
return _value(type, value);
}
}
} else if (str instanceof Value) {
return str;
} else if (typeof str == 'number') {
return _value(enum_object.pixel, str);
}
throw error(str, desc, ['auto', 'full', 10, '20%', '60!']);
}
enum background_position_type_2 {
LEFT = Types.LEFT,
RIGHT = Types.RIGHT,
CENTER = Types.CENTER,
TOP = Types.TOP,
BOTTOM = Types.BOTTOM,
}
export function parseBackgroundPosition(str: BackgroundPositionIn, desc?: string) {
if (typeof str == 'string') {
// left | right | center | top | bottom | 10.1 | 20%
var type = enum_object[str];
var value = 0;
if (check_enum(background_position_type_2, type)) {
return _background_position(type, value);
}
var m = str.match(/^(-?(?:\d+)?\.?\d+)(%)?$/);
if (m) {
type = enum_object.pixel;
value = parseFloat(m[1]);
if (m[2]) { // %
type = enum_object.percent;
value /= 100; // %
}
return _background_position(type, value);
}
} else if (str instanceof BackgroundPosition) {
return str;
} else if (typeof str == 'number') {
return _background_position(enum_object.pixel, str);
}
throw error(str, desc, ['left', 'right', 'center', 'top', 'bottom', 10, '20%']);
}
export function parseBackgroundSize(str: BackgroundSizeIn, desc?: string) {
if (typeof str == 'string') {
// auto | 10.1 | 20%
var m = str.match(/^((auto)|(-?(?:\d+)?\.?\d+)(%)?)$/);
if (m) {
if (m[2]) { // auto
return _background_size(enum_object.auto, 0);
} else {
var type = enum_object.pixel;
var value = parseFloat(m[3]);
if (m[4]) { // %
type = enum_object.percent;
value /= 100; // %
}
return _background_size(type, value);
}
}
} else if (str instanceof BackgroundSize) {
return str;
} else if (typeof str == 'number') {
return _background_size(enum_object.pixel, str);
}
throw error(str, desc, ['auto', 10, '20%']);
}
enum BGToken {
EOS, //
LPAREN, // (
RPAREN, // )
COMMA, // ,
WHITESPACE, // \s\r\t\n
OTHER, //
}
interface BGScanner {
code: string;
value: string;
index: number;
}
var background_help = `url(res/image.png) repeat(none,[repeat]) position(left,[20%]) size(auto,[10.1])`;
function scanner_background_token(scanner: BGScanner): BGToken {
var token = BGToken.OTHER;
var value = '';
var code = scanner.code;
var index = scanner.index;
do {
if (index >= code.length) {
token = BGToken.EOS;
} else {
switch (code.charCodeAt(index)) {
case 9: // \t
case 10: // \n
case 13: // \r
case 32: // \s
if (value)
token = BGToken.WHITESPACE;
break;
case 40: // (
token = BGToken.LPAREN; break;
case 41: // )
token = BGToken.RPAREN; break;
case 44: // ,
token = BGToken.COMMA; break;
default:
value += code.charAt(index); break;
}
}
index++;
} while (token == BGToken.OTHER);
if (value) {
index--;
token = BGToken.OTHER;
}
scanner.index = index;
scanner.value = value;
return token;
}
function parse_background_paren(scanner: BGScanner, desc?: string): string[] {
if (scanner_background_token(scanner) == BGToken.LPAREN) {
var exp: any[] = [];
var token: BGToken;
while ((token = scanner_background_token(scanner)) != BGToken.EOS) {
switch (token) {
case BGToken.LPAREN:
scanner.index--;
exp.push( parse_background_paren(scanner, desc) );
break;
case BGToken.RPAREN: // )
if (exp.length === 0)
throw error(scanner.code, desc, [background_help]);
return exp;
case BGToken.OTHER:
exp.push( scanner.value );
if (scanner_background_token(scanner) != BGToken.COMMA) { // ,
throw error(scanner.code, desc, [background_help]);
}
break;
}
}
}
throw error(scanner.code, desc, [background_help]);
}
export function parseBackground(str: BackgroundIn, desc?: string): Background {
// url(res/image.png) repeat(none,[repeat]) position(left,[20%]) size(auto,[10.1])
if (str instanceof Background) {
return str;
}
var r: Background | null = null;
if (typeof str == 'string') {
var bgi: BackgroundImage | null = null;
var prev: Background | null = null;
var token: BGToken;
var scanner: BGScanner = { code: str, value: '', index: 0 };
while ( (token = scanner_background_token(scanner)) != BGToken.EOS ) {
switch (token) {
case BGToken.COMMA: {// ,
bgi = null;
break;
}
case BGToken.OTHER: {
if (scanner.value == 'url' || scanner.value == 'image') {
if (bgi)
throw error(str, desc, [background_help]);
bgi = new BackgroundImage();
bgi.src = parse_background_paren(scanner)[0] as string;
if (!r) r = bgi;
if (prev) prev.next = bgi;
prev = bgi;
}
// else if (scanner.value == 'gradient') { }
else {
if (!bgi) throw error(str, desc, [background_help]);
switch (scanner.value) {
case 'repeat': {
if (scanner_background_token(scanner) == BGToken.LPAREN) { // repeat(none)
scanner.index--;
bgi.repeat = parse_background_paren(scanner).map(e=>parseRepeat(e, desc))[0];
} else { // repeat
bgi.repeat = Repeat.REPEAT;
}
break;
}
case 'position': { // position(10,top)
var poss = parse_background_paren(scanner).map(e=>parseBackgroundPosition(e, desc));
bgi.position = { x: poss[0], y: poss[1] || poss[0] };
break;
}
case 'size': { // size(10,20%)
var sizes = parse_background_paren(scanner).map(e=>parseBackgroundSize(e, desc));
bgi.size = { x: sizes[0], y: sizes[1] || sizes[0] };
break;
}
case 'positionX': { // positionX(10)
bgi.positionX = parse_background_paren(scanner).map(e=>parseBackgroundPosition(e, desc))[0];
break;
}
case 'positionY': { // positionY(10)
bgi.positionY = parse_background_paren(scanner).map(e=>parseBackgroundPosition(e, desc))[0];
break;
}
case 'sizeX': { // sizeX(10)
bgi.sizeX = parse_background_paren(scanner).map(e=>parseBackgroundSize(e, desc))[0];
break;
}
case 'sizeY': { // sizeY(10)
bgi.sizeY = parse_background_paren(scanner).map(e=>parseBackgroundSize(e, desc))[0];
break;
}
default:
throw error(str, desc, [background_help]);
}
}
break;
}
default:
throw error(str, desc, [background_help]);
}
}
} else {
if (str.image) {
return Object.assign(new BackgroundImage(), str.image);
}
}
if (r)
return r;
throw error(str, desc, [background_help]);
}
export function parseValues(str: ValuesIn, desc?: string) {
if (typeof str == 'string') {
var rev: Value[] = [];
for (var i of str.split(/\s+/)) {
rev.push(parseValue(i, desc));
}
return rev;
} else if (str instanceof Value) {
return [str];
} else if (Array.isArray(str)) {
return str.map(e=>parseValue(e, desc));
} else {
return [parseValue(str)];
}
throw error(str, desc, ['auto', 'full', 10, '20%', '60!']);
}
export function parseAligns(str: AlignsIn, desc?: string) {
if (typeof str == 'string') {
var rev: Align[] = [];
for (var i of str.split(/\s+/)) {
rev.push(parseAlign(i));
}
return rev;
} else if (Array.isArray(str)) {
return str.map(e=>parseAlign(e));
} else if (check_enum(Align, str)) {
return [str as Align];
}
throw error(str, desc, ['left', 'top center']);
}
export function parseFloats(str: FloatsIn, desc?: string) {
if (typeof str == 'string') {
var ls = str.split(/\s+/);
var rev: number[] = [];
for (var i of str.split(/\s+/)) {
var mat = i.match(/^(-?(?:\d+)?\.?\d+)$/);
if (!mat) {
throw error(str, desc, [10, '10 20 30 40']);
}
rev.push(parseFloat(mat[1]));
}
return rev;
} else if (Array.isArray(str)) {
return str.map(e=>Number(e) || 0);
} else if (isFinite(str)) {
return [str];
}
throw error(str, desc, [10, '10 20 30 40']);
}
export function parseBackgroundPositionCollection(str: BackgroundPositionCollectionIn, desc?: string) {
if (typeof str == 'string') {
var items: BackgroundPosition[] = [];
for (var j of str.split(/\s+/))
items.push(parseBackgroundPosition(j, desc));
var x = items[0] || new BackgroundPosition();
var y = items[1] || x;
return { __proto__: BackgroundPositionCollection.prototype, x, y } as BackgroundPositionCollection;
} else if (str instanceof BackgroundPositionCollection) {
return str;
} else if (str instanceof BackgroundPosition) {
return { __proto__: BackgroundPositionCollection.prototype, x: str, y: str } as BackgroundPositionCollection;
}
throw error(str, desc, [10, '20%', 'left', 'right', 'center', 'top', 'bottom']);
}
export function parseBackgroundSizeCollection(str: BackgroundSizeCollectionIn, desc?: string) {
if (typeof str == 'string') {
var items: BackgroundSize[] = [];
for (var j of str.split(/\s+/))
items.push(parseBackgroundSize(j, desc));
var x = items[0] || new BackgroundSize();
var y = items[1] || x;
return { __proto__: BackgroundSizeCollection.prototype, x, y } as BackgroundSizeCollection;
} else if (str instanceof BackgroundSizeCollection) {
return str;
} else if (str instanceof BackgroundSize) {
return { __proto__: BackgroundSizeCollection.prototype, x: str, y: str } as BackgroundSizeCollection;
}
throw error(str, desc, ['auto', 10, '50%']);
}
export function parseTextColor(str: TextColorIn, desc?: string) {
if (typeof str == 'string') {
if (str == 'inherit') {
return new TextColor();
} else {
var value = parseColor(str);
if (value) {
return new TextColor(TextValueType.VALUE, value);
}
}
} else if (str instanceof TextColor) {
return str;
} else if (str instanceof Color) {
return new TextColor(TextValueType.VALUE, str);
}
throw error(str, desc, ['inherit', 'rgba(255,255,255,255)', 'rgb(255,255,255)', '#ff0', '#ff00', '#ff00ff', '#ff00ffff']);
}
export function parseTextSize(str: TextSizeIn, desc?: string) {
if (typeof str == 'string') {
if (str == 'inherit') {
return new TextSize();
} else {
if (/^(?:\d+)?\.?\d+$/.test(str)) {
return _text_size(TextValueType.VALUE, parseFloat(str));
}
}
} else if (str instanceof TextSize) {
return str;
} else if (typeof str == 'number') {
return _text_size(TextValueType.VALUE, str);
}
throw error(str, desc, ['inherit', 12]);
}
export function parseTextFamily(str: TextFamilyIn, desc?: string) {
if (typeof str == 'string') {
if (str == 'inherit') {
return new TextFamily();
} else {
return _text_family(TextValueType.VALUE, str);
}
} else if (str instanceof TextFamily) {
return str;
}
throw error(str, desc, ['inherit', 'Ubuntu Mono']);
}
export function parseTextStyle(str: TextStyleIn, desc?: string) {
if (typeof str == 'string') {
if (str == 'inherit') {
return new TextStyle();
} else {
var value = enum_object[str];
if (check_enum(TextStyleEnum, value)) {
return _text_style(TextValueType.VALUE, value);
}
}
} else if (str instanceof TextStyle) {
return str;
} else if (check_enum(TextStyleEnum, str)) {
return _text_style(TextValueType.VALUE, str as TextStyleEnum);
}
throw error(str, desc, ['inherit'], TextStyleEnum);
}
export function parseTextShadow(str: TextShadowIn, desc?: string) {
if (typeof str == 'string') {
if (str == 'inherit') {
return new TextShadow();
} else {
var value = parseShadow(str);
if (value) {
return new TextShadow(TextValueType.VALUE, value);
}
}
} else if (str instanceof TextShadow) {
return str;
} else if (str instanceof Shadow) {
return new TextShadow(TextValueType.VALUE, str);
}
throw error(str, desc, ['inherit', '10 10 2 #ff00aa', '10 10 2 rgba(255,255,0,255)']);
}
export function parseTextLineHeight(str: TextLineHeightIn, desc?: string) {
if (typeof str == 'string') {
if (str == 'inherit') {
return new TextLineHeight();
} else if (str == 'auto') {
return _text_line_height(TextValueType.VALUE, 0);
} else {
if (/^(?:\d+)?\.?\d+$/.test(str)) {
return _text_line_height(TextValueType.VALUE, parseFloat(str));
}
}
} else if (str instanceof TextLineHeight) {
return str;
} else if (typeof str == 'number') {
return _text_line_height(TextValueType.VALUE, str);
}
throw error(str, desc, ['inherit', 24]);
}
export function parseTextDecoration(str: TextDecorationIn, desc?: string) {
if (typeof str == 'string') {
if (str == 'inherit') {
return new TextDecoration();
} else {
var value = enum_object[str];
if (check_enum(TextDecorationEnum, value)) {
return _text_decoration(TextValueType.VALUE, value);
}
}
} else if (str instanceof TextDecoration) {
return str;
} else if (check_enum(TextDecorationEnum, str)) {
return _text_decoration(TextValueType.VALUE, str as TextDecorationEnum);
}
throw error(str, desc, ['inherit'], TextDecorationEnum);
}
export function parseTextOverflow(str: TextOverflowIn, desc?: string) {
if (typeof str == 'string') {
if (str == 'inherit') {
return new TextOverflow();
} else {
var value = enum_object[str];
if (check_enum(TextOverflowEnum, value)) {
return _text_overflow(TextValueType.VALUE, value);
}
}
} else if (str instanceof TextOverflow) {
return str;
} else if (check_enum(TextOverflowEnum, str)) {
return _text_overflow(TextValueType.VALUE, str as TextOverflowEnum);
}
throw error(str, desc, ['inherit'], TextOverflowEnum);
}
export function parseTextWhiteSpace(str: TextWhiteSpaceIn, desc?: string) {
if (typeof str == 'string') {
if (str == 'inherit') {
return new TextWhiteSpace();
} else {
var value = enum_object[str];
if (check_enum(TextWhiteSpaceEnum, value)) {
return _text_white_space(TextValueType.VALUE, value);
}
}
} else if (str instanceof TextWhiteSpace) {
return str;
} else if (check_enum(TextWhiteSpaceEnum, str)) {
return _text_white_space(TextValueType.VALUE, str as TextWhiteSpaceEnum);
}
throw error(str, desc, ['inherit'], TextWhiteSpaceEnum);
}
// _priv
const _priv = exports._priv;
delete exports._priv;
Object.assign(_priv, exports);
_priv._Base = Base;
_priv._TextAlign = _text_align;
_priv._Align = _align;
_priv._ContentAlign = _content_align;
_priv._Repeat = _repeat;
_priv._Direction = _direction;
_priv._KeyboardType = _keyboard_type;
_priv._KeyboardReturnType = _keyboard_return_type;
_priv._Border = _border;
_priv._Shadow = _shadow;
_priv._Color = _color;
_priv._Vec2 = _vec2;
_priv._Vec3 = _vec3;
_priv._Vec4 = _vec4;
_priv._Curve = _curve;
_priv._Rect = _rect;
_priv._Mat = _mat;
_priv._Mat4 = _mat4;
_priv._Value = _value;
_priv._BackgroundPosition = _background_position;
_priv._BackgroundSize = _background_size;
_priv._BackgroundPositionCollection = _background_position_collection;
_priv._BackgroundSizeCollection = _background_size_collection;
_priv._TextColor = _text_color;
_priv._TextSize = _text_size;
_priv._TextFamily = _text_family;
_priv._TextStyle = _text_style;
_priv._TextShadow = _text_shadow;
_priv._TextLine_height = _text_line_height;
_priv._TextDecoration = _text_decoration;
_priv._TextOverflow = _text_overflow;
_priv._TextWhiteSpace = _text_white_space; | the_stack |
import * as React from 'react';
import { i18n, I18nProvider } from '../../i18n';
import { Wrapper } from './elements';
import {
Controls,
ControlsWrapper,
ControlsName,
ControlsDescription,
ControlsHeader,
ControlsMain,
InlineControl,
} from '../../common/forms/controls-wrapper';
import { Input } from '../../common/forms/text';
import { RadioButtons } from '../../common/forms/radio';
import { useI18n } from '../../i18n/react';
import { NewRoomStore } from './store';
import { observer } from 'mobx-react-lite';
import { FontAwesomeIcon } from '../../util/icon';
import { WideButton } from '../../common/button';
import { CheckButton } from '../../common/forms/check-button';
import { Select } from '../../common/forms/select';
import { showConfirmDialog } from '../../dialog';
export interface ThemeDoc {
/**
* displayed name of theme.
*/
name: string;
/**
* ID of theme.
*/
value: string;
}
export interface IPropNewRoom {
themes: ThemeDoc[];
store: NewRoomStore;
onCreate(query: unknown): void;
}
export const NewRoom: React.FunctionComponent<IPropNewRoom> = observer(
({ themes, store, onCreate }) => {
const t = useI18n('newroom_client');
const nameInputRef = React.useRef<HTMLInputElement | null>(null);
const passwordInputRef = React.useRef<HTMLInputElement | null>(null);
const commentInputRef = React.useRef<HTMLInputElement | null>(null);
const maxNumberInputRef = React.useRef<HTMLInputElement | null>(null);
const themeSelectRef = React.useRef<HTMLSelectElement | null>(null);
// memory of whether submit button was explicitly clicked (or pressed).
const enterPressedRef = React.useRef(false);
React.useEffect(() => {
// initialize store with saved jobs.
if (localStorage.savedRule) {
try {
const savedRule = JSON.parse(localStorage.savedRule);
if ('number' === typeof savedRule.maxnumber) {
if (maxNumberInputRef.current != null) {
maxNumberInputRef.current.value = String(savedRule.maxnumber);
}
}
if ('string' === typeof savedRule.blind) {
store.setBlind(savedRule.blind);
}
if ('boolean' === typeof savedRule.gm) {
store.setGm(savedRule.gm);
}
if ('boolean' === typeof savedRule.watchspeak) {
store.setWatchSpeak(savedRule.watchspeak);
}
} catch (e) {
console.error(e);
}
}
}, []);
const passwordOptions = React.useMemo(
() => [
{
value: 'no',
label: t('password.no'),
},
{
value: 'yes',
label: t('password.yes'),
},
],
[t],
);
const blindOptions = React.useMemo(
() => [
{
value: '',
label: t('blind.no'),
},
{
value: 'yes',
label: t('game_client:roominfo.blind'),
},
{
value: 'complete',
label: t('game_client:roominfo.blindComplete'),
},
],
[t],
);
const gmOptions = React.useMemo(
() => [
{
value: 'no',
label: t('gm.no'),
},
{
value: 'yes',
label: t('gm.yes'),
},
],
[t],
);
const watchSpeakOptions = React.useMemo(
() => [
{
value: 'no',
label: t('watchSpeak.no'),
},
{
value: 'yes',
label: t('watchSpeak.yes'),
},
],
[t],
);
const keydownHandler = (e: React.KeyboardEvent<HTMLFormElement>) => {
const target = e.target as HTMLInputElement;
if (e.key !== 'Enter') {
return;
}
if (target.tagName === 'INPUT' && target.type === 'submit') {
// allow because user explicitly pressed the submit button.
enterPressedRef.current = false;
} else {
enterPressedRef.current = true;
}
};
const submitHandler = (e: React.SyntheticEvent<HTMLFormElement>) => {
e.preventDefault();
const confirmed = !enterPressedRef.current
? Promise.resolve(true)
: showConfirmDialog({
title: t('title'),
message: t('confirm.message'),
yes: t('confirm.yes'),
no: t('confirm.no'),
});
enterPressedRef.current = false;
confirmed.then(c => {
if (!c) {
// canceled by used
return;
}
const getValue = (
ref: React.RefObject<HTMLInputElement | HTMLSelectElement | null>,
) => {
return ref.current != null ? ref.current.value : '';
};
const query = {
name: getValue(nameInputRef),
usepassword: store.usePassword ? 'on' : '',
password: store.usePassword ? getValue(passwordInputRef) : void 0,
comment: getValue(commentInputRef),
number: getValue(maxNumberInputRef),
blind: store.blind,
theme: getValue(themeSelectRef),
ownerGM: store.gm ? 'yes' : '',
watchspeak: store.watchSpeak ? 'on' : 'off',
};
onCreate(query);
});
};
return (
<Wrapper>
<h1>
{t('title')}
{' '}
<InlineControl>
<CheckButton
slim
checked={store.descriptionShown}
onChange={value => store.setDescriptionShown(value)}
>
{t('showDescriptionButton')}
</CheckButton>
</InlineControl>
</h1>
<form onSubmit={submitHandler} onKeyDown={keydownHandler}>
<ControlsWrapper>
{/* title input */}
<ControlsHeader>
<ControlsName>{t('roomname.title')}</ControlsName>
</ControlsHeader>
<ControlsMain>
<Input type="text" required name="room-name" ref={nameInputRef} />
</ControlsMain>
{/* password settings */}
<ControlsHeader>
<ControlsName>{t('password.title')}</ControlsName>
{store.descriptionShown ? (
<ControlsDescription>
{t('password.description')}
</ControlsDescription>
) : null}
</ControlsHeader>
<ControlsMain>
<RadioButtons
onChange={value => store.setUsePassword(value === 'yes')}
current={store.usePassword ? 'yes' : 'no'}
options={passwordOptions}
/>
{!store.usePassword ? null : (
<>
<FontAwesomeIcon icon="lock" />{' '}
<Input
type="text"
required
size={30}
placeholder={t('password.placeholder')}
ref={passwordInputRef}
/>
</>
)}
</ControlsMain>
{/* comment input */}
<ControlsHeader>
<ControlsName>{t('comment.title')}</ControlsName>
{store.descriptionShown ? (
<ControlsDescription>
{t('comment.description')}
</ControlsDescription>
) : null}
</ControlsHeader>
<ControlsMain>
<Input type="text" name="room-comment" ref={commentInputRef} />
</ControlsMain>
</ControlsWrapper>
{/* max number of room. */}
<Controls
title={t('maxnumber.title')}
description={
store.descriptionShown ? t('maxnumber.description') : void 0
}
compact={!store.descriptionShown}
>
<Input
type="number"
size={10}
defaultValue="30"
min="5"
ref={maxNumberInputRef}
/>
</Controls>
{/* blind mode */}
<Controls
title={t('blind.title')}
description={
store.descriptionShown ? t('blind.description') : void 0
}
compact={!store.descriptionShown}
>
<RadioButtons
onChange={value => store.setBlind(value as any)}
current={store.blind}
options={blindOptions}
/>
</Controls>
{/* theme */}
{themes.length > 0 ? (
<Controls
title={t('theme.title')}
description={
store.descriptionShown ? t('theme.description') : void 0
}
compact={!store.descriptionShown}
>
<Select ref={themeSelectRef}>
<option value="">{t('theme.none')}</option>
{themes.map(theme => (
<option key={theme.value} value={theme.value}>
{theme.name}
</option>
))}
</Select>
</Controls>
) : null}
{/* gm */}
<Controls
title={t('gm.title')}
description={store.descriptionShown ? t('gm.description') : void 0}
compact={!store.descriptionShown}
>
<RadioButtons
onChange={value => store.setGm(value === 'yes')}
current={store.gm ? 'yes' : 'no'}
options={gmOptions}
/>
</Controls>
{/* watchSpeak */}
<Controls
title={t('watchSpeak.title')}
description={
store.descriptionShown ? t('watchSpeak.description') : void 0
}
compact={!store.descriptionShown}
>
<RadioButtons
onChange={value => store.setWatchSpeak(value === 'yes')}
current={store.watchSpeak ? 'yes' : 'no'}
options={watchSpeakOptions}
/>
</Controls>
<WideButton type="submit" disabled={store.formDisabled}>
{t('create')}
</WideButton>
</form>
</Wrapper>
);
},
); | the_stack |
import * as object from "../common/object";
import * as geom from "../format/geom";
import * as dbft from "../format/dragonBonesFormat";
const enum FrameValueType {
Step,
Int,
Float,
}
const intArray: Array<number> = [];
const floatArray: Array<number> = [];
const timelineArray: Array<number> = [];
const frameArray: Array<number> = [];
const frameIntArray: Array<number> = [];
const frameFloatArray: Array<number> = [];
const colorArray: Array<number> = [];
const colors: { [key: string]: number } = {};
let currentArmature: dbft.Armature;
let currentAnimationBinary: dbft.AnimationBinary;
/**
* Convert DragonBones format to binary.
*/
export default function (data: dbft.DragonBones): ArrayBuffer {
// Clean helper.
intArray.length = 0;
floatArray.length = 0;
timelineArray.length = 0;
frameArray.length = 0;
frameIntArray.length = 0;
frameFloatArray.length = 0;
colorArray.length = 0;
for (let k in colors) {
delete colors[k];
}
const binaryDatas = new Array<dbft.BaseData>();
for (currentArmature of data.armature) {
for (const bone of currentArmature.bone) {
if (bone instanceof dbft.Surface) {
bone.offset = createVertices(bone);
binaryDatas.push(bone);
}
}
for (const skin of currentArmature.skin) {
for (const slot of skin.slot) {
for (const display of slot.display) {
if (display instanceof dbft.MeshDisplay) {
display.offset = createMesh(display);
binaryDatas.push(display);
}
else if (display instanceof dbft.PathDisplay) {
display.offset = createVertices(display);
binaryDatas.push(display);
}
else if (display instanceof dbft.PolygonBoundingBoxDisplay) {
display.offset = createVertices(display);
binaryDatas.push(display);
}
}
}
}
const animationBinarys = new Array<dbft.AnimationBinary>();
for (const animation of currentArmature.animation as dbft.Animation[]) {
currentAnimationBinary = new dbft.AnimationBinary();
currentAnimationBinary.type = animation.type;
currentAnimationBinary.blendType = animation.blendType;
currentAnimationBinary.duration = animation.duration;
currentAnimationBinary.playTimes = animation.playTimes;
currentAnimationBinary.scale = animation.scale;
currentAnimationBinary.fadeInTime = animation.fadeInTime;
currentAnimationBinary.name = animation.name;
currentAnimationBinary.offset[dbft.OffsetOrder.FrameInt] = frameIntArray.length;
currentAnimationBinary.offset[dbft.OffsetOrder.FrameFloat] = frameFloatArray.length;
currentAnimationBinary.offset[dbft.OffsetOrder.Frame] = frameArray.length;
animationBinarys.push(currentAnimationBinary);
if (animation.frame.length > 0) {
currentAnimationBinary.action = createTimeline(animation, animation.frame, FrameValueType.Step, 0, createActionFrame);
}
if (animation.zOrder) {
currentAnimationBinary.zOrder = createTimeline(animation.zOrder, animation.zOrder.frame, FrameValueType.Step, 0, createZOrderFrame);
}
for (const timeline of animation.bone) {
currentAnimationBinary.bone[timeline.name] = createBoneTimeline(timeline);
}
for (const timeline of animation.slot) {
if (!(timeline.name in currentAnimationBinary.slot)) {
currentAnimationBinary.slot[timeline.name] = [];
}
const timelines = currentAnimationBinary.slot[timeline.name];
if (timeline.displayFrame.length > 0) {
timelines.push(dbft.TimelineType.SlotDisplay);
timelines.push(createTimeline(timeline, timeline.displayFrame, FrameValueType.Step, 0, (frame, frameStart) => {
const offset = createFrame(frame, frameStart);
frameArray.push(frame.value);
return offset;
}));
}
if (timeline.colorFrame.length > 0) {
timelines.push(dbft.TimelineType.SlotColor);
timelines.push(createTimeline(timeline, timeline.colorFrame, FrameValueType.Int, 1, (frame, frameStart) => {
const offset = createTweenFrame(frame, frameStart);
// Color.
const colorString = frame.value.toString();
if (!(colorString in colors)) {
colors[colorString] = createColor(frame.value);
}
frameIntArray.push(colors[colorString]);
return offset;
}));
}
}
for (const timeline of animation.ffd) {
if (!(timeline.slot in currentAnimationBinary.slot)) {
currentAnimationBinary.slot[timeline.slot] = [];
}
const timelines = currentAnimationBinary.slot[timeline.slot];
timelines.push(createDeformTimeline(timeline));
}
for (const timeline of animation.ik) {
if (!(timeline.name in currentAnimationBinary.constraint)) {
currentAnimationBinary.constraint[timeline.name] = [];
}
const timelines = currentAnimationBinary.constraint[timeline.name];
if (timeline.frame.length > 0) {
timelines.push(dbft.TimelineType.IKConstraint);
timelines.push(createTimeline(timeline, timeline.frame as dbft.IKConstraintFrame[], FrameValueType.Int, 2, (frame, frameStart) => {
const offset = createTweenFrame(frame, frameStart);
frameIntArray.push(frame.bendPositive ? 1 : 0); // TODO 100
frameIntArray.push(Math.round(frame.weight * 100.0));
return offset;
}));
}
currentAnimationBinary.constraint[timeline.name] = timelines;
}
for (const timeline of animation.timeline) {
timeline.offset = createTypeTimeline(timeline);
if (timeline.offset >= 0) {
currentAnimationBinary.timeline.push(timeline);
timeline.clearToBinary();
}
}
}
currentArmature.animation.length = 0;
for (const animation of animationBinarys) {
currentArmature.animation.push(animation);
}
}
// Clear binary data.
for (const data of binaryDatas) {
data.clearToBinary();
}
// Align.
if ((intArray.length % Int16Array.BYTES_PER_ELEMENT) !== 0) {
intArray.push(0);
}
if ((frameIntArray.length % Int16Array.BYTES_PER_ELEMENT) !== 0) {
frameIntArray.push(0);
}
if ((frameArray.length % Int16Array.BYTES_PER_ELEMENT) !== 0) {
frameArray.push(0);
}
if ((timelineArray.length % Uint16Array.BYTES_PER_ELEMENT) !== 0) {
timelineArray.push(0);
}
if ((colorArray.length % Int16Array.BYTES_PER_ELEMENT) !== 0) {
colorArray.push(0);
}
// Offset.
let byteLength = 0;
let byteOffset = 0;
data.offset[0] = 0;
byteLength += data.offset[1] = intArray.length * Int16Array.BYTES_PER_ELEMENT;
data.offset[2] = data.offset[0] + data.offset[1];
byteLength += data.offset[3] = floatArray.length * Float32Array.BYTES_PER_ELEMENT;
data.offset[4] = data.offset[2] + data.offset[3];
byteLength += data.offset[5] = frameIntArray.length * Int16Array.BYTES_PER_ELEMENT;
data.offset[6] = data.offset[4] + data.offset[5];
byteLength += data.offset[7] = frameFloatArray.length * Float32Array.BYTES_PER_ELEMENT;
data.offset[8] = data.offset[6] + data.offset[7];
byteLength += data.offset[9] = frameArray.length * Int16Array.BYTES_PER_ELEMENT;
data.offset[10] = data.offset[8] + data.offset[9];
byteLength += data.offset[11] = timelineArray.length * Uint16Array.BYTES_PER_ELEMENT;
data.offset[12] = data.offset[10] + data.offset[11];
byteLength += data.offset[13] = colorArray.length * Int16Array.BYTES_PER_ELEMENT;
object.compress(data, dbft.compressConfig);
//
const jsonString = JSON.stringify(data);
const jsonArray = stringToUTF8Array(jsonString);
modifyBytesPosition(jsonArray, " ".charCodeAt(0));
//
const buffer = new ArrayBuffer(4 + 4 + 4 + jsonArray.length + byteLength);
const dataView = new DataView(buffer);
// Write DragonBones format tag.
dataView.setUint8(byteOffset++, "D".charCodeAt(0));
dataView.setUint8(byteOffset++, "B".charCodeAt(0));
dataView.setUint8(byteOffset++, "D".charCodeAt(0));
dataView.setUint8(byteOffset++, "T".charCodeAt(0));
// Write version.
dataView.setUint8(byteOffset++, 0);
dataView.setUint8(byteOffset++, 0);
dataView.setUint8(byteOffset++, 0);
dataView.setUint8(byteOffset++, 3);
// Write json length.
dataView.setUint32(byteOffset, jsonArray.length, true); byteOffset += 4;
for (const value of jsonArray) {
dataView.setUint8(byteOffset, value); byteOffset++;
}
for (const value of intArray) {
dataView.setInt16(byteOffset, value, true); byteOffset += 2;
}
for (const value of floatArray) {
dataView.setFloat32(byteOffset, value, true); byteOffset += 4;
}
for (const value of frameIntArray) {
dataView.setInt16(byteOffset, value, true); byteOffset += 2;
}
for (const value of frameFloatArray) {
dataView.setFloat32(byteOffset, value, true); byteOffset += 4;
}
for (const value of frameArray) {
dataView.setInt16(byteOffset, value, true); byteOffset += 2;
}
for (const value of timelineArray) {
dataView.setUint16(byteOffset, value, true); byteOffset += 2;
}
for (const value of colorArray) {
dataView.setInt16(byteOffset, value, true); byteOffset += 2;
}
return buffer;
}
function createColor(value: geom.ColorTransform): number {
const offset = intArray.length;
intArray.length += 8;
intArray[offset + 0] = value.aM;
intArray[offset + 1] = value.rM;
intArray[offset + 2] = value.gM;
intArray[offset + 3] = value.bM;
intArray[offset + 4] = value.aO;
intArray[offset + 5] = value.rO;
intArray[offset + 6] = value.gO;
intArray[offset + 7] = value.bO;
if (offset >= 65536) {
// TODO
}
return offset;
}
function createVertices(value: dbft.VerticesData): number {
const vertexCount = value.vertexCount;
const offset = intArray.length;
const vertexOffset = floatArray.length;
intArray.length += 1 + 1 + 1 + 1;
intArray[offset + dbft.BinaryOffset.GeometryVertexCount] = vertexCount;
intArray[offset + dbft.BinaryOffset.GeometryTriangleCount] = 0;
intArray[offset + dbft.BinaryOffset.GeometryFloatOffset] = vertexOffset;
if (value.weights.length === 0) {
floatArray.length += value.vertices.length;
for (let i = 0, l = value.vertices.length; i < l; i++) {
floatArray[vertexOffset + i] = value.vertices[i];
}
intArray[offset + dbft.BinaryOffset.GeometryWeightOffset] = -1;
}
else {
const weightBoneCount = value.bones.length;
const weightCount = Math.floor(value.weights.length - vertexCount) / 2; // uint
const weightOffset = intArray.length;
const floatOffset = floatArray.length;
intArray.length += 1 + 1 + weightBoneCount;
intArray[weightOffset + dbft.BinaryOffset.WeigthBoneCount] = weightBoneCount;
intArray[weightOffset + dbft.BinaryOffset.WeigthFloatOffset] = floatOffset;
for (let i = 0; i < weightBoneCount; i++) {
intArray[weightOffset + dbft.BinaryOffset.WeigthBoneIndices + i] = value.bones[i];
}
floatArray.length += weightCount * 3;
for (let i = 0, iV = 0, iW = 0, iB = weightOffset + dbft.BinaryOffset.WeigthBoneIndices + weightBoneCount, iF = floatOffset; i < weightCount; i++) {
const boneCount = value.weights[iW++];
intArray[iB++] = boneCount;
for (let j = 0; j < boneCount; j++) {
const boneIndex = value.weights[iW++];
const boneWeight = value.weights[iW++];
intArray[iB++] = value.bones.indexOf(boneIndex);
floatArray[iF++] = boneWeight;
floatArray[iF++] = value.vertices[iV++];
floatArray[iF++] = value.vertices[iV++];
}
}
intArray[offset + dbft.BinaryOffset.GeometryWeightOffset] = weightOffset;
}
return offset;
}
function createMesh(value: dbft.MeshDisplay): number {
const vertexCount = Math.floor(value.vertices.length / 2); // uint
const triangleCount = Math.floor(value.triangles.length / 3); // uint
const offset = intArray.length;
const vertexOffset = floatArray.length;
const uvOffset = vertexOffset + vertexCount * 2;
intArray.length += 1 + 1 + 1 + 1 + triangleCount * 3;
intArray[offset + dbft.BinaryOffset.GeometryVertexCount] = vertexCount;
intArray[offset + dbft.BinaryOffset.GeometryTriangleCount] = triangleCount;
intArray[offset + dbft.BinaryOffset.GeometryFloatOffset] = vertexOffset;
for (let i = 0, l = triangleCount * 3; i < l; ++i) {
intArray[offset + dbft.BinaryOffset.GeometryVertexIndices + i] = value.triangles[i];
}
floatArray.length += vertexCount * 2 + vertexCount * 2;
for (let i = 0, l = vertexCount * 2; i < l; ++i) {
floatArray[vertexOffset + i] = value.vertices[i];
floatArray[uvOffset + i] = value.uvs[i];
}
if (value.weights.length > 0) {
const weightOffset = intArray.length;
const floatOffset = floatArray.length;
value._boneCount = Math.floor(value.bonePose.length / 7);
value._weightCount = Math.floor((value.weights.length - vertexCount) / 2);
intArray.length += 1 + 1 + value._boneCount + vertexCount + value._weightCount;
intArray[weightOffset + dbft.BinaryOffset.WeigthBoneCount] = value._boneCount;
intArray[weightOffset + dbft.BinaryOffset.WeigthFloatOffset] = floatOffset;
for (let i = 0; i < value._boneCount; ++i) {
intArray[weightOffset + dbft.BinaryOffset.WeigthBoneIndices + i] = value.bonePose[i * 7];
}
floatArray.length += value._weightCount * 3;
geom.helpMatrixA.copyFromArray(value.slotPose, 0);
for (
let i = 0, iW = 0, iB = weightOffset + dbft.BinaryOffset.WeigthBoneIndices + value._boneCount, iV = floatOffset;
i < vertexCount;
++i
) {
const iD = i * 2;
const vertexBoneCount = intArray[iB++] = value.weights[iW++]; // uint
let x = floatArray[vertexOffset + iD];
let y = floatArray[vertexOffset + iD + 1];
geom.helpMatrixA.transformPoint(x, y, geom.helpPointA);
x = geom.helpPointA.x;
y = geom.helpPointA.y;
for (let j = 0; j < vertexBoneCount; ++j) {
const rawBoneIndex = value.weights[iW++]; // uint
const bonePoseOffset = value.getBonePoseOffset(rawBoneIndex);
geom.helpMatrixB.copyFromArray(value.bonePose, bonePoseOffset + 1);
geom.helpMatrixB.invert();
geom.helpMatrixB.transformPoint(x, y, geom.helpPointA);
intArray[iB++] = bonePoseOffset / 7; //
floatArray[iV++] = value.weights[iW++];
floatArray[iV++] = geom.helpPointA.x;
floatArray[iV++] = geom.helpPointA.y;
}
}
intArray[offset + dbft.BinaryOffset.GeometryWeightOffset] = weightOffset;
}
else {
intArray[offset + dbft.BinaryOffset.GeometryWeightOffset] = -1;
}
return offset;
}
function createTimeline<T extends dbft.Frame>(
value: dbft.Timeline | dbft.Animation, frames: T[],
frameValueType: FrameValueType, frameValueCount: number,
createFrame: (frame: T, frameStart: number) => number
): number {
const offset = timelineArray.length;
timelineArray.length += 1 + 1 + 1 + 1 + 1;
if (value instanceof dbft.Animation) {
timelineArray[offset + dbft.BinaryOffset.TimelineScale] = 100;
timelineArray[offset + dbft.BinaryOffset.TimelineOffset] = 0;
}
else {
timelineArray[offset + dbft.BinaryOffset.TimelineScale] = Math.round(value.scale * 100.0);
timelineArray[offset + dbft.BinaryOffset.TimelineOffset] = Math.round(value.offset * 100.0);
}
timelineArray[offset + dbft.BinaryOffset.TimelineFrameValueCount] = frameValueCount;
switch (frameValueType) {
case FrameValueType.Step:
timelineArray[offset + dbft.BinaryOffset.TimelineFrameValueOffset] = 0;
break;
case FrameValueType.Int:
timelineArray[offset + dbft.BinaryOffset.TimelineFrameValueOffset] = frameIntArray.length - currentAnimationBinary.offset[dbft.OffsetOrder.FrameInt];
break;
case FrameValueType.Float:
timelineArray[offset + dbft.BinaryOffset.TimelineFrameValueOffset] = frameFloatArray.length - currentAnimationBinary.offset[dbft.OffsetOrder.FrameFloat];
break;
}
let frameStart = 0;
let keyFrameCount = 0;
for (let i = 0, l = frames.length; i < l; ++i) { // Frame offsets.
const frame = frames[i];
const frameOffset = createFrame(frame as any, frameStart);
frameStart += frame.duration;
if (frameOffset >= 0) {
timelineArray.push(frameOffset - currentAnimationBinary.offset[dbft.OffsetOrder.Frame]);
keyFrameCount++;
}
}
timelineArray[offset + dbft.BinaryOffset.TimelineKeyFrameCount] = keyFrameCount;
return offset;
}
function createTypeTimeline(timeline: dbft.TypeTimeline) {
let valueScale = 1.0;
switch (timeline.type) {
case dbft.TimelineType.SlotDisplay:
// TODO
case dbft.TimelineType.SlotZIndex:
return createTimeline(timeline, timeline.frame, FrameValueType.Int, 1, (frame: dbft.SingleValueFrame0, frameStart) => {
const offset = createTweenFrame(frame, frameStart);
frameIntArray.push(frame.value);
return offset;
});
case dbft.TimelineType.BoneAlpha:
case dbft.TimelineType.SlotAlpha:
case dbft.TimelineType.AnimationProgress:
case dbft.TimelineType.AnimationWeight:
valueScale = timeline.type === dbft.TimelineType.BoneAlpha || timeline.type === dbft.TimelineType.SlotAlpha ? 100.0 : 10000.0;
return createTimeline(timeline, timeline.frame, FrameValueType.Int, 1, (frame: dbft.SingleValueFrame0 | dbft.SingleValueFrame1, frameStart) => {
const offset = createTweenFrame(frame, frameStart);
frameIntArray.push(Math.round(frame.value * valueScale));
return offset;
});
case dbft.TimelineType.BoneTranslate:
case dbft.TimelineType.BoneRotate:
case dbft.TimelineType.BoneScale:
valueScale = timeline.type === dbft.TimelineType.BoneRotate ? geom.DEG_RAD : 1.0;
return createTimeline(timeline, timeline.frame, FrameValueType.Float, 2, (frame: dbft.DoubleValueFrame0 | dbft.DoubleValueFrame1, frameStart) => {
const offset = createTweenFrame(frame, frameStart);
frameFloatArray.push(frame.x * valueScale);
frameFloatArray.push(frame.y * valueScale);
return offset;
});
case dbft.TimelineType.IKConstraint:
case dbft.TimelineType.AnimationParameter:
valueScale = timeline.type === dbft.TimelineType.IKConstraint ? 100.0 : 10000.0;
return createTimeline(timeline, timeline.frame, FrameValueType.Int, 2, (frame: dbft.DoubleValueFrame0 | dbft.DoubleValueFrame1, frameStart) => {
const offset = createTweenFrame(frame, frameStart);
frameIntArray.push(Math.round(frame.x * valueScale));
frameIntArray.push(Math.round(frame.y * valueScale));
return offset;
});
case dbft.TimelineType.ZOrder:
// TODO
break;
case dbft.TimelineType.Surface:
return createSurfaceTimeline(timeline);
case dbft.TimelineType.SlotDeform:
return createDeformTimeline(timeline);
case dbft.TimelineType.SlotColor:
return createTimeline(timeline, timeline.frame, FrameValueType.Int, 1, (frame: dbft.SlotColorFrame, frameStart) => {
const offset = createTweenFrame(frame, frameStart);
// Color.
const colorString = frame.value.toString();
if (!(colorString in colors)) {
colors[colorString] = createColor(frame.value);
}
frameIntArray.push(colors[colorString]);
return offset;
});
}
return -1;
}
function createFrame(value: dbft.Frame, frameStart: number): number {
// tslint:disable-next-line:no-unused-expression
value;
const offset = frameArray.length;
frameArray.push(frameStart);
return offset;
}
function createTweenFrame(frame: dbft.TweenFrame, frameStart: number): number {
const frameOffset = createFrame(frame, frameStart);
if (frame.duration > 0) {
if (frame.curve.length > 0) {
const isOmited = (frame.curve.length % 3) === 1;
const sampleCount = frame.duration + (isOmited ? 1 : 3);
const samples = new Array<number>(sampleCount);
dbft.samplingEasingCurve(frame.curve, samples, isOmited);
frameArray.length += 1 + 1 + samples.length;
frameArray[frameOffset + dbft.BinaryOffset.FrameTweenType] = dbft.TweenType.Curve;
frameArray[frameOffset + dbft.BinaryOffset.FrameTweenEasingOrCurveSampleCount] = isOmited ? sampleCount : -sampleCount; // Notice: If not omit data, the count is negative number.
for (let i = 0; i < sampleCount; ++i) {
frameArray[frameOffset + dbft.BinaryOffset.FrameCurveSamples + i] = Math.round(samples[i] * 10000.0); // Min ~ Max [-3.00~3.00]
}
}
else {
if (isNaN(frame.tweenEasing)) {
frameArray.length += 1;
frameArray[frameOffset + dbft.BinaryOffset.FrameTweenType] = dbft.TweenType.None;
}
else if (frame.tweenEasing === 0.0) {
frameArray.length += 1;
frameArray[frameOffset + dbft.BinaryOffset.FrameTweenType] = dbft.TweenType.Line;
}
else if (frame.tweenEasing < 0.0) {
frameArray.length += 1 + 1;
frameArray[frameOffset + dbft.BinaryOffset.FrameTweenType] = dbft.TweenType.QuadIn;
frameArray[frameOffset + dbft.BinaryOffset.FrameTweenEasingOrCurveSampleCount] = Math.round(-frame.tweenEasing * 100.0);
}
else if (frame.tweenEasing <= 1.0) {
frameArray.length += 1 + 1;
frameArray[frameOffset + dbft.BinaryOffset.FrameTweenType] = dbft.TweenType.QuadOut;
frameArray[frameOffset + dbft.BinaryOffset.FrameTweenEasingOrCurveSampleCount] = Math.round(frame.tweenEasing * 100.0);
}
else {
frameArray.length += 1 + 1;
frameArray[frameOffset + dbft.BinaryOffset.FrameTweenType] = dbft.TweenType.QuadInOut;
frameArray[frameOffset + dbft.BinaryOffset.FrameTweenEasingOrCurveSampleCount] = Math.round(frame.tweenEasing * 100.0 - 100.0);
}
}
}
else {
frameArray.length += 1;
frameArray[frameOffset + dbft.BinaryOffset.FrameTweenType] = dbft.TweenType.None;
}
return frameOffset;
}
function createActionFrame(frame: dbft.ActionFrame, frameStart: number): number {
const frameOffset = createFrame(frame, frameStart);
const actionCount = frame.actions.length;
frameArray.length += 1 + 1 + actionCount;
frameArray[frameOffset + dbft.BinaryOffset.FramePosition] = frameStart;
frameArray[frameOffset + dbft.BinaryOffset.ActionFrameActionCount] = actionCount; // Action count.
for (let i = 0; i < actionCount; ++i) { // Action offsets.
const action = frame.actions[i];
frameArray[frameOffset + dbft.BinaryOffset.ActionFrameActionIndices + i] = currentArmature.actions.length;
currentArmature.actions.push(action);
}
frame.actions.length = 0;
return frameOffset;
}
function createZOrderFrame(frame: dbft.MutilpleValueFrame, frameStart: number): number {
const frameOffset = createFrame(frame, frameStart);
if (frame.zOrder.length > 0) {
const slotCount = currentArmature.slot.length;
const unchanged = new Array<number>(slotCount - frame.zOrder.length / 2);
const zOrders = new Array<number>(slotCount);
for (let i = 0; i < unchanged.length; ++i) {
unchanged[i] = 0;
}
for (let i = 0; i < slotCount; ++i) {
zOrders[i] = -1;
}
let originalIndex = 0;
let unchangedIndex = 0;
for (let i = 0, l = frame.zOrder.length; i < l; i += 2) {
const slotIndex = frame.zOrder[i];
const zOrderOffset = frame.zOrder[i + 1];
while (originalIndex !== slotIndex) {
unchanged[unchangedIndex++] = originalIndex++;
}
zOrders[originalIndex + zOrderOffset] = originalIndex++;
}
while (originalIndex < slotCount) {
unchanged[unchangedIndex++] = originalIndex++;
}
frameArray.length += 1 + slotCount;
frameArray[frameOffset + 1] = slotCount;
let i = slotCount;
while (i--) {
if (zOrders[i] === -1) {
frameArray[frameOffset + 2 + i] = unchanged[--unchangedIndex] || 0;
}
else {
frameArray[frameOffset + 2 + i] = zOrders[i] || 0;
}
}
}
else {
frameArray.length += 1;
frameArray[frameOffset + 1] = 0;
}
return frameOffset;
}
function createBoneTimeline(timeline: dbft.BoneTimeline): number[] {
const timelines = new Array<number>();
if (timeline.translateFrame.length > 0) {
timelines.push(dbft.TimelineType.BoneTranslate);
timelines.push(createTimeline(timeline, timeline.translateFrame, FrameValueType.Float, 2, (frame, frameStart): number => {
const offset = createTweenFrame(frame, frameStart);
frameFloatArray.push(frame.x);
frameFloatArray.push(frame.y);
return offset;
}));
}
if (timeline.rotateFrame.length > 0) {
let clockwise = 0;
let prevRotate = 0.0;
timelines.push(dbft.TimelineType.BoneRotate);
timelines.push(createTimeline(timeline, timeline.rotateFrame, FrameValueType.Float, 2, (frame, frameStart): number => {
const offset = createTweenFrame(frame, frameStart);
let rotate = frame.rotate;
if (frameStart !== 0) {
if (clockwise === 0) {
rotate = prevRotate + geom.normalizeDegree(rotate - prevRotate);
}
else {
if (clockwise > 0 ? rotate >= prevRotate : rotate <= prevRotate) {
clockwise = clockwise > 0 ? clockwise - 1 : clockwise + 1;
}
rotate = prevRotate + rotate - prevRotate + geom.PI_D * clockwise * geom.RAD_DEG;
}
}
clockwise = frame.clockwise;
prevRotate = rotate;
frameFloatArray.push(rotate * geom.DEG_RAD);
frameFloatArray.push(geom.normalizeDegree(frame.skew) * geom.DEG_RAD);
return offset;
}));
}
if (timeline.scaleFrame.length > 0) {
timelines.push(dbft.TimelineType.BoneScale);
timelines.push(createTimeline(timeline, timeline.scaleFrame, FrameValueType.Float, 2, (frame, frameStart): number => {
const offset = createTweenFrame(frame, frameStart);
frameFloatArray.push(frame.x);
frameFloatArray.push(frame.y);
return offset;
}));
}
return timelines;
}
function createSurfaceTimeline(timeline: dbft.TypeTimeline): number {
const surface = currentArmature.getBone(timeline.name) as dbft.Surface;
const vertexCount = surface.vertices.length / 2;
const frames = timeline.frame as dbft.MutilpleValueFrame[];
for (const frame of frames) {
let x = 0.0;
let y = 0.0;
const vertices = new Array<number>();
for (
let i = 0;
i < vertexCount * 2;
i += 2
) {
if (frame.value.length === 0) {
x = 0.0;
y = 0.0;
}
else {
if (i < frame.offset || i - frame.offset >= frame.value.length) {
x = 0.0;
}
else {
x = frame.value[i - frame.offset];
}
if (i + 1 < frame.offset || i + 1 - frame.offset >= frame.value.length) {
y = 0.0;
}
else {
y = frame.value[i + 1 - frame.offset];
}
}
vertices.push(x, y);
}
frame.value.length = 0;
for (const value of vertices) {
frame.value.push(value);
}
}
const firstValues = frames[0].value;
const count = firstValues.length;
let completedBegin = false;
let completedEnd = false;
let begin = 0;
let end = count - 1;
while (!completedBegin || !completedEnd) {
if (!completedBegin) {
for (const frame of frames) {
if (frame.value[begin] !== firstValues[begin]) {
completedBegin = true;
break;
}
}
if (begin === count - 1) {
completedBegin = true;
}
else if (!completedBegin) {
begin++;
}
}
if (completedBegin && !completedEnd) {
for (const frame of frames) {
if (frame.value[end] !== firstValues[end]) {
completedEnd = true;
break;
}
}
if (end === begin) {
completedEnd = true;
}
else if (!completedEnd) {
end--;
}
}
}
const frameIntOffset = frameIntArray.length;
const valueCount = end - begin + 1;
frameIntArray.length += 5;
frameIntArray[frameIntOffset + dbft.BinaryOffset.DeformMeshOffset] = surface.offset; // Surface offset.
frameIntArray[frameIntOffset + dbft.BinaryOffset.DeformCount] = count; // Deform count.
frameIntArray[frameIntOffset + dbft.BinaryOffset.DeformValueCount] = valueCount; // Value count.
frameIntArray[frameIntOffset + dbft.BinaryOffset.DeformValueOffset] = begin; // Value offset.
frameIntArray[frameIntOffset + dbft.BinaryOffset.DeformFloatOffset] = frameFloatArray.length - currentAnimationBinary.offset[dbft.OffsetOrder.FrameFloat]; // Float offset.
for (let i = 0; i < begin; ++i) {
frameFloatArray.push(firstValues[i]);
}
for (let i = end + 1; i < count; ++i) {
frameFloatArray.push(firstValues[i]);
}
const timelineOffset = createTimeline(timeline, frames, FrameValueType.Float, valueCount, (frame, frameStart) => {
const offset = createTweenFrame(frame, frameStart);
for (let i = 0; i < valueCount; ++i) {
frameFloatArray.push(frame.value[begin + i]);
}
return offset;
});
// Get more infomation form value count offset.
timelineArray[timelineOffset + dbft.BinaryOffset.TimelineFrameValueCount] = frameIntOffset - currentAnimationBinary.offset[dbft.OffsetOrder.FrameInt];
return timelineOffset;
}
function createDeformTimeline(timeline: dbft.SlotDeformTimeline | dbft.TypeTimeline): number {
const mesh = (
timeline instanceof dbft.SlotDeformTimeline ?
currentArmature.getDisplay(timeline.skin, timeline.slot, timeline.name) :
currentArmature.getDisplay("", "", timeline.name)
) as dbft.MeshDisplay | null; // TODO
if (!mesh) {
return -1;
}
const vertexCount = mesh.vertices.length / 2;
const frames = timeline.frame as dbft.MutilpleValueFrame[];
for (const frame of frames) {
let x = 0.0;
let y = 0.0;
let iB = 0;
if (mesh.weights.length > 0) {
geom.helpMatrixA.copyFromArray(mesh.slotPose, 0);
// frameFloatArray.length += mesh._weightCount * 2; // TODO CK
}
else {
// frameFloatArray.length += vertexCount * 2;
}
if (frame.vertices.length > 0) { //
frame.value.length = 0;
for (const value of frame.vertices) {
frame.value.push(value);
}
frame.vertices.length = 0;
}
const vertices = new Array<number>();
for (
let i = 0;
i < vertexCount * 2;
i += 2
) {
if (frame.value.length === 0) {
x = 0.0;
y = 0.0;
}
else {
if (i < frame.offset || i - frame.offset >= frame.value.length) {
x = 0.0;
}
else {
x = frame.value[i - frame.offset];
}
if (i + 1 < frame.offset || i + 1 - frame.offset >= frame.value.length) {
y = 0.0;
}
else {
y = frame.value[i + 1 - frame.offset];
}
}
if (mesh.weights.length > 0) { // If mesh is skinned, transform point by bone bind pose.
const vertexBoneCount = mesh.weights[iB++];
geom.helpMatrixA.transformPoint(x, y, geom.helpPointA, true);
x = geom.helpPointA.x;
y = geom.helpPointA.y;
for (let j = 0; j < vertexBoneCount; ++j) {
const rawBoneIndex = mesh.weights[iB];
geom.helpMatrixB.copyFromArray(mesh.bonePose, mesh.getBonePoseOffset(rawBoneIndex) + 1);
geom.helpMatrixB.invert();
geom.helpMatrixB.transformPoint(x, y, geom.helpPointA, true);
vertices.push(geom.helpPointA.x, geom.helpPointA.y);
iB += 2;
}
}
else {
vertices.push(x, y);
}
}
frame.value.length = 0;
for (const value of vertices) {
frame.value.push(value);
}
}
const firstValues = frames[0].value;
const count = firstValues.length;
let completedBegin = false;
let completedEnd = false;
let begin = 0;
let end = count - 1;
while (!completedBegin || !completedEnd) {
if (!completedBegin) {
for (const frame of frames) {
if (frame.value[begin] !== firstValues[begin]) {
completedBegin = true;
break;
}
}
if (begin === count - 1) {
completedBegin = true;
}
else if (!completedBegin) {
begin++;
}
}
if (completedBegin && !completedEnd) {
for (const frame of frames) {
if (frame.value[end] !== firstValues[end]) {
completedEnd = true;
break;
}
}
if (end === begin) {
completedEnd = true;
}
else if (!completedEnd) {
end--;
}
}
}
const frameIntOffset = frameIntArray.length;
const valueCount = end - begin + 1;
frameIntArray.length += 5;
frameIntArray[frameIntOffset + dbft.BinaryOffset.DeformMeshOffset] = mesh.offset; // Mesh offset.
frameIntArray[frameIntOffset + dbft.BinaryOffset.DeformCount] = count; // Deform count.
frameIntArray[frameIntOffset + dbft.BinaryOffset.DeformValueCount] = valueCount; // Value count.
frameIntArray[frameIntOffset + dbft.BinaryOffset.DeformValueOffset] = begin; // Value offset.
frameIntArray[frameIntOffset + dbft.BinaryOffset.DeformFloatOffset] = frameFloatArray.length - currentAnimationBinary.offset[dbft.OffsetOrder.FrameFloat]; // Float offset.
for (let i = 0; i < begin; ++i) {
frameFloatArray.push(firstValues[i]);
}
for (let i = end + 1; i < count; ++i) {
frameFloatArray.push(firstValues[i]);
}
const timelineOffset = createTimeline(timeline, frames, FrameValueType.Float, valueCount, (frame, frameStart) => {
const offset = createTweenFrame(frame, frameStart);
for (let i = 0; i < valueCount; ++i) {
frameFloatArray.push(frame.value[begin + i]);
}
return offset;
});
// Get more infomation form value count offset.
timelineArray[timelineOffset + dbft.BinaryOffset.TimelineFrameValueCount] = frameIntOffset - currentAnimationBinary.offset[dbft.OffsetOrder.FrameInt];
return timelineOffset;
}
function modifyBytesPosition(bytes: number[], byte: number = 0): void {
while ((bytes.length % 4) !== 0) {
bytes.push(byte);
}
}
function stringToUTF8Array(string: string): number[] {
const result: number[] = [];
for (let i = 0; i < string.length; i++) {
const c = string.charAt(i);
const cc = c.charCodeAt(0);
if (cc > 0xFFFF) {
throw new Error("InvalidCharacterError");
}
if (cc > 0x80) {
if (cc < 0x07FF) {
const c1 = (cc >>> 6) | 0xC0;
const c2 = (cc & 0x3F) | 0x80;
result.push(c1, c2);
}
else {
const c1 = (cc >>> 12) | 0xE0;
const c2 = ((cc >>> 6) & 0x3F) | 0x80;
const c3 = (cc & 0x3F) | 0x80;
result.push(c1, c2, c3);
}
}
else {
result.push(cc);
}
}
return result;
} | the_stack |
import {
Live2DCubismFramework as live2dcubismframework,
Option as Csm_Option
} from '@framework/live2dcubismframework';
import Csm_CubismFramework = live2dcubismframework.CubismFramework;
import {LAppView} from './lappview';
import {LAppPal} from './lapppal';
import {LAppTextureManager} from './lapptexturemanager';
import {LAppLive2DManager} from './lapplive2dmanager';
import * as LAppDefine from './lappdefine';
import {LAppModel} from "./lappmodel";
import { DebugLogEnable } from './lappdefine';
export let canvas: HTMLCanvasElement = null;
export let s_instance: LAppDelegate = null;
export let gl: WebGLRenderingContext = null;
export let frameBuffer: WebGLFramebuffer = null;
export let scale: number = window.devicePixelRatio;
export let lAppDelegateEvent:LAppDelegateEvent = null;
let lastCalledTime;
let fps;
let curr_window = null;
if (LAppDefine.IsElectron){
const { remote } = require('electron')
let curr_window = remote.getCurrentWindow();
}
interface LAppDelegateEvent {
modelCompleteSetup();
}
/**
* アプリケーションクラス。
* Cubism SDKの管理を行う。
*/
export class LAppDelegate {
/**
* クラスのインスタンス(シングルトン)を返す。
* インスタンスが生成されていない場合は内部でインスタンスを生成する。
*
* @return クラスのインスタンス
*/
public static getInstance(): LAppDelegate {
if (s_instance == null) {
s_instance = new LAppDelegate();
}
return s_instance;
}
/**
* クラスのインスタンス(シングルトン)を解放する。
*/
public static releaseInstance(): void {
if (s_instance != null) {
s_instance.release();
}
s_instance = null;
}
/**
* APPに必要な物を初期化する。
*/
public initialize(): boolean {
// キャンバスの作成
canvas = document.createElement('canvas');
canvas.width = LAppDefine.RenderTargetWidth;
canvas.height = LAppDefine.RenderTargetHeight;
canvas.style.width = canvas.width + 'px';
canvas.style.height = canvas.height + 'px';
canvas.width = canvas.width * scale;
canvas.height = canvas.height * scale;
// canvas.setAttribute('style','width:'+LAppDefine.RenderTargetWidth+'px;height:'+LAppDefine.RenderTargetHeight+'px');
// glコンテキストを初期化
// @ts-ignore
gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
if (!gl) {
alert('Cannot initialize WebGL. This browser does not support.');
gl = null;
document.body.innerHTML =
'This browser does not support the <code><canvas></code> element.';
// gl初期化失敗
return false;
}
// キャンバスを DOM に追加
document.body.appendChild(canvas);
if (!frameBuffer) {
frameBuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
}
// 透過設定
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
const supportTouch: boolean = 'ontouchend' in canvas;
// document.getElementsByName('body')[0].on
if (supportTouch) {
// タッチ関連コールバック関数登録
canvas.ontouchstart = onTouchBegan;
canvas.ontouchmove = onTouchMoved;
canvas.ontouchend = onTouchEnded;
canvas.ontouchcancel = onTouchCancel;
} else {
// マウス関連コールバック関数登録
canvas.onmousedown = onClickBegan;
canvas.onmousemove = onMouseMoved;
canvas.onmouseup = onClickEnded;
canvas.onmouseenter = onMouseEnter;
canvas.onmouseleave = onMouseLeave;
}
// AppViewの初期化
this._view.initialize();
// Cubism SDKの初期化
this.initializeCubism();
return true;
}
/**
* 解放する。
*/
public release(): void {
this._textureManager.release();
this._textureManager = null;
this._view.release();
this._view = null;
// リソースを解放
LAppLive2DManager.releaseInstance();
// Cubism SDKの解放
Csm_CubismFramework.dispose();
}
/**
* 実行処理。
*/
public run(): void {
if (DebugLogEnable){
let fps_element = document.createElement('div');
fps_element.style.position = 'absolute';
fps_element.style.right = '0';
fps_element.style.top = '0';
fps_element.style.color = 'rebeccapurple';
document.body.appendChild(fps_element)
setInterval(function () {
fps_element.innerText = 'fps:'+fps.toFixed(2);
},1000)
}
// メインループ
const loop = (): void => {
// インスタンスの有無の確認
if (s_instance == null) {
return;
}
// if(!lastCalledTime) {
// lastCalledTime = Date.now();
// fps = 0;
// return;
// }
let delta = (Date.now() - lastCalledTime)/1000;
lastCalledTime = Date.now();
fps = 1/delta;
// 時間更新
LAppPal.updateTime();
// 画面の初期化
gl.clearColor(0.0, 0.0, 0.0, 0.0);
// 深度テストを有効化
gl.enable(gl.DEPTH_TEST);
// 近くにある物体は、遠くにある物体を覆い隠す
gl.depthFunc(gl.LEQUAL);
// カラーバッファや深度バッファをクリアする
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.clearDepth(1.0);
// 透過設定
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
// 描画更新
this._view.render();
// 建立像素集合 这种方式性能canvas缓冲区越大越差
// pixels = new Uint8Array( canvas.width*canvas.height*4);
// //从缓冲区读取像素数据,然后将其装到事先建立好的像素集合里
// gl.readPixels(0, 0,gl.drawingBufferWidth, gl.drawingBufferHeight, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
// ループのために再帰呼び出し
requestAnimationFrame(loop);
};
loop();
}
/**
* シェーダーを登録する。
*/
public createShader(): WebGLProgram {
// バーテックスシェーダーのコンパイル
const vertexShaderId = gl.createShader(gl.VERTEX_SHADER);
if (vertexShaderId == null) {
LAppPal.printMessage('failed to create vertexShader');
return null;
}
const vertexShader: string =
'precision mediump float;' +
'attribute vec3 position;' +
'attribute vec2 uv;' +
'varying vec2 vuv;' +
'void main(void)' +
'{' +
' gl_Position = vec4(position, 1.0);' +
' vuv = uv;' +
'}';
gl.shaderSource(vertexShaderId, vertexShader);
gl.compileShader(vertexShaderId);
// フラグメントシェーダのコンパイル
const fragmentShaderId = gl.createShader(gl.FRAGMENT_SHADER);
if (fragmentShaderId == null) {
LAppPal.printMessage('failed to create fragmentShader');
return null;
}
const fragmentShader: string =
'precision mediump float;' +
'varying vec2 vuv;' +
'uniform sampler2D texture;' +
'void main(void)' +
'{' +
' gl_FragColor = texture2D(texture, vuv);' +
'}';
gl.shaderSource(fragmentShaderId, fragmentShader);
gl.compileShader(fragmentShaderId);
// プログラムオブジェクトの作成
const programId = gl.createProgram();
gl.attachShader(programId, vertexShaderId);
gl.attachShader(programId, fragmentShaderId);
gl.deleteShader(vertexShaderId);
gl.deleteShader(fragmentShaderId);
// リンク
gl.linkProgram(programId);
gl.useProgram(programId);
return programId;
}
/**
* View情報を取得する。
*/
public getView(): LAppView {
return this._view;
}
public setLappModelEvent(call:LAppDelegateEvent){
lAppDelegateEvent = call;
}
public getTextureManager(): LAppTextureManager {
return this._textureManager;
}
/**
* コンストラクタ
*/
constructor() {
this._captured = false;
this._mouseX = 0.0;
this._mouseY = 0.0;
this._isEnd = false;
this._cubismOption = new Csm_Option();
this._view = new LAppView();
this._textureManager = new LAppTextureManager();
}
/**
* Cubism SDKの初期化
*/
public initializeCubism(): void {
// setup cubism
this._cubismOption.logFunction = LAppPal.printMessage;
this._cubismOption.loggingLevel = LAppDefine.CubismLoggingLevel;
Csm_CubismFramework.startUp(this._cubismOption);
// initialize cubism
Csm_CubismFramework.initialize();
// load model
LAppLive2DManager.getInstance();
LAppPal.updateTime();
this._view.initializeSprite();
}
_cubismOption: Csm_Option; // Cubism SDK Option
_view: LAppView; // View情報
_captured: boolean; // 点击了吗?
_mouseX: number; // X坐标
_mouseY: number; // 鼠标Y坐标
_isEnd: boolean; // APP終了しているか
_textureManager: LAppTextureManager; // テクスチャマネージャー
}
function onMouseLeave() {
LAppPal.log("划出去")
const live2DManager: LAppLive2DManager = LAppLive2DManager.getInstance();
live2DManager.onDrag(0.0, 0.0);
}
function onMouseEnter(e: MouseEvent) {
e.preventDefault()
LAppPal.log("划进来")
}
/**
* クリックしたときに呼ばれる。
*/
function onClickBegan(e: MouseEvent): void {
LAppPal.log('click_began')
if (!LAppDelegate.getInstance()._view) {
LAppPal.printMessage('view notfound');
return;
}
LAppDelegate.getInstance()._captured = true;
let posX: number = e.pageX;
let posY: number = e.pageY;
posX *= scale;
posY *= scale;
LAppDelegate.getInstance()._view.onTouchesBegan(posX, posY);
}
export function hitModel(posX,posY) {
let view = LAppDelegate.getInstance().getView()
const viewX: number = view.transformViewX(posX);
const viewY: number = view.transformViewY(posY);
return LAppLive2DManager.getInstance().hitModel(viewX,viewY)
// console.log(pixels) 配合loop里的readPixels 虽然性能较差,但可以控制的点很多,比如像素颜色
// return pixels[((posY * (canvas.width * 4)) + (posX * 4)) + 3] > 0;
}
/**
* マウスポインタが動いたら呼ばれる。
*/
function onMouseMoved(e: MouseEvent): void {
// if (!LAppDelegate.getInstance()._captured) {
// return;
// }
if (!LAppDelegate.getInstance()._view) {
LAppPal.printMessage('view notfound');
return;
}
const rect = (e.target as Element).getBoundingClientRect();
let posX: number = e.clientX - rect.left;
let posY: number = e.clientY - rect.top;
posX *= scale;
posY *= scale;
let hit = LAppLive2DManager.getInstance();
let hitstr = hit.isHit(posX,posY);
if (hitstr != "" && hit.move_hit){
hit.move_hit(hitstr)
}
if (LAppDefine.IsElectron){
if (!hitstr){
//整个app 忽略所有点击事件
curr_window.setIgnoreMouseEvents(true, { forward: true })
LAppPal.log(true,'move')
}else{
curr_window.setIgnoreMouseEvents(false,{ forward: true })
LAppPal.log(false,'move')
}
}
LAppDelegate.getInstance()._view.onTouchesMoved(posX, posY);
}
/**
* クリックが終了したら呼ばれる。
*/
function onClickEnded(e: MouseEvent): void {
LAppDelegate.getInstance()._captured = false;
if (!LAppDelegate.getInstance()._view) {
LAppPal.printMessage('view notfound');
return;
}
const rect = (e.target as Element).getBoundingClientRect();
let posX: number = e.clientX - rect.left;
let posY: number = e.clientY - rect.top;
// 解决模糊问题
posX *= scale;
posY *= scale;
LAppPal.log('点击')
let hit = LAppLive2DManager.getInstance();
let hitstr = hit.isHit(posX,posY);
if (hitstr != ""&&hit.click_hit){
hit.click_hit(hitstr)
}
LAppDelegate.getInstance()._view.onTouchesEnded(posX, posY);
}
/**
* タッチしたときに呼ばれる。
*/
function onTouchBegan(e: TouchEvent): void {
if (!LAppDelegate.getInstance()._view) {
LAppPal.printMessage('view notfound');
return;
}
LAppDelegate.getInstance()._captured = true;
let posX = e.changedTouches[0].pageX;
let posY = e.changedTouches[0].pageY;
posX *= scale;
posY *= scale;
LAppDelegate.getInstance()._view.onTouchesBegan(posX, posY);
}
/**
* スワイプすると呼ばれる。
*/
function onTouchMoved(e: TouchEvent): void {
if (!LAppDelegate.getInstance()._captured) {
return;
}
if (!LAppDelegate.getInstance()._view) {
LAppPal.printMessage('view notfound');
return;
}
const rect = (e.target as Element).getBoundingClientRect();
let posX = e.changedTouches[0].clientX - rect.left;
let posY = e.changedTouches[0].clientY - rect.top;
posX *= scale;
posY *= scale;
LAppDelegate.getInstance()._view.onTouchesMoved(posX, posY);
}
/**
* タッチが終了したら呼ばれる。
*/
function onTouchEnded(e: TouchEvent): void {
LAppDelegate.getInstance()._captured = false;
if (!LAppDelegate.getInstance()._view) {
LAppPal.printMessage('view notfound');
return;
}
const rect = (e.target as Element).getBoundingClientRect();
let posX = e.changedTouches[0].clientX - rect.left;
let posY = e.changedTouches[0].clientY - rect.top;
posX *= scale;
posY *= scale;
LAppDelegate.getInstance()._view.onTouchesEnded(posX, posY);
}
/**
* タッチがキャンセルされると呼ばれる。
*/
function onTouchCancel(e: TouchEvent): void {
LAppDelegate.getInstance()._captured = false;
if (!LAppDelegate.getInstance()._view) {
LAppPal.printMessage('view notfound');
return;
}
const rect = (e.target as Element).getBoundingClientRect();
const posX = e.changedTouches[0].clientX - rect.left;
const posY = e.changedTouches[0].clientY - rect.top;
LAppDelegate.getInstance()._view.onTouchesEnded(posX, posY);
} | the_stack |
import { mount, Wrapper } from '@vue/test-utils'
import Picker from '../'
import PickerColumn from '../WPickerColumn'
import { slowVerticalDrag } from '@/test/unit/utils'
import { ExtractVue } from '@/utils/mixins'
const testSingleColumn = [
{
options: [1, 2, 3],
},
]
const testMultiColumn = [
{
options: [1, 2, 3],
},
{
options: ['yes', 'no'],
},
]
type PickerWrapper = Wrapper<ExtractVue<typeof Picker>>
type PickerColumnWrapper = Wrapper<ExtractVue<typeof PickerColumn>>
describe('picker', () => {
test('create', () => {
const wrapper = mount(Picker, {
propsData: {
visible: true,
},
})
expect(wrapper.name()).toBe('w-picker')
expect(wrapper.html()).toMatchSnapshot()
})
test('create a single-column picker', () => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
visible: true,
columns: testSingleColumn,
},
})
expect(wrapper.findAll(PickerColumn)).toHaveLength(1)
expect(wrapper.vm.getColumnOptions(0)).toHaveLength(3)
expect(wrapper.vm.getValues()).toEqual([1])
expect(wrapper.html()).toMatchSnapshot()
})
test('create a multi-column picker', () => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
visible: true,
columns: testMultiColumn,
},
})
expect(wrapper.findAll(PickerColumn)).toHaveLength(2)
expect(wrapper.vm.getColumnOptions(0)).toHaveLength(3)
expect(wrapper.vm.getColumnOptions(1)).toHaveLength(2)
expect(wrapper.vm.getValues()).toEqual([1, 'yes'])
expect(wrapper.html()).toMatchSnapshot()
})
test('getColumnValue method', () => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
visible: true,
columns: testSingleColumn,
},
})
expect(wrapper.vm.getColumnValue(0)).toEqual(1)
})
test('getColumnOptions method', () => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
visible: true,
columns: testMultiColumn,
},
})
expect(wrapper.vm.getColumnOptions(0)).toEqual([1, 2, 3])
expect(wrapper.vm.getColumnOptions(1)).toEqual(['yes', 'no'])
})
test('test setColumnValue method', () => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
visible: true,
columns: testMultiColumn,
},
})
wrapper.vm.setColumnOptions(0, [1, 2, 3])
expect(wrapper.vm.getColumnOptions(0)).toEqual([1, 2, 3])
})
test('test getValues method', () => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
visible: true,
columns: testSingleColumn,
},
})
expect(wrapper.vm.getValues()).toEqual([1])
})
test('test setValues method', () => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
visible: true,
columns: [
{
options: [1, 2, 3],
default: 0,
},
],
},
})
wrapper.vm.setValues([2])
expect(wrapper.vm.getValues()).toEqual([2])
})
test('test getColumnIndex method', () => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
visible: true,
columns: testMultiColumn,
},
})
expect(wrapper.vm.getColumnIndex(0)).toBe(0)
expect(wrapper.vm.getColumnIndex(1)).toBe(0)
})
test('test setColumnIndex method', () => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
visible: true,
columns: testMultiColumn,
},
})
wrapper.vm.setColumnIndex(0, 1)
wrapper.vm.setColumnIndex(1, 1)
expect(wrapper.vm.getIndexes()).toEqual([1, 1])
})
test('test getIndexes method', () => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
visible: true,
columns: testMultiColumn,
},
})
expect(wrapper.vm.getIndexes()).toEqual([0, 0])
})
test('test setIndexes method', () => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
visible: true,
columns: testMultiColumn,
},
})
wrapper.vm.setIndexes([1, 1])
expect(wrapper.vm.getIndexes()).toEqual([1, 1])
})
test('click cancel button', () => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
'visible.sync': true,
columns: [],
},
})
wrapper
.findAll('.weui-picker__action')
.at(0)
.trigger('click')
expect(wrapper.vm.isActive).toBe(false)
expect(wrapper.emitted().cancel).toBeTruthy()
})
test('click confirm button', () => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
'visible.sync': true,
columns: [],
},
})
wrapper
.findAll('.weui-picker__action')
.at(1)
.trigger('click')
expect(wrapper.vm.isActive).toBe(false)
expect(wrapper.emitted().confirm).toBeTruthy()
})
test('when column value changed, change event should be emitted', () => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
visible: true,
columns: [
{
options: [1, 2, 3],
default: 0,
},
],
},
})
wrapper
.findAll(PickerColumn)
.at(0)
.vm.$emit('change', 0)
expect(wrapper.emitted().change).toBeTruthy()
})
test('value watcher', () => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
visible: true,
columns: [
{
options: [1, 2, 3],
default: 0,
},
],
},
})
const spy = jest.spyOn(wrapper.vm, 'setValues')
wrapper.setProps({
value: [2],
})
expect(spy).toHaveBeenCalled()
})
})
describe('picker-column', () => {
// test('create', () => {
// const wrapper = mount(PickerColumn, {
// parentComponent: Picker
// })
//
// expect(wrapper.name()).toBe('w-picker-column')
// })
// test('create using object-array values', () => {
// const options = [
// {
// label: 'label1',
// value: 'value1'
// },
// {
// label: 'label2',
// value: 'value2'
// },
// {
// label: 'label3',
// value: 'value3'
// }
// ]
//
// const wrapper = mount(PickerColumn, {
// parentComponent: Picker,
// propsData: {
// options: options,
// valueKey: 'value'
// }
// })
//
// expect(wrapper.findAll('.weui-picker__item').length).toBe(3)
// })
// test('render a divider slot', () => {
// const wrapper = mount(PickerColumn, {
// parentComponent: Picker,
// propsData: {
// divider: true,
// content: '-'
// }
// })
//
// expect(wrapper.text()).toBe('-')
// })
test(
'drag slot',
() => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
visible: true,
columns: testSingleColumn,
},
})
const columnWrapper = wrapper.find(PickerColumn) as PickerColumnWrapper
slowVerticalDrag(columnWrapper, 0, -34)
expect(columnWrapper.vm.currentIndex).toBe(1)
slowVerticalDrag(columnWrapper, 0, -34)
expect(columnWrapper.vm.currentIndex).toBe(2)
// this will out of range
slowVerticalDrag(columnWrapper, 0, -34)
expect(columnWrapper.vm.currentIndex).toBe(2)
slowVerticalDrag(columnWrapper, 0, 34)
expect(columnWrapper.vm.currentIndex).toBe(1)
// this will out of range
slowVerticalDrag(columnWrapper, 0, 100)
expect(columnWrapper.vm.currentIndex).toBe(0)
},
15000
)
test('click slot to change the current-value', () => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
visible: true,
columns: [
{
options: [1, 2, 3],
defaultIndex: 0,
},
],
},
})
const columnWrapper = wrapper.find(PickerColumn) as PickerColumnWrapper
const option1 = wrapper.findAll('.weui-picker__item').at(1)
option1.trigger('click')
expect(columnWrapper.vm.currentIndex).toBe(1)
})
test('divider pickerSlot', () => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
visible: true,
columns: [
{
divider: true,
},
],
},
})
const pickerColumnWrapper = wrapper.find(PickerColumn)
pickerColumnWrapper.setData({
currentIndex: 1,
})
// divider should not emit change event when currentIndex changed
expect(pickerColumnWrapper.emitted().change).toBeFalsy()
})
test('index should be adjust to a suitable value when it is exceeded ot disabled', () => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
visible: true,
columns: [
{
options: [
{
text: 1,
},
{
text: 2,
},
{
text: 3,
disabled: true,
},
],
defaultIndex: 0,
},
],
},
})
const pickerColumnWrapper = wrapper.find(PickerColumn) as PickerColumnWrapper
pickerColumnWrapper.vm.setIndex(4)
// divider should not emit change event when currentIndex changed
expect(pickerColumnWrapper.vm.currentIndex).toBe(1)
})
test('watch defaultIndex', () => {
const wrapper = mount(Picker, {
attachToDocument: true,
propsData: {
visible: true,
columns: [
{
options: [1, 2, 3],
defaultIndex: 0,
},
],
},
})
const pickerColumnWrapper = wrapper.find(PickerColumn) as PickerColumnWrapper
pickerColumnWrapper.setProps({
defaultIndex: 1,
})
expect(pickerColumnWrapper.vm.currentIndex).toBe(1)
})
test('test setValue method', () => {
const wrapper: PickerWrapper = mount(Picker, {
attachToDocument: true,
propsData: {
visible: true,
columns: [
{
options: [1, 2, 3],
defaultIndex: 0,
},
],
},
})
const pickerColumnWrapper = wrapper.find(PickerColumn) as PickerColumnWrapper
const spy = jest.spyOn(pickerColumnWrapper.vm, 'setIndex')
pickerColumnWrapper.vm.setValue(3)
expect(spy).toHaveBeenCalledWith(2)
})
}) | the_stack |
import { HttpClient, HttpEvent, HttpHeaders, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import * as Sentry from '@sentry/browser';
import { apiUrl } from '../../shared/config';
import { MailboxKey } from '../datatypes';
import { AdvancedSearchQueryParameters, Attachment, Folder, Mail, Mailbox, Unsubscribe } from '../models';
import { MailFolderType } from '../models/mail.model';
@Injectable({
providedIn: 'root',
})
export class MailService {
constructor(private http: HttpClient) {}
getMessages(payload: {
limit: number;
offset: number;
folder: MailFolderType;
read?: boolean;
seconds?: number;
search?: boolean;
}): Observable<any> {
payload.limit = payload.limit ? payload.limit : 20;
if (payload.search) {
return this.searchMessages(payload);
}
let url = `${apiUrl}emails/messages/?limit=${payload.limit}&offset=${payload.offset}`;
if (!payload.folder) {
payload.folder = MailFolderType.INBOX;
}
if (payload.folder === MailFolderType.STARRED) {
url = `${url}&starred=true`;
} else {
const folder = encodeURIComponent(payload.folder);
url = `${url}&folder=${folder}`;
}
if (payload.read === false || payload.read === true) {
url = `${url}&read=${payload.read}`;
}
if (payload.seconds) {
url = `${url}&seconds=${payload.seconds}`;
}
return this.http.get<Mail[]>(url);
}
searchMessages(payload: {
limit: number;
offset: number;
folder: MailFolderType;
read?: boolean;
seconds?: number;
searchData?: AdvancedSearchQueryParameters;
}): Observable<any> {
const { searchData, limit, offset } = payload;
let url = '';
if (searchData) {
let queryParameters = '';
if (searchData.q) {
queryParameters = `q=${searchData.q}`;
if (searchData.exact) {
queryParameters = `${queryParameters}&exact=${searchData.exact}`;
}
}
if (searchData.sender) {
queryParameters = queryParameters
? `${queryParameters}&sender=${searchData.sender}`
: `sender=${searchData.sender}`;
}
if (searchData.receiver) {
queryParameters = queryParameters
? `${queryParameters}&receiver=${searchData.receiver}`
: `receiver=${searchData.receiver}`;
}
if (searchData.start_date) {
queryParameters = queryParameters
? `${queryParameters}&start_date=${searchData.start_date}`
: `start_date=${searchData.start_date}`;
}
if (searchData.end_date) {
queryParameters = queryParameters
? `${queryParameters}&end_date=${searchData.end_date}`
: `end_date=${searchData.end_date}`;
}
if (searchData.size !== undefined) {
queryParameters = queryParameters ? `${queryParameters}&size=${searchData.size}` : `size=${searchData.size}`;
if (searchData.size_operator) {
queryParameters = `${queryParameters}&size_operator=${searchData.size_operator}`;
}
}
if (searchData.have_attachment) {
queryParameters = queryParameters
? `${queryParameters}&have_attachment=${searchData.have_attachment}`
: `have_attachment=${searchData.have_attachment}`;
}
if (searchData.folder) {
queryParameters = queryParameters
? `${queryParameters}&folder=${searchData.folder}`
: `folder=${searchData.folder}`;
}
if (queryParameters) {
queryParameters = `${queryParameters}&`;
}
url = `${apiUrl}search/messages/?${queryParameters}limit=${limit}&offset=${offset}`;
} else {
url = `${apiUrl}search/messages/?q=''`;
}
return this.http.get<Mail[]>(url);
}
getMessage(payload: { messageId: number; folder: string }): Observable<Mail> {
const url = `${apiUrl}emails/messages/?id__in=${payload.messageId}&folder=${payload.folder}`;
return this.http.get<Mail>(url).pipe(
map((data: any) => {
return data.results ? data.results[0] : null;
}),
);
}
getUnreadMailsCount(): Observable<any> {
return this.http.get<Mail>(`${apiUrl}emails/unread/`);
}
getCustomFolderMessageCount(): Observable<any> {
return this.http.get<Mail>(`${apiUrl}emails/customfolder-message-count/`);
}
getMailboxes(limit = 50, offset = 0): Observable<any> {
const url = `${apiUrl}emails/mailboxes/?limit=${limit}&offset=${offset}`;
return this.http.get<any>(url).pipe(
map(data => {
const newData = data.results.map((mailbox: any) => {
mailbox.customFolders = mailbox.custom_folders;
return mailbox;
});
return newData;
}),
);
}
getUsersPublicKeys(emails: Array<string>): Observable<any> {
const body = { emails };
return this.http.post<any>(`${apiUrl}emails/keys/`, body);
}
getSecureMessage(hash: string, secret: string): Observable<any> {
const url = `${apiUrl}emails/secure-message/${hash}/${secret}/`;
return this.http.get<any>(url);
}
getSecureMessageKeys(hash: string, secret: string): Observable<any> {
const url = `${apiUrl}emails/secure-message/${hash}/${secret}/keys/`;
return this.http.get<any>(url);
}
createFolder(folder: Folder): Observable<any> {
if (folder.id) {
return this.http.patch<any>(`${apiUrl}emails/custom-folder/${folder.id}/`, folder);
}
return this.http.post<any>(`${apiUrl}emails/custom-folder/`, folder);
}
updateFoldersOrder(data: any) {
return this.http.post<any>(`${apiUrl}emails/folder-order/`, data);
}
createMail(data: any): Observable<any[]> {
let url = `${apiUrl}emails/messages/`;
if (data.id) {
url = `${url}${data.id}/`;
return this.http.patch<any>(url, data);
}
return this.http.post<any>(url, data);
}
secureReply(hash: string, secret: string, data: any): Observable<any> {
const url = `${apiUrl}emails/secure-message/${hash}/${secret}/reply/`;
return this.http.post<any>(url, data);
}
markAsRead(ids: string, isMailRead: boolean, folder: string): Observable<any[]> {
if (ids === 'all') {
return this.http.patch<any>(`${apiUrl}emails/messages/?folder=${folder}`, { read: isMailRead });
}
return this.http.patch<any>(`${apiUrl}emails/messages/?id__in=${ids}`, { read: isMailRead });
}
markAsStarred(ids: string, isMailStarred: boolean, folder: string, withChildren: boolean): Observable<any[]> {
if (ids === 'all') {
return this.http.patch<any>(`${apiUrl}emails/messages/?folder=${folder}`, {
starred: isMailStarred,
with_children: withChildren,
});
}
return this.http.patch<any>(`${apiUrl}emails/messages/?id__in=${ids}`, {
starred: isMailStarred,
with_children: withChildren,
});
}
moveMail(
ids: string,
folder: string,
sourceFolder: string,
withChildren = true,
fromTrash = false,
): Observable<any[]> {
if (ids === 'all') {
return this.http.patch<any>(`${apiUrl}emails/messages/?folder=${sourceFolder}`, {
folder,
with_children: withChildren,
from_trash: fromTrash,
});
}
return this.http.patch<any>(`${apiUrl}emails/messages/?id__in=${ids}`, {
folder,
with_children: withChildren,
from_trash: fromTrash,
});
}
deleteMails(ids: string, folder: string, parent_only = false): Observable<any[]> {
if (ids === 'all') {
return this.http.delete<any>(`${apiUrl}emails/messages/?folder=${folder}&parent_only=${parent_only ? 1 : 0}`);
}
return this.http.delete<any>(`${apiUrl}emails/messages/?id__in=${ids}&parent_only=${parent_only ? 1 : 0}`);
}
deleteMailForAll(id: string): Observable<any[]> {
return this.http.post<any>(`${apiUrl}emails/delete-message/${id}/`, {});
}
deleteFolder(id: string): Observable<any[]> {
return this.http.delete<any>(`${apiUrl}emails/custom-folder/${id}/`);
}
uploadFile(attachment: Attachment): Observable<HttpEvent<any>> {
const formData = new FormData();
formData.append('document', attachment.document);
formData.append('message', attachment.message.toString());
formData.append('is_inline', attachment.is_inline.toString());
formData.append('is_encrypted', attachment.is_encrypted.toString());
formData.append('file_type', attachment.document.type.toString());
formData.append('name', attachment.name.toString());
formData.append('actual_size', attachment.actual_size.toString());
if (attachment.is_pgp_mime) {
formData.append('is_pgp_mime', attachment.is_pgp_mime.toString());
}
const request = attachment.id
? new HttpRequest('PATCH', `${apiUrl}emails/attachments/update/${attachment.id}/`, formData, {
reportProgress: true,
})
: new HttpRequest('POST', `${apiUrl}emails/attachments/create/`, formData, {
reportProgress: true,
});
return this.http.request(request);
}
deleteAttachment(attachment: Attachment): Observable<any> {
return this.http.delete<any>(`${apiUrl}emails/attachments/${attachment.id}/`);
}
getAttachment(attachment: Attachment): Observable<any> {
return this.http.get(`${apiUrl}emails/attachments/${attachment.id}/`);
}
getSecureMessageAttachment(attachment: Attachment, hash: string, randomSecret: string): Observable<any> {
return this.http.get(`${apiUrl}emails/secure-message/${hash}/${randomSecret}/attachment/${attachment.id}/`);
}
updateMailBoxSettings(data: Mailbox) {
return this.http.patch<any>(`${apiUrl}emails/mailboxes/${data.id}/`, data);
}
createMailbox(data: any) {
return this.http.post<any>(`${apiUrl}emails/mailboxes/`, data);
}
updateMailboxOrder(data: any) {
return this.http.post<any>(`${apiUrl}emails/mailbox-order/`, data);
}
deleteMailbox(id: number) {
return this.http.delete<any>(`${apiUrl}emails/mailboxes/${id}/`);
}
emptyFolder(data: any) {
return this.http.post<any>(`${apiUrl}emails/empty-folder/`, data);
}
fetchMailboxKeys() {
return this.http.get(`${apiUrl}emails/mailbox-keys/`);
}
addMailboxKeys(data: MailboxKey) {
return this.http.post(`${apiUrl}emails/mailbox-keys/`, data);
}
deleteMailboxKeys(data: MailboxKey) {
const options = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
}),
body: { password: data.password },
};
return this.http.delete<any>(`${apiUrl}emails/mailbox-keys/${data.id}/`, options);
}
setPrimaryMailboxKeys(data: MailboxKey) {
return this.http.post<any>(`${apiUrl}emails/mailboxes-change-primary/`, {
mailbox_id: data.mailbox,
mailboxkey_id: data.id,
});
}
unsubscribe(data: Unsubscribe): Observable<any> {
return this.http.post<any>(`${apiUrl}emails/list-unsubscribe/`, data);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
Sentry.captureException(error.originalError || error);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
} | the_stack |
import { printp } from "../../adapters/messages/pending-logs";
import { PromiseError, Component } from "./../../adapters/errors/promise-error";
import { ProcessCEMetadata } from "../../adapters/mongo-db/repo-models";
import {
DeploymentError,
DeploymentResult,
} from "../../adapters/ethereum-blockchain/structs/deployment-output";
import { AccountInfo } from "../../adapters/ethereum-blockchain/structs/account-info";
import { FunctionInfo } from "../../adapters/ethereum-blockchain/structs/function-info";
import {
CompilationResult,
CompilationOutput,
} from "../../adapters/ethereum-blockchain/structs/compilation-output";
import { CompilationInfo } from "../../adapters/ethereum-blockchain/structs/compilation-output";
import { ModelInfo } from "../utils/structs/compilation-info";
import { ContractInfo } from "../../adapters/ethereum-blockchain/structs/contract-info";
import * as ethereumAdapter from "../../adapters/ethereum-blockchain/ethereum-adapter";
import {
TypeMessage,
print,
printSeparator,
} from "../../adapters/messages/console-log";
import * as mongoDBAdapter from "../../adapters/mongo-db/mongo-db-adapter";
import { RepoType } from "../../adapters/mongo-db/repo-types";
let defaultAccount: AccountInfo;
// Step 1. Model Registration: Collects the compilation artifacts of the produced models,
// and saves all these metadata as an entry in the Process Repository.
export let registerProcessRepository = (
modelInfo: ModelInfo,
contracts: CompilationInfo
) => {
printp(2);
return new Promise<Array<any>>((resolve, reject) => {
// Sorting elements such that children are created first
let queue = [
{
nodeId: modelInfo.id,
nodeName: modelInfo.name,
bundleId: "",
nodeIndex: 0,
bundleParent: "",
factoryContract: "",
},
];
for (let i = 0; i < queue.length; i++) {
if (modelInfo.controlFlowInfoMap.has(queue[i].nodeId)) {
let cfInfo = modelInfo.controlFlowInfoMap.get(queue[i].nodeId);
let candidates = [
cfInfo.multiinstanceActivities,
cfInfo.nonInterruptingEvents,
cfInfo.callActivities,
];
candidates.forEach((children) => {
if (children) {
children.forEach((value, key) => {
queue.push({
nodeId: key,
nodeName: value,
bundleId: "",
nodeIndex: 0,
bundleParent: "",
factoryContract: "",
});
});
}
});
}
}
queue.reverse();
let nodeIndexes = new Map();
for (let i = 0; i < queue.length; i++) nodeIndexes.set(queue[i].nodeId, i);
saveProcessInRepository(queue, nodeIndexes, modelInfo, contracts)
.then((sortedElements) => {
resolve(sortedElements);
})
.catch((error) => {
reject(error);
});
});
};
export let registerParent2ChildrenRelation = async (
sortedElements: Array<any>,
modelInfo: ModelInfo,
runtimeRegistry: ContractInfo
): Promise<Array<any>> => {
printp(3);
try {
if (!defaultAccount)
defaultAccount = await ethereumAdapter.defaultDeployment();
for (let i = 0; i < sortedElements.length; i++) {
let executionRes = await ethereumAdapter.execContractFunctionSync(
runtimeRegistry.address,
runtimeRegistry.abi,
new FunctionInfo("addChildBundleId", ["bytes32", "bytes32", "uint256"]),
defaultAccount,
[
sortedElements[i].bundleParent,
sortedElements[i].bundleId,
sortedElements[i].nodeIndex,
]
);
if (executionRes instanceof DeploymentError) {
printTreeRelations(sortedElements[i], executionRes);
return Promise.reject([(executionRes as DeploymentError).error]);
} else printTreeRelations(sortedElements[i], executionRes);
}
let removedCallActivities: Array<any> = [];
sortedElements.forEach((element) => {
if (
modelInfo.controlFlowInfoMap.has(element.nodeId) ||
modelInfo.globalNodeMap.get(element.nodeId).$type === "bpmn:StartEvent"
) {
removedCallActivities.push(element);
}
});
printSeparator();
return removedCallActivities;
} catch (error) {
printTreeRelations(undefined, undefined, error);
return Promise.reject(error);
}
};
export let deployAndRegisterFactories = async (
sortedElements: Array<any>,
contracts: Array<CompilationOutput>,
runtimeRegistry: ContractInfo
): Promise<Array<any>> => {
printp(4);
return await deployAndRegisterContract(
"Factory",
sortedElements,
contracts,
runtimeRegistry
);
};
export let deployAndRegisterWorklists = async (
modelInfo: ModelInfo,
sortedElements: Array<any>,
contracts: Array<CompilationOutput>,
runtimeRegistry: ContractInfo
) => {
printp(5);
await deployAndRegisterContract(
"Worklist",
sortedElements,
contracts,
runtimeRegistry
);
let bundleId = "";
for (let i = 0; i < sortedElements.length; i++) {
if (sortedElements[i].nodeName === modelInfo.name) {
bundleId = sortedElements[i].bundleId;
break;
}
}
return bundleId;
};
export let retrieveProcessModelMetadata = async (
mHash: string
): Promise<ProcessCEMetadata> => {
let modelInfo = await mongoDBAdapter.findModelMetadataById(
RepoType.ProcessCompiledEngine,
mHash
);
if (modelInfo instanceof PromiseError) {
modelInfo.components.push(
new Component("deployment-mediator", "retrieveProcessModelMetadata")
);
return Promise.reject(modelInfo);
}
print(JSON.stringify(modelInfo as ProcessCEMetadata));
printSeparator();
return modelInfo as ProcessCEMetadata;
};
////////////////////////////////////////////////
//////////// PRIVATE FUNCTIONS /////////////
////////////////////////////////////////////////
let saveProcessInRepository = async (
sortedElements: Array<any>,
nodeIndexes: Map<string, number>,
modelInfo: ModelInfo,
contracts: CompilationInfo
): Promise<Array<any>> => {
for (let i = 0; i < sortedElements.length; i++) {
let nodeName = sortedElements[i].nodeName;
let gNodeId = sortedElements[i].nodeId;
let controlFlowInfo = modelInfo.controlFlowInfoMap.get(gNodeId);
if (modelInfo.globalNodeMap.get(gNodeId).$type === "bpmn:StartEvent")
controlFlowInfo = modelInfo.controlFlowInfoMap.get(
modelInfo.globalNodeMap.get(gNodeId).$parent.id
);
if (controlFlowInfo) {
let indexToFunctionName = [];
let childrenSubproc = [];
controlFlowInfo.nodeList.forEach((nodeId) => {
let element = modelInfo.globalNodeMap.get(nodeId);
if (controlFlowInfo.nodeList.indexOf(nodeId) >= 0) {
let type = "None";
let role = "None";
if (
controlFlowInfo.callActivities.has(nodeId) ||
controlFlowInfo.multiinstanceActivities.has(nodeId) ||
controlFlowInfo.nonInterruptingEvents.has(nodeId)
)
type = "Separate-Instance";
else if (element.$type === "bpmn:ServiceTask") type = "Service";
else if (
element.$type === "bpmn:UserTask" ||
element.$type === "bpmn:ReceiveTask" ||
controlFlowInfo.catchingMessages.indexOf(nodeId) >= 0
) {
type = "Workitem";
}
indexToFunctionName[controlFlowInfo.nodeIndexMap.get(nodeId)] = {
name: controlFlowInfo.nodeNameMap.get(nodeId),
id: nodeId,
type: type,
role: role,
};
if (
controlFlowInfo.callActivities.has(nodeId) ||
controlFlowInfo.multiinstanceActivities.has(nodeId) ||
controlFlowInfo.nonInterruptingEvents.has(nodeId)
) {
childrenSubproc.push(nodeId);
sortedElements[
nodeIndexes.get(nodeId)
].nodeIndex = controlFlowInfo.nodeIndexMap.get(nodeId);
if (controlFlowInfo.externalBundles.has(nodeId))
sortedElements[
nodeIndexes.get(nodeId)
].bundleId = controlFlowInfo.externalBundles.get(nodeId);
}
}
});
try {
let processRepoId = await mongoDBAdapter.updateRepository(
RepoType.ProcessCompiledEngine,
new ProcessCEMetadata(
"",
gNodeId,
nodeName,
i < sortedElements.length - 1 ? "empty" : modelInfo.bpmn,
indexToFunctionName,
getContractAbi(
`${nodeName}Worklist`,
contracts.compilationMetadata
),
new ContractInfo(
`${nodeName}Workflow`,
getContractAbi(
`${nodeName}Workflow`,
contracts.compilationMetadata
),
getContractBytecode(
`${nodeName}Workflow`,
contracts.compilationMetadata
),
modelInfo.solidity,
undefined
)
)
);
sortedElements[i].bundleId = processRepoId;
sortedElements[i].bundleParent = processRepoId;
childrenSubproc.forEach((childId) => {
sortedElements[nodeIndexes.get(childId)].bundleParent = processRepoId;
});
printRepoUpdates(`${nodeName}Workflow`, processRepoId);
} catch (error) {
printRepoUpdates(`${nodeName}Workflow`, undefined, error);
return Promise.reject(error);
}
}
}
return sortedElements;
};
let deployAndRegisterContract = async (
nameSuffix: string,
sortedElements: Array<any>,
contracts: Array<CompilationOutput>,
runtimeRegistry: ContractInfo
): Promise<Array<any>> => {
try {
if (!defaultAccount)
defaultAccount = await ethereumAdapter.defaultDeployment();
for (let i = 0; i < sortedElements.length; i++) {
let contractName = sortedElements[i].nodeName + nameSuffix;
let compilationInfo = getCompilationResults(contractName, contracts);
if (!compilationInfo) continue;
let contractDeployment = (await ethereumAdapter.deploySmartContractSync(
compilationInfo,
defaultAccount
)) as DeploymentResult;
printDeployment(`${nameSuffix} ${contractName}`, contractDeployment);
let executionResult = (await ethereumAdapter.execContractFunctionSync(
runtimeRegistry.address,
runtimeRegistry.abi,
new FunctionInfo("register" + nameSuffix, ["bytes32", "address"]),
defaultAccount,
[sortedElements[i].bundleId, contractDeployment.contractAddress]
)) as DeploymentResult;
printRegistryUpdates(`${nameSuffix} ${contractName}`, executionResult);
}
return sortedElements;
} catch (error) {
return Promise.reject(error);
}
};
let getCompilationResults = (
contractName: string,
contracts: Array<CompilationOutput>
): CompilationResult => {
let contract = contracts.find((contract) => {
return contract.contractName === contractName;
});
return contract ? (contract as CompilationResult) : undefined;
};
let getContractAbi = (
contractName: string,
contracts: Array<CompilationOutput>
) => {
let compilationResults = getCompilationResults(contractName, contracts);
return compilationResults ? compilationResults.abi : undefined;
};
let getContractBytecode = (
contractName: string,
contracts: Array<CompilationOutput>
) => {
let compilationResults = getCompilationResults(contractName, contracts);
return compilationResults ? compilationResults.bytecode : undefined;
};
let printRepoUpdates = (contractName: string, id: any, error?: any) => {
if (error) {
print(
`ERROR: Updating process repository with contract ${contractName}`,
TypeMessage.error
);
print(error.toString(), TypeMessage.error);
} else {
print(
`SUCCESS: Metadata of contract ${contractName} updated in process repository`,
TypeMessage.success
);
print(` ID: ${id}`, TypeMessage.info);
}
printSeparator();
};
let printDeployment = (
contractName: string,
contractDeployment: DeploymentResult
) => {
print(`SUCCESS: ${contractName} deployed`, TypeMessage.success);
print(` Address: ${contractDeployment.contractAddress})`, TypeMessage.info);
print(` Cost: ${contractDeployment.gasCost} gas units`, TypeMessage.info);
printSeparator();
};
let printRegistryUpdates = (
contractName: string,
executionResult: DeploymentResult
) => {
print(
`SUCCESS: Runtime registry updated with: ${contractName}`,
TypeMessage.success
);
print(` Cost: ${executionResult.gasCost} gas units`, TypeMessage.info);
printSeparator();
};
let printTreeRelations = (sortedElement: any, result: any, error?: any) => {
if (error) {
print(
"ERROR: Registering process hierarchical relations in runtime registry",
TypeMessage.error
);
print(error.toString(), TypeMessage.error);
printSeparator();
} else if (result instanceof DeploymentError) {
print(
`ERROR: registering Parent-Child Relation in Contract ${sortedElement.name}`,
TypeMessage.error
);
print((result as DeploymentError).error.toString(), TypeMessage.error);
printSeparator();
} else {
print(
`SUCCESS: Relation Parent(${sortedElement.bundleParent})-Child(${sortedElement.bundleId}) updated`,
TypeMessage.success
);
print(
` Cost: ${(result as DeploymentResult).gasCost} gas units`,
TypeMessage.info
);
}
}; | the_stack |
import { left, right, leftSeq, rightSeq } from "string-left-right";
interface Obj {
[key: string]: any;
}
function isStr(something: any): boolean {
return typeof something === "string";
}
const headsAndTails = {
CONFIGHEAD: "GENERATE-ATOMIC-CSS-CONFIG-STARTS",
CONFIGTAIL: "GENERATE-ATOMIC-CSS-CONFIG-ENDS",
CONTENTHEAD: "GENERATE-ATOMIC-CSS-CONTENT-STARTS",
CONTENTTAIL: "GENERATE-ATOMIC-CSS-CONTENT-ENDS",
};
const units = [
"px",
"em",
"%",
"rem",
"cm",
"mm",
"in",
"pt",
"pc",
"ex",
"ch",
"vw",
"vmin",
"vmax",
];
const { CONFIGHEAD, CONFIGTAIL, CONTENTHEAD, CONTENTTAIL } = headsAndTails;
const padLeftIfTheresOnTheLeft = [":"];
function extractConfig(
str: string
): [extractedConfig: string, rawContentAbove: string, rawContentBelow: string] {
console.log(
`045 util ███████████████████████████████████████ extractConfig() ███████████████████████████████████████`
);
let extractedConfig = str;
let rawContentAbove = "";
let rawContentBelow = "";
if (str.includes(CONFIGHEAD) && str.includes(CONFIGTAIL)) {
console.log(`052 config calc - case #2`);
if (
str.indexOf(CONFIGTAIL) !== -1 &&
str.indexOf(CONTENTHEAD) !== -1 &&
str.indexOf(CONFIGTAIL) > str.indexOf(CONTENTHEAD)
) {
throw new Error(
`generate-atomic-css: [THROW_ID_02] Config heads are after config tails!`
);
}
let sliceFrom = str.indexOf(CONFIGHEAD) + CONFIGHEAD.length;
let sliceTo = str.indexOf(CONFIGTAIL);
// if there are opening CSS comments, include them:
if (
str[right(str, sliceFrom) as number] === "*" &&
str[right(str, right(str, sliceFrom) as number) as number] === "/"
) {
sliceFrom = (right(str, right(str, sliceFrom) as number) as number) + 1;
}
// if there are closing CSS comments include them too:
if (
str[left(str, sliceTo) as number] === "*" &&
str[left(str, left(str, sliceTo) as number) as number] === "/"
) {
sliceTo = left(str, left(str, sliceTo) as number) as number;
}
extractedConfig = str.slice(sliceFrom, sliceTo).trim();
if (!isStr(extractedConfig) || !extractedConfig.trim().length) {
console.log(`082 util: return empty`);
return [extractedConfig, rawContentAbove, rawContentBelow];
}
console.log(
`086 util: ${`\u001b[${36}m${`extractedConfig.trim()`}\u001b[${39}m`} = "${extractedConfig.trim()}"`
);
} else if (
str.includes(CONFIGHEAD) &&
!str.includes(CONFIGTAIL) &&
str.includes(CONTENTHEAD)
) {
console.log(`093 config calc - case #3`);
if (str.indexOf(CONFIGHEAD) > str.indexOf(CONTENTHEAD)) {
throw new Error(
`generate-atomic-css: [THROW_ID_03] Config heads are after content heads!`
);
}
extractedConfig = str.slice(
str.indexOf(CONFIGHEAD) + CONFIGHEAD.length,
str.indexOf(CONTENTHEAD)
);
} else if (
!str.includes(CONFIGHEAD) &&
!str.includes(CONFIGTAIL) &&
(str.includes(CONTENTHEAD) || str.includes(CONTENTTAIL))
) {
// strange case where instead of config heads/tails we have content heads/tails
console.log(`109 config calc - case #4`);
extractedConfig = str;
// remove content head
if (extractedConfig.includes(CONTENTHEAD)) {
console.log(`114 CONTENTHEAD present`);
// if content heads are present, cut off right after the closing comment
// if such follows, or right after heads if not
if (left(str, extractedConfig.indexOf(CONTENTHEAD))) {
console.log(`118 - characters present on the left of contenthead`);
let sliceTo = extractedConfig.indexOf(CONTENTHEAD);
// if there are opening or closing comments, don't include those
if (leftSeq(str, sliceTo, "/", "*")) {
console.log(`122`);
sliceTo = (leftSeq(str, sliceTo, "/", "*") as Obj).leftmostChar;
}
rawContentAbove = sliceTo === 0 ? "" : str.slice(0, sliceTo);
console.log(
`127 ${`\u001b[${33}m${`rawContentAbove`}\u001b[${39}m`} = ${JSON.stringify(
rawContentAbove,
null,
4
)}; ${`\u001b[${33}m${`rawContentBelow`}\u001b[${39}m`} = ${JSON.stringify(
rawContentBelow,
null,
4
)}`
);
}
let sliceFrom = extractedConfig.indexOf(CONTENTHEAD) + CONTENTHEAD.length;
console.log(
`141 ${`\u001b[${33}m${`sliceFrom`}\u001b[${39}m`} = ${JSON.stringify(
sliceFrom,
null,
4
)}`
);
if (rightSeq(extractedConfig, sliceFrom - 1, "*", "/")) {
sliceFrom =
(rightSeq(extractedConfig, sliceFrom - 1, "*", "/") as Obj)
.rightmostChar + 1;
}
let sliceTo = null;
if (str.includes(CONTENTTAIL)) {
console.log(`155 content tail detected`);
sliceTo = str.indexOf(CONTENTTAIL);
console.log(
`158 ${`\u001b[${33}m${`sliceTo`}\u001b[${39}m`} = ${JSON.stringify(
sliceTo,
null,
4
)}`
);
// don't include comment on the left
if (
str[left(str, sliceTo) as number] === "*" &&
str[left(str, left(str, sliceTo) as number) as number] === "/"
) {
sliceTo = left(str, left(str, sliceTo));
console.log(
`171 ${`\u001b[${33}m${`sliceTo`}\u001b[${39}m`} = ${JSON.stringify(
sliceTo,
null,
4
)}`
);
}
// is there content afterwards?
let contentAfterStartsAt =
str.indexOf(CONTENTTAIL) + CONTENTTAIL.length;
console.log(
`183 ${`\u001b[${33}m${`contentAfterStartsAt`}\u001b[${39}m`} = ${JSON.stringify(
contentAfterStartsAt,
null,
4
)}; slice: "${str.slice(contentAfterStartsAt)}"`
);
if (
str[right(str, contentAfterStartsAt - 1) as number] === "*" &&
str[
right(str, right(str, contentAfterStartsAt - 1) as number) as number
] === "/"
) {
contentAfterStartsAt =
(right(
str,
right(str, contentAfterStartsAt - 1) as number
) as number) + 1;
console.log(
`201 ${`\u001b[${33}m${`contentAfterStartsAt`}\u001b[${39}m`} = ${JSON.stringify(
contentAfterStartsAt,
null,
4
)}; slice: "${str.slice(contentAfterStartsAt)}"`
);
// if there are non-whitespace characters, that's rawContentBelow
}
if (right(str, contentAfterStartsAt)) {
rawContentBelow = str.slice(contentAfterStartsAt);
}
}
if (sliceTo) {
extractedConfig = extractedConfig.slice(sliceFrom, sliceTo).trim();
} else {
extractedConfig = extractedConfig.slice(sliceFrom).trim();
}
console.log(
`221 ${`\u001b[${33}m${`extractedConfig`}\u001b[${39}m`} = ${JSON.stringify(
extractedConfig,
null,
4
)}`
);
}
// remove content tail
else if (extractedConfig.includes(CONTENTTAIL)) {
console.log(`231 CONTENTTAIL present`);
const contentInFront: string[] = [];
let stopFilteringAndPassAllLines = false;
extractedConfig = extractedConfig
.split("\n")
.filter((rowStr) => {
if (!rowStr.includes("$$$") && !stopFilteringAndPassAllLines) {
if (!stopFilteringAndPassAllLines) {
contentInFront.push(rowStr);
}
return false;
}
// ... so the row contains $$$
if (!stopFilteringAndPassAllLines) {
stopFilteringAndPassAllLines = true;
return true;
}
return true;
})
.join("\n");
let sliceTo = extractedConfig.indexOf(CONTENTTAIL);
if (leftSeq(extractedConfig, sliceTo, "/", "*")) {
sliceTo = (leftSeq(extractedConfig, sliceTo, "/", "*") as Obj)
.leftmostChar;
}
extractedConfig = extractedConfig.slice(0, sliceTo).trim();
if (contentInFront.length) {
rawContentAbove = `${contentInFront.join("\n")}\n`;
}
// retrieve the content after content tails
let contentAfterStartsAt;
if (right(str, str.indexOf(CONTENTTAIL) + CONTENTTAIL.length)) {
console.log(`268 content after CONTENTTAIL detected`);
contentAfterStartsAt = str.indexOf(CONTENTTAIL) + CONTENTTAIL.length;
if (
str[right(str, contentAfterStartsAt) as number] === "*" &&
str[
right(str, right(str, contentAfterStartsAt) as number) as number
] === "/"
) {
contentAfterStartsAt =
(right(str, right(str, contentAfterStartsAt) as number) as number) +
1;
if (right(str, contentAfterStartsAt)) {
rawContentBelow = str.slice(contentAfterStartsAt);
}
}
}
}
console.log(
`287 ${`\u001b[${33}m${`rawContentAbove`}\u001b[${39}m`} = ${JSON.stringify(
rawContentAbove,
null,
4
)}; ${`\u001b[${33}m${`rawContentBelow`}\u001b[${39}m`} = ${JSON.stringify(
rawContentBelow,
null,
4
)}`
);
console.log(
`299 ${`\u001b[${33}m${`extractedConfig`}\u001b[${39}m`} = ${JSON.stringify(
extractedConfig,
null,
4
)}`
);
} else {
console.log(`306 config calc - case #5`);
const contentHeadsRegex = new RegExp(
`(\\/\\s*\\*\\s*)*${CONTENTHEAD}(\\s*\\*\\s*\\/)*`
);
const contentTailsRegex = new RegExp(
`(\\/\\s*\\*\\s*)*${CONTENTTAIL}(\\s*\\*\\s*\\/)*`
);
let stopFiltering = false;
const gatheredLinesAboveTopmostConfigLine: string[] = [];
const gatheredLinesBelowLastConfigLine: string[] = [];
// remove all lines above the first line which contains $$$
const configLines: string[] = str.split("\n").filter((rowStr) => {
if (stopFiltering) {
return true;
}
if (
!rowStr.includes("$$$") &&
!rowStr.includes("{") &&
!rowStr.includes(":")
) {
gatheredLinesAboveTopmostConfigLine.push(rowStr);
return false;
}
// but if it does contain $$$...
stopFiltering = true;
return true;
});
// now we need to separate any rows in the end that don't contain $$$
for (let i = configLines.length; i--; ) {
if (
!configLines[i].includes("$$$") &&
!configLines[i].includes("}") &&
!configLines[i].includes(":")
) {
gatheredLinesBelowLastConfigLine.unshift(configLines.pop() as string);
} else {
break;
}
}
extractedConfig = configLines
.join("\n")
.replace(contentHeadsRegex, "")
.replace(contentTailsRegex, "");
if (gatheredLinesAboveTopmostConfigLine.length) {
rawContentAbove = `${gatheredLinesAboveTopmostConfigLine.join("\n")}\n`;
}
if (gatheredLinesBelowLastConfigLine.length) {
rawContentBelow = `\n${gatheredLinesBelowLastConfigLine.join("\n")}`;
}
}
console.log(
`364 util ███████████████████████████████████████ extractConfig() ends ███████████████████████████████████████`
);
return [extractedConfig, rawContentAbove, rawContentBelow];
}
function trimBlankLinesFromLinesArray(lineArr: string[], trim = true) {
// killswitch is activated, do nothing
if (!trim) {
return lineArr;
}
const copyArr = Array.from(lineArr);
if (copyArr.length && isStr(copyArr[0]) && !copyArr[0].trim().length) {
do {
copyArr.shift();
} while (isStr(copyArr[0]) && !copyArr[0].trim().length);
}
if (
copyArr.length &&
isStr(copyArr[copyArr.length - 1]) &&
!copyArr[copyArr.length - 1].trim().length
) {
do {
copyArr.pop();
} while (
copyArr &&
copyArr[copyArr.length - 1] &&
!copyArr[copyArr.length - 1].trim().length
);
}
return copyArr;
}
// takes string for example, .mt$$$ { margin-top: $$$px; }|3
// and extracts the parts after the pipe
// also, we use it for simpler format sources that come from wizard on the
// webapp, format .mt|0|500 - same business, extract digits between pipes
function extractFromToSource(
str: string,
fromDefault = 0,
toDefault = 500
): [from: number, to: number, source: string] {
let from = fromDefault;
let to = toDefault;
let source = str;
let tempArr;
if (
str.lastIndexOf("}") > 0 &&
str.slice(str.lastIndexOf("}") + 1).includes("|")
) {
console.log(`414 util: closing curlie detected`);
tempArr = str
.slice(str.lastIndexOf("}") + 1)
.split("|")
.filter((val) => val.trim().length)
.map((val) => val.trim())
.filter((val) =>
String(val)
.split("")
.every((char) => /\d/g.test(char))
);
} else if (str.includes("|")) {
console.log(`426 util: else case with pipes`);
tempArr = str
.split("|")
.filter((val) => val.trim().length)
.map((val) => val.trim())
.filter((val) =>
String(val)
.split("")
.every((char) => /\d/g.test(char))
);
}
console.log(
`439 util: ${`\u001b[${33}m${`tempArr`}\u001b[${39}m`} = ${JSON.stringify(
tempArr,
null,
4
)}`
);
if (Array.isArray(tempArr)) {
if (tempArr.length === 1) {
to = Number.parseInt(tempArr[0], 10);
} else if (tempArr.length > 1) {
from = Number.parseInt(tempArr[0], 10);
to = Number.parseInt(tempArr[1], 10);
}
}
console.log(`454 from=${from}; to=${to}`);
// extract the source string - it's everything from zero to first pipe
// that follows the last closing curly brace
if (
str.lastIndexOf("}") > 0 &&
str.slice(str.lastIndexOf("}") + 1).includes("|")
) {
source = str.slice(0, str.indexOf("|", str.lastIndexOf("}") + 1)).trimEnd();
if (source.trim().startsWith("|")) {
console.log(`464 util: crop leading pipe`);
while (source.trim().startsWith("|")) {
source = source.trim().slice(1);
}
}
} else {
console.log(`470 ${`\u001b[${36}m${`loop`}\u001b[${39}m`}`);
let lastPipeWasAt = null;
let firstNonPipeNonWhitespaceCharMet = false;
let startFrom = 0;
let endTo = str.length;
// null is fresh state, true is met, false is pattern of only digits was broken
let onlyDigitsAndWhitespaceBeenMet = null;
for (let i = 0, len = str.length; i < len; i++) {
console.log(
`481 ${`\u001b[${36}m${`------ ${`str[${i}] = ${`\u001b[${35}m${
str[i]
}\u001b[${39}m`}`} ------`}\u001b[${39}m`}`
);
// first "cell" between pipes which contains only digits terminates the
// loop; its opening pipe is "endTo", we slice up to it
if ("0123456789".includes(str[i])) {
// if it's digit...
if (onlyDigitsAndWhitespaceBeenMet === null && str[i].trim().length) {
onlyDigitsAndWhitespaceBeenMet = true;
console.log(`493 SET onlyDigitsAndWhitespaceBeenMet = true`);
}
}
// if not digit...
else if (str[i] !== "|" && str[i].trim().length) {
onlyDigitsAndWhitespaceBeenMet = false;
console.log(`499 SET onlyDigitsAndWhitespaceBeenMet = false`);
}
// catch the last character
if (!str[i + 1] && onlyDigitsAndWhitespaceBeenMet && lastPipeWasAt) {
endTo = lastPipeWasAt;
console.log(
`506 SET ${`\u001b[${33}m${`endTo`}\u001b[${39}m`} = ${endTo}`
);
}
// catch pipe
if (str[i] === "|") {
console.log(`512 ${`\u001b[${33}m${`pipe caught`}\u001b[${39}m`}`);
if (onlyDigitsAndWhitespaceBeenMet && lastPipeWasAt) {
endTo = lastPipeWasAt;
console.log(
`516 set endTo = ${endTo}; ${`\u001b[${31}m${`BREAK`}\u001b[${39}m`}`
);
break;
}
lastPipeWasAt = i;
console.log(`522 SET lastPipeWasAt = ${lastPipeWasAt}`);
// reset:
onlyDigitsAndWhitespaceBeenMet = null;
console.log(`526 SET onlyDigitsAndWhitespaceBeenMet = null`);
} else if (!firstNonPipeNonWhitespaceCharMet && str[i].trim().length) {
firstNonPipeNonWhitespaceCharMet = true;
if (lastPipeWasAt !== null) {
startFrom = lastPipeWasAt + 1;
console.log(
`532 SET ${`\u001b[${33}m${`startFrom`}\u001b[${39}m`} = ${startFrom}`
);
}
console.log(
`536 SET ${`\u001b[${33}m${`firstNonPipeNonWhitespaceCharMet`}\u001b[${39}m`} = ${firstNonPipeNonWhitespaceCharMet};`
);
}
console.log(
`541 ${`\u001b[${90}m${` ENDING
startFrom = ${startFrom}
endTo = ${endTo}
onlyDigitsAndWhitespaceBeenMet = ${onlyDigitsAndWhitespaceBeenMet}
lastPipeWasAt = ${lastPipeWasAt}
`}\u001b[${39}m`}`
);
}
console.log(`549 startFrom = ${startFrom}; endTo = ${endTo}`);
source = str.slice(startFrom, endTo).trimEnd();
console.log(
`552 FINAL ${`\u001b[${33}m${`source`}\u001b[${39}m`} = ${source}`
);
}
return [from, to, source];
}
function prepLine(
str: string,
progressFn: null | ((percDone: number) => void),
subsetFrom: number,
subsetTo: number,
generatedCount: Obj,
pad: boolean
) {
//
//
//
// PART I. Extract from, to and source values
//
//
//
let currentPercentageDone;
let lastPercentage = 0;
console.log(`\n\n\n\n\n`);
console.log(`578 util: ${`\u001b[${36}m${`===========`}\u001b[${39}m`}`);
console.log(
`580 util: prepLine(): str: "${`\u001b[${35}m${str}\u001b[${39}m`}";\n${`\u001b[${35}m${`generatedCount`}\u001b[${39}m`} = ${JSON.stringify(
generatedCount,
null,
0
)}`
);
// we need to extract the "from" and to "values"
// the separator is vertical pipe, which is a legit CSS selector
const [from, to, source] = extractFromToSource(str, 0, 500);
console.log(
`593 ${`\u001b[${33}m${`from`}\u001b[${39}m`} = ${from}\n${`\u001b[${33}m${`to`}\u001b[${39}m`} = ${to}\n${`\u001b[${33}m${`source`}\u001b[${39}m`} = "${source}"\n`
);
//
//
//
// PART II. extract dollar-dollar-dollar positions and types
//
//
//
const subsetRange = subsetTo - subsetFrom;
let res = "";
// traverse
for (let i = from; i <= to; i++) {
let debtPaddingLen = 0;
console.log("\n");
console.log(
`612 ███████████████████████████████████████ row i=${i} ███████████████████████████████████████\n`
);
// if (pad) {
let startPoint = 0;
for (let y = 0, len = source.length; y < len; y++) {
const charcode = source[y].charCodeAt(0);
console.log(
`\u001b[${36}m${`===============================`}\u001b[${39}m \u001b[${35}m${`source[ ${y} ] = ${
source[y].trim().length
? source[y]
: JSON.stringify(source[y], null, 0)
}`}\u001b[${39}m ${`\u001b[${90}m#${charcode}\u001b[${39}m`} \u001b[${36}m${`===============================`}\u001b[${39}m`
);
// catch third dollar of three dollars in a row
// -----------------------------------------------------------------------
if (source[y] === "$" && source[y - 1] === "$" && source[y - 2] === "$") {
console.log(
`630 ${`\u001b[${33}m${`startPoint`}\u001b[${39}m`} = ${JSON.stringify(
startPoint,
null,
4
)}`
);
console.log(`636 $$$ caught`);
// submit all the content up until now
const restOfStr = source.slice(y + 1);
console.log(
`640 ${`\u001b[${33}m${`restOfStr`}\u001b[${39}m`} = ${JSON.stringify(
restOfStr,
null,
4
)}`
);
let unitFound = "";
console.log(`648`);
if (
i === 0 &&
// eslint-disable-next-line consistent-return, array-callback-return
units.some((unit) => {
if (restOfStr.startsWith(unit)) {
unitFound = unit;
return true;
}
}) &&
(source[right(source, y + unitFound.length) as number] === "{" ||
!source[y + unitFound.length + 1].trim().length)
) {
console.log(`661 push: "${source.slice(startPoint, y - 2)}"`);
console.log(
`663 push also: "${
pad
? String(i).padStart(
String(to).length - String(i).length + unitFound.length + 1
)
: i
}"`
);
res += `${source.slice(startPoint, y - 2)}${
pad
? String(i).padStart(
String(to).length - String(i).length + unitFound.length + 1
)
: i
}`;
console.log(`678 ${`\u001b[${32}m${`res = "${res}"`}\u001b[${39}m`}`);
startPoint = y + 1 + (unitFound ? unitFound.length : 0);
} else {
// extract units if any follow the $$$
let unitThatFollow = "";
console.log(`683`);
// eslint-disable-next-line consistent-return, array-callback-return
units.some((unit) => {
if (source.startsWith(unit, y + 1)) {
unitThatFollow = unit;
console.log(`688 return true`);
return true;
}
});
console.log(
`693 extracted ${`\u001b[${33}m${`unitThatFollow`}\u001b[${39}m`} = ${JSON.stringify(
unitThatFollow,
null,
4
)}`
);
if (
!source[y - 3].trim().length ||
// eslint-disable-next-line
padLeftIfTheresOnTheLeft.some((val) =>
source
.slice(startPoint, y - 2)
.trim()
.endsWith(val)
)
) {
// if left-side padding can be possible:
console.log(
`712 source.slice(startPoint, y - 2) = "${source.slice(
startPoint,
y - 2
)}"`
);
console.log(
`718 push ${`${source.slice(startPoint, y - 2)}${
pad
? String(i).padStart(
String(to).length +
(i === 0 && unitThatFollow ? unitThatFollow.length : 0)
)
: i
}`}`
);
// if the chunk we're adding starts with unit, we need to remove it
// if it's zero'th row
let temp = 0;
if (i === 0) {
// eslint-disable-next-line no-loop-func
units.some((unit) => {
if (`${source.slice(startPoint, y - 2)}`.startsWith(unit)) {
temp = unit.length;
}
return true;
});
}
res += `${source.slice(startPoint + temp, y - 2)}${
pad
? String(i).padStart(
String(to).length +
(i === 0 && unitThatFollow ? unitThatFollow.length : 0)
)
: i
}`;
console.log(
`749 ${`\u001b[${32}m${`res = "${res}"`}\u001b[${39}m`}`
);
} else if (
!source[y + 1].trim().length ||
source[right(source, y) as number] === "{"
) {
console.log(
`756 push ${`${source.slice(startPoint, y - 2)}${
pad
? String(i).padEnd(
String(to).length +
(i === 0 && unitThatFollow
? (unitThatFollow as any).length
: 0)
)
: i
}`}`
);
// if right-side padding can be possible:
res += `${source.slice(startPoint, y - 2)}${
pad
? String(i).padEnd(
String(to).length +
(i === 0 && unitThatFollow
? (unitThatFollow as any).length
: 0)
)
: i
}`;
console.log(
`779 ${`\u001b[${32}m${`res = "${res}"`}\u001b[${39}m`}`
);
} else {
console.log(`782 push ${`${source.slice(startPoint, y - 2)}${i}`}`);
res += `${source.slice(startPoint, y - 2)}${i}`;
console.log(
`785 ${`\u001b[${32}m${`res = "${res}"`}\u001b[${39}m`}`
);
// also, make a note of padding which we'll need to do later,
// in front of the next opening curlie.
// for example, range is 0-10, so 2 digit padding, and we have
// .pt0px[lang|=en]
// this zero above needs to be padded at the next available location
// that is before opening curlie.
//
if (pad) {
debtPaddingLen = String(to).length - String(i).length;
console.log(
`799 ${`\u001b[${32}m${`██`}\u001b[${39}m`} ${`\u001b[${33}m${`debtPaddingLen`}\u001b[${39}m`} = ${JSON.stringify(
debtPaddingLen,
null,
4
)}`
);
}
}
startPoint = y + 1;
}
}
// catch opening curlie
// -----------------------------------------------------------------------
if (source[y] === "{" && pad) {
console.log(`814 opening curlie caught`);
if (debtPaddingLen) {
res += `${source.slice(startPoint, y)}${` `.repeat(debtPaddingLen)}`;
startPoint = y;
debtPaddingLen = 0;
console.log(
`820 SET startPoint = ${startPoint}; debtPaddingLen = ${debtPaddingLen}`
);
}
}
// catch the last character of a line
if (!source[y + 1]) {
console.log(`827 last character on a line!`);
console.log(
`829 ${`\u001b[${33}m${`startPoint`}\u001b[${39}m`} = ${JSON.stringify(
startPoint,
null,
4
)}`
);
let unitFound = "";
const restOfStr = source.slice(startPoint);
console.log(
`838 restOfStr = "${restOfStr}" --- we'll check, does it start with any elements from units`
);
if (
i === 0 &&
// eslint-disable-next-line
units.some((unit) => {
if (restOfStr.startsWith(unit)) {
unitFound = unit;
return true;
}
})
) {
console.log(
`851 push "${source.slice(startPoint + unitFound.length)}"`
);
res += `${source.slice(startPoint + unitFound.length)}`;
console.log(`854 ${`\u001b[${32}m${`res = "${res}"`}\u001b[${39}m`}`);
} else {
console.log(`856 last char - submit "${source.slice(startPoint)}"`);
res += `${source.slice(startPoint)}`;
console.log(`858 ${`\u001b[${32}m${`res = "${res}"`}\u001b[${39}m`}`);
}
// add line break
res += `${i !== to ? "\n" : ""}`;
console.log(
`863 add line break ${`\u001b[${32}m${`res = "${res}"`}\u001b[${39}m`}`
);
}
}
// eslint-disable-next-line no-param-reassign
generatedCount.count += 1;
if (typeof progressFn === "function") {
currentPercentageDone = Math.floor(
subsetFrom + (i / (to - from)) * subsetRange
);
if (currentPercentageDone !== lastPercentage) {
lastPercentage = currentPercentageDone;
progressFn(currentPercentageDone);
}
}
}
return res;
}
function bump(str: string, thingToBump: Obj) {
if (/\.\w/g.test(str)) {
// eslint-disable-next-line no-param-reassign
thingToBump.count += 1;
}
return str;
}
function prepConfig(
str: string,
progressFn: null | ((percDone: number) => void),
progressFrom: number,
progressTo: number,
trim = true,
generatedCount: Obj,
pad: boolean
) {
// all rows will report the progress from progressFrom to progressTo.
// For example, defaults 0 to 100.
// If there are for example 5 rows, each row will iterate through
// (100-0)/5 = 20 percent range. This means, progress bar will be jumpy:
// it will pass rows without $$$ quick but ones with $$$ slow and granular.
return trimBlankLinesFromLinesArray(
str
.split(/\r?\n/)
.map((rowStr, i, arr) =>
rowStr.includes("$$$")
? prepLine(
rowStr,
progressFn,
progressFrom + ((progressTo - progressFrom) / arr.length) * i,
progressFrom +
((progressTo - progressFrom) / arr.length) * (i + 1),
generatedCount,
pad
)
: bump(rowStr, generatedCount)
),
trim
).join("\n");
}
export {
Obj,
prepLine,
prepConfig,
isStr,
extractFromToSource,
extractConfig,
headsAndTails,
}; | the_stack |
import { isBoolean, isDate, isDefined, isFunction, isNumber, isObject, isString } from "../typeChecks";
import { Attr, type } from "./attrs";
import { CSSInJSRule, margin, styles } from "./css";
export interface ErsatzElement {
element: HTMLElement;
}
export function isErsatzElement(obj: any): obj is ErsatzElement {
return isObject(obj)
&& "element" in obj
&& (obj as any).element instanceof Node;
}
export interface ErsatzElements {
elements: HTMLElement[];
}
export function isErsatzElements(obj: any): obj is ErsatzElements {
return isObject(obj)
&& "elements" in obj
&& (obj as any).elements instanceof Array;
}
export type Elements = HTMLElement | ErsatzElement;
export interface IElementAppliable {
applyToElement(x: Elements): void;
}
export function isIElementAppliable(obj: any): obj is IElementAppliable {
return isObject(obj)
&& "applyToElement" in obj
&& isFunction((obj as any).applyToElement);
}
export type ElementChild = Node
| Elements
| ErsatzElements
| IElementAppliable
| string
| number
| boolean
| Date;
export function isElementChild(obj: any): obj is ElementChild {
return obj instanceof Node
|| isErsatzElement(obj)
|| isErsatzElements(obj)
|| isIElementAppliable(obj)
|| isString(obj)
|| isNumber(obj)
|| isBoolean(obj)
|| isDate(obj);
}
export interface IFocusable {
focus(): void;
}
export function isFocusable(elem: any): elem is IFocusable {
return "focus" in elem && isFunction((elem as IFocusable).focus);
}
export function elementSetDisplay(elem: Elements, visible: boolean, visibleDisplayType: string = "block"): void {
if (isErsatzElement(elem)) {
elem = elem.element;
}
elem.style.display = visible ? visibleDisplayType : "none";
}
export function elementIsDisplayed(elem: Elements): boolean {
if (isErsatzElement(elem)) {
elem = elem.element;
}
return elem.style.display !== "none";
}
export function elementToggleDisplay(elem: Elements, visibleDisplayType: string = "block"): void {
elementSetDisplay(elem, !elementIsDisplayed(elem), visibleDisplayType);
}
export function elementApply(elem: Elements, ...children: ElementChild[]) {
if (isErsatzElement(elem)) {
elem = elem.element;
}
for (let child of children) {
if (isDefined(child)) {
if (child instanceof Node) {
elem.append(child);
}
else if (isErsatzElement(child)) {
elem.append(child.element);
}
else if (isErsatzElements(child)) {
elem.append(...child.elements);
}
else if (isIElementAppliable(child)) {
child.applyToElement(elem);
}
else {
elem.append(document.createTextNode(child.toLocaleString()));
}
}
}
}
export function getElement<T extends HTMLElement>(selector: string): T {
return document.querySelector<T>(selector);
}
export function getButton(selector: string) {
return getElement<HTMLButtonElement>(selector);
}
export function getInput(selector: string) {
return getElement<HTMLInputElement>(selector);
}
export function getSelect(selector: string) {
return getElement<HTMLSelectElement>(selector);
}
export function getCanvas(selector: string) {
return getElement<HTMLCanvasElement>(selector);
}
/**
* Creates an HTML element for a given tag name.
*
* Boolean attributes that you want to default to true can be passed
* as just the attribute creating function,
* e.g. `Audio(autoPlay)` vs `Audio(autoPlay(true))`
* @param name - the name of the tag
* @param rest - optional attributes, child elements, and text
* @returns
*/
export function tag<T extends HTMLElement>(name: string, ...rest: ElementChild[]): T {
let elem: T = null;
for (const attr of rest) {
if (attr instanceof Attr && attr.key === "id") {
elem = document.getElementById(attr.value) as T;
break;
}
}
if (elem == null) {
elem = document.createElement(name) as T;
}
elementApply(elem, ...rest);
return elem;
}
export interface IDisableable {
disabled: boolean;
}
export function isDisableable(obj: any): obj is IDisableable {
return "disabled" in obj
&& typeof obj.disabled === "boolean";
}
/**
* Empty an element of all children. This is faster than setting `innerHTML = ""`.
*/
export function elementClearChildren(elem: Elements) {
if (isErsatzElement(elem)) {
elem = elem.element;
}
while (elem.lastChild) {
elem.lastChild.remove();
}
}
export function elementSetText(elem: Elements, text: string) {
if (isErsatzElement(elem)) {
elem = elem.element;
}
elementClearChildren(elem);
elem.appendChild(TextNode(text));
}
export type HTMLAudioElementWithSinkID = HTMLAudioElement & {
sinkId: string;
setSinkId(id: string): Promise<void>;
};
export function A(...rest: ElementChild[]): HTMLAnchorElement { return tag("a", ...rest); }
export function Abbr(...rest: ElementChild[]): HTMLElement { return tag("abbr", ...rest); }
export function Address(...rest: ElementChild[]): HTMLElement { return tag("address", ...rest); }
export function Area(...rest: ElementChild[]): HTMLAreaElement { return tag("area", ...rest); }
export function Article(...rest: ElementChild[]): HTMLElement { return tag("article", ...rest); }
export function Aside(...rest: ElementChild[]): HTMLElement { return tag("aside", ...rest); }
export function Audio(...rest: ElementChild[]): HTMLAudioElementWithSinkID { return tag("audio", ...rest); }
export function B(...rest: ElementChild[]): HTMLElement { return tag("b", ...rest); }
export function Base(...rest: ElementChild[]): HTMLBaseElement { return tag("base", ...rest); }
export function BDI(...rest: ElementChild[]): HTMLElement { return tag("bdi", ...rest); }
export function BDO(...rest: ElementChild[]): HTMLElement { return tag("bdo", ...rest); }
export function BlockQuote(...rest: ElementChild[]): HTMLQuoteElement { return tag("blockquote", ...rest); }
export function Body(...rest: ElementChild[]): HTMLBodyElement { return tag("body", ...rest); }
export function BR(): HTMLBRElement { return tag("br"); }
export function ButtonRaw(...rest: ElementChild[]): HTMLButtonElement { return tag("button", ...rest); }
export function Button(...rest: ElementChild[]): HTMLButtonElement { return ButtonRaw(...rest, type("button")); }
export function ButtonSubmit(...rest: ElementChild[]): HTMLButtonElement { return ButtonRaw(...rest, type("submit")); }
export function ButtonReset(...rest: ElementChild[]): HTMLButtonElement { return ButtonRaw(...rest, type("reset")); }
export function Canvas(...rest: ElementChild[]): HTMLCanvasElement { return tag("canvas", ...rest); }
export function Caption(...rest: ElementChild[]): HTMLTableCaptionElement { return tag("caption", ...rest); }
export function Cite(...rest: ElementChild[]): HTMLElement { return tag("cite", ...rest); }
export function Code(...rest: ElementChild[]): HTMLElement { return tag("code", ...rest); }
export function Col(...rest: ElementChild[]): HTMLTableColElement { return tag("col", ...rest); }
export function ColGroup(...rest: ElementChild[]): HTMLTableColElement { return tag("colgroup", ...rest); }
export function Data(...rest: ElementChild[]): HTMLDataElement { return tag("data", ...rest); }
export function DataList(...rest: ElementChild[]): HTMLDataListElement { return tag("datalist", ...rest); }
export function DD(...rest: ElementChild[]): HTMLElement { return tag("dd", ...rest); }
export function Del(...rest: ElementChild[]): HTMLModElement { return tag("del", ...rest); }
export function Details(...rest: ElementChild[]): HTMLDetailsElement { return tag("details", ...rest); }
export function DFN(...rest: ElementChild[]): HTMLElement { return tag("dfn", ...rest); }
export function Dialog(...rest: ElementChild[]): HTMLDialogElement { return tag("dialog", ...rest); }
export function Dir(...rest: ElementChild[]): HTMLDirectoryElement { return tag("dir", ...rest); }
export function Div(...rest: ElementChild[]): HTMLDivElement { return tag("div", ...rest); }
export function DL(...rest: ElementChild[]): HTMLDListElement { return tag("dl", ...rest); }
export function DT(...rest: ElementChild[]): HTMLElement { return tag("dt", ...rest); }
export function Em(...rest: ElementChild[]): HTMLElement { return tag("em", ...rest); }
export function Embed(...rest: ElementChild[]): HTMLEmbedElement { return tag("embed", ...rest); }
export function FieldSet(...rest: ElementChild[]): HTMLFieldSetElement { return tag("fieldset", ...rest); }
export function FigCaption(...rest: ElementChild[]): HTMLElement { return tag("figcaption", ...rest); }
export function Figure(...rest: ElementChild[]): HTMLElement { return tag("figure", ...rest); }
export function Footer(...rest: ElementChild[]): HTMLElement { return tag("footer", ...rest); }
export function Form(...rest: ElementChild[]): HTMLFormElement { return tag("form", ...rest); }
export function H1(...rest: ElementChild[]): HTMLHeadingElement { return tag("h1", ...rest); }
export function H2(...rest: ElementChild[]): HTMLHeadingElement { return tag("h2", ...rest); }
export function H3(...rest: ElementChild[]): HTMLHeadingElement { return tag("h3", ...rest); }
export function H4(...rest: ElementChild[]): HTMLHeadingElement { return tag("h4", ...rest); }
export function H5(...rest: ElementChild[]): HTMLHeadingElement { return tag("h5", ...rest); }
export function H6(...rest: ElementChild[]): HTMLHeadingElement { return tag("h6", ...rest); }
export function HR(...rest: ElementChild[]): HTMLHRElement { return tag("hr", ...rest); }
export function Head(...rest: ElementChild[]): HTMLHeadElement { return tag("head", ...rest); }
export function Header(...rest: ElementChild[]): HTMLElement { return tag("header", ...rest); }
export function HGroup(...rest: ElementChild[]): HTMLElement { return tag("hgroup", ...rest); }
export function HTML(...rest: ElementChild[]): HTMLHtmlElement { return tag("html", ...rest); }
export function I(...rest: ElementChild[]): HTMLElement { return tag("i", ...rest); }
export function IFrame(...rest: ElementChild[]): HTMLIFrameElement { return tag("iframe", ...rest); }
export function Img(...rest: ElementChild[]): HTMLImageElement { return tag("img", ...rest); }
export function Input(...rest: ElementChild[]): HTMLInputElement { return tag("input", ...rest); }
export function Ins(...rest: ElementChild[]): HTMLModElement { return tag("ins", ...rest); }
export function KBD(...rest: ElementChild[]): HTMLElement { return tag("kbd", ...rest); }
export function Label(...rest: ElementChild[]): HTMLLabelElement { return tag("label", ...rest); }
export function Legend(...rest: ElementChild[]): HTMLLegendElement { return tag("legend", ...rest); }
export function LI(...rest: ElementChild[]): HTMLLIElement { return tag("li", ...rest); }
export function Link(...rest: ElementChild[]): HTMLLinkElement { return tag("link", ...rest); }
export function Main(...rest: ElementChild[]): HTMLElement { return tag("main", ...rest); }
export function HtmlMap(...rest: ElementChild[]): HTMLMapElement { return tag("map", ...rest); }
export function Mark(...rest: ElementChild[]): HTMLElement { return tag("mark", ...rest); }
export function Marquee(...rest: ElementChild[]): HTMLMarqueeElement { return tag("marquee", ...rest); }
export function Menu(...rest: ElementChild[]): HTMLMenuElement { return tag("menu", ...rest); }
export function Meta(...rest: ElementChild[]): HTMLMetaElement { return tag("meta", ...rest); }
export function Meter(...rest: ElementChild[]): HTMLMeterElement { return tag("meter", ...rest); }
export function Nav(...rest: ElementChild[]): HTMLElement { return tag("nav", ...rest); }
export function NoScript(...rest: ElementChild[]): HTMLElement { return tag("noscript", ...rest); }
export function HtmlObject(...rest: ElementChild[]): HTMLObjectElement { return tag("object", ...rest); }
export function OL(...rest: ElementChild[]): HTMLOListElement { return tag("ol", ...rest); }
export function OptGroup(...rest: ElementChild[]): HTMLOptGroupElement { return tag("optgroup", ...rest); }
export function Option(...rest: ElementChild[]): HTMLOptionElement { return tag("option", ...rest); }
export function Output(...rest: ElementChild[]): HTMLOutputElement { return tag("output", ...rest); }
export function P(...rest: ElementChild[]): HTMLParagraphElement { return tag("p", ...rest); }
export function Param(...rest: ElementChild[]): HTMLParamElement { return tag("param", ...rest); }
export function Picture(...rest: ElementChild[]): HTMLPictureElement { return tag("picture", ...rest); }
export function Pre(...rest: ElementChild[]): HTMLPreElement { return tag("pre", ...rest); }
export function Progress(...rest: ElementChild[]): HTMLProgressElement { return tag("progress", ...rest); }
export function Q(...rest: ElementChild[]): HTMLQuoteElement { return tag("q", ...rest); }
export function RB(...rest: ElementChild[]): HTMLElement { return tag("rb", ...rest); }
export function RP(...rest: ElementChild[]): HTMLElement { return tag("rp", ...rest); }
export function RT(...rest: ElementChild[]): HTMLElement { return tag("rt", ...rest); }
export function RTC(...rest: ElementChild[]): HTMLElement { return tag("rtc", ...rest); }
export function Ruby(...rest: ElementChild[]): HTMLElement { return tag("ruby", ...rest); }
export function S(...rest: ElementChild[]): HTMLElement { return tag("s", ...rest); }
export function Samp(...rest: ElementChild[]): HTMLElement { return tag("samp", ...rest); }
export function Script(...rest: ElementChild[]): HTMLScriptElement { return tag("script", ...rest); }
export function Section(...rest: ElementChild[]): HTMLElement { return tag("section", ...rest); }
export function Select(...rest: ElementChild[]): HTMLSelectElement { return tag("select", ...rest); }
export function Slot(...rest: ElementChild[]): HTMLSlotElement { return tag("slot", ...rest); }
export function Small(...rest: ElementChild[]): HTMLElement { return tag("small", ...rest); }
export function Source(...rest: ElementChild[]): HTMLSourceElement { return tag("source", ...rest); }
export function Span(...rest: ElementChild[]): HTMLSpanElement { return tag("span", ...rest); }
export function Strong(...rest: ElementChild[]): HTMLElement { return tag("strong", ...rest); }
export function Sub(...rest: ElementChild[]): HTMLElement { return tag("sub", ...rest); }
export function Summary(...rest: ElementChild[]): HTMLElement { return tag("summary", ...rest); }
export function Sup(...rest: ElementChild[]): HTMLElement { return tag("sup", ...rest); }
export function Table(...rest: ElementChild[]): HTMLTableElement { return tag("table", ...rest); }
export function TBody(...rest: ElementChild[]): HTMLTableSectionElement { return tag("tbody", ...rest); }
export function TD(...rest: ElementChild[]): HTMLTableDataCellElement { return tag("td", ...rest); }
export function Template(...rest: ElementChild[]): HTMLTemplateElement { return tag("template", ...rest); }
export function TextArea(...rest: ElementChild[]): HTMLTextAreaElement { return tag("textarea", ...rest); }
export function TFoot(...rest: ElementChild[]): HTMLTableSectionElement { return tag("tfoot", ...rest); }
export function TH(...rest: ElementChild[]): HTMLTableHeaderCellElement { return tag("th", ...rest); }
export function THead(...rest: ElementChild[]): HTMLTableSectionElement { return tag("thead", ...rest); }
export function Time(...rest: ElementChild[]): HTMLTimeElement { return tag("time", ...rest); }
export function Title(...rest: ElementChild[]): HTMLTitleElement { return tag("title", ...rest); }
export function TR(...rest: ElementChild[]): HTMLTableRowElement { return tag("tr", ...rest); }
export function Track(...rest: ElementChild[]): HTMLTrackElement { return tag("track", ...rest); }
export function U(...rest: ElementChild[]): HTMLElement { return tag("u", ...rest); }
export function UL(...rest: ElementChild[]): HTMLUListElement { return tag("ul", ...rest); }
export function Var(...rest: ElementChild[]): HTMLElement { return tag("var", ...rest); }
export function Video(...rest: ElementChild[]): HTMLVideoElement { return tag("video", ...rest); }
export function WBR(): HTMLElement { return tag("wbr"); }
/**
* creates an HTML Input tag that is a button.
*/
export function InputButton(...rest: ElementChild[]): HTMLInputElement { return Input(type("button"), ...rest); }
/**
* creates an HTML Input tag that is a checkbox.
*/
export function InputCheckbox(...rest: ElementChild[]): HTMLInputElement { return Input(type("checkbox"), ...rest); }
/**
* creates an HTML Input tag that is a color picker.
*/
export function InputColor(...rest: ElementChild[]): HTMLInputElement { return Input(type("color"), ...rest); }
/**
* creates an HTML Input tag that is a date picker.
*/
export function InputDate(...rest: ElementChild[]): HTMLInputElement { return Input(type("date"), ...rest); }
/**
* creates an HTML Input tag that is a local date-time picker.
*/
export function InputDateTime(...rest: ElementChild[]): HTMLInputElement { return Input(type("datetime-local"), ...rest); }
/**
* creates an HTML Input tag that is an email entry field.
*/
export function InputEmail(...rest: ElementChild[]): HTMLInputElement { return Input(type("email"), ...rest); }
/**
* creates an HTML Input tag that is a file picker.
*/
export function InputFile(...rest: ElementChild[]): HTMLInputElement { return Input(type("file"), ...rest); }
/**
* creates an HTML Input tag that is a hidden field.
*/
export function InputHidden(...rest: ElementChild[]): HTMLInputElement { return Input(type("hidden"), ...rest); }
/**
* creates an HTML Input tag that is a graphical submit button.
*/
export function InputImage(...rest: ElementChild[]): HTMLInputElement { return Input(type("image"), ...rest); }
/**
* creates an HTML Input tag that is a month picker.
*/
export function InputMonth(...rest: ElementChild[]): HTMLInputElement { return Input(type("month"), ...rest); }
/**
* creates an HTML Input tag that is a month picker.
*/
export function InputNumber(...rest: ElementChild[]): HTMLInputElement { return Input(type("number"), ...rest); }
/**
* creates an HTML Input tag that is a password entry field.
*/
export function InputPassword(...rest: ElementChild[]): HTMLInputElement { return Input(type("password"), ...rest); }
/**
* creates an HTML Input tag that is a radio button.
*/
export function InputRadio(...rest: ElementChild[]): HTMLInputElement { return Input(type("radio"), ...rest); }
/**
* creates an HTML Input tag that is a range selector.
*/
export function InputRange(...rest: ElementChild[]): HTMLInputElement { return Input(type("range"), ...rest); }
/**
* creates an HTML Input tag that is a form reset button.
*/
export function InputReset(...rest: ElementChild[]): HTMLInputElement { return Input(type("reset"), ...rest); }
/**
* creates an HTML Input tag that is a search entry field.
*/
export function InputSearch(...rest: ElementChild[]): HTMLInputElement { return Input(type("search"), ...rest); }
/**
* creates an HTML Input tag that is a submit button.
*/
export function InputSubmit(...rest: ElementChild[]): HTMLInputElement { return Input(type("submit"), ...rest); }
/**
* creates an HTML Input tag that is a telephone number entry field.
*/
export function InputTelephone(...rest: ElementChild[]): HTMLInputElement { return Input(type("tel"), ...rest); }
/**
* creates an HTML Input tag that is a text entry field.
*/
export function InputText(...rest: ElementChild[]): HTMLInputElement { return Input(type("text"), ...rest); }
/**
* creates an HTML Input tag that is a time picker.
*/
export function InputTime(...rest: ElementChild[]): HTMLInputElement { return Input(type("time"), ...rest); }
/**
* creates an HTML Input tag that is a URL entry field.
*/
export function InputURL(...rest: ElementChild[]): HTMLInputElement { return Input(type("url"), ...rest); }
/**
* creates an HTML Input tag that is a week picker.
*/
export function InputWeek(...rest: ElementChild[]): HTMLInputElement { return Input(type("week"), ...rest); }
/**
* Creates a text node out of the give input.
*/
export function TextNode(txt: any): Text {
return document.createTextNode(txt);
}
/**
* Creates a Div element with margin: auto.
*/
export function Run(...rest: ElementChild[]): HTMLDivElement {
return Div(
styles(
margin("auto")),
...rest);
}
export function Style(...rest: CSSInJSRule[]): HTMLStyleElement {
let elem = document.createElement("style");
document.head.appendChild(elem);
for (let x of rest) {
x.apply(elem.sheet);
}
return elem;
} | the_stack |
import * as fs from "fs";
import {PathLike} from "fs";
import * as readline from "readline";
interface ClassInfo {
/**
* 类的id,默认使用类名,不能重复
*/
id?: string;
/**
* 类的类型
*/
type: any;
/**
* 记录装饰器调用的位置
*/
pos: any;
}
/**
* 序列化时需要忽略的字段
*/
const transientFields = new Map<any, any>();
/**
* 被@Serialize装饰的类信息
*/
const classInfos = new Map<any, ClassInfo>();
/**
* 通过 classId 获取 classInfo
* @param {string} id
* @returns {ClassInfo}
*/
export const getClassInfoById = (id: string) => {
for (let entry of classInfos) {
let classInfo = entry[1];
if (classInfo.id == id) {
return classInfo;
}
}
return null;
};
export const getClassInfoByConstructor = (constructor: any) => {
return classInfos.get(constructor);
};
const stackPosReg = new RegExp("^at .* \\((.*)\\)$");
/**
* 获取 @Serialize 的装饰位置,以便在后续报错时能指出正确的位置
* @returns {string}
*/
function getDecoratorPos() {
const stack = new Error("test").stack.split("\n");
const pos = stack[3].trim();
const stackPosM = stackPosReg.exec(pos);
return stackPosM ? stackPosM[1] : null;
}
export interface SerializableConfig {
classId?: string;
}
/**
* 在js加载的过程中,有这个装饰器的类的类信息会保存到 classInfos 中,用于序列化和反序列化
* @param {SerializableConfig} config
* @returns {(target) => void}
* @constructor
*/
export function Serializable(config?: SerializableConfig) {
const decoratorPos = getDecoratorPos();
return function (target) {
if (!config) config = {};
const id = config.classId || target.name;
let existed = classInfos.get(id);
if (!existed) {
existed = {
id: config.classId || target.name,
type: target,
pos: decoratorPos,
transients: transientFields[target],
} as ClassInfo;
classInfos.set(target, existed);
}
else {
throw new Error("duplicate classId(" + existed.id + ") at: \n" + existed.pos + "\n" + existed.pos);
}
}
}
/**
* 类在序列化时要忽略的字段
* 不能作用于类静态字段
* @returns {(target: any, field: string) => void}
* @constructor
*/
export function Transient() {
return function (target: any, field: string) {
const isStatic = target.constructor.name === "Function";
if (isStatic) throw new Error("cannot decorate static field with Transient"); // @Transient 不能作用于类静态成员
const type = target.constructor;
let transients = transientFields[type];
if (!transients) {
transientFields[type] = transients = {};
}
transients[field] = true;
};
}
export function Assign(target, source) {
if (source && target && typeof source == "object" && typeof target == "object") {
const transients = transientFields[target.constructor];
if (transients) {
for (let field of Object.keys(source)) {
if (!transients[field]) {
target[field] = source[field];
}
}
}
else {
Object.assign(target, source);
}
}
}
interface Writer {
write(str: string);
}
/**
* 序列化和反序列化工具类,目前在整个框架中只有一个地方用到:
* 1. QueueManager 中保存和加载运行状态
*/
export class SerializableUtil {
static serializeToFile(obj: any, file: PathLike, encoding: string = "utf-8"): Promise<void> {
return new Promise((resolve, reject) => {
let writeStream = fs.createWriteStream(file, encoding);
let serFinish = false;
let writeNum = 0;
const checkWriteFinish = () => {
if (writeNum == 0) {
writeStream.close();
resolve();
}
};
let buffer = "";
const bufferMaxLen = 1024;
const tryFlush = (force: boolean = false) => {
if (buffer.length >= bufferMaxLen || (force && buffer.length > 0)) {
writeNum++;
writeStream.write(buffer, error => {
if (error) {
reject(error);
}
else {
writeNum--;
if (serFinish) {
checkWriteFinish();
}
}
});
buffer = "";
}
};
const writer = {
write: str => {
buffer += str;
tryFlush();
}
};
this._serialize(obj, writer);
serFinish = true;
tryFlush(true);
checkWriteFinish();
});
}
static serializeToString(obj: any): string {
let res = "";
const writer = {
write: str => {
res += str;
}
};
this._serialize(obj, writer);
return res;
}
private static _serialize(obj: any, writer: Writer): string[] {
if (this.isSimpleType(obj)) {
writer.write("g.$=" + JSON.stringify(obj) + ";");
return;
}
// 54进制
const objIdChars = "$ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz";
const objId = num => {
let res = "";
let base = 54;
while (num > 0) {
res = objIdChars[num % base] + res;
num = +(num / base).toFixed(0);
}
return res || "$";
};
const classes = new Map<any, string>();
const addClassNewFunction = objConstructor => {
let c = classes.get(objConstructor);
if (c == null) {
const classInfo = classInfos.get(objConstructor);
if (classInfo) {
const classId = classes.size;
c = "g.c" + classId;
classes.set(objConstructor, c);
writer.write(`g.class${classId} = (getClass(${JSON.stringify(classInfo.id)}) || {}).type;${c} = obj => { if (g.class${classId}) { const ins = new g.class${classId}(); Object.assign(ins, obj); return ins; } return obj;};\n`);
}
}
return c;
};
const refs = new Map<string, {
objIndex: string,
keyOrIndex: number | string
}[]>();
const addRef = (objIndex: string, keyOrIndex: number | string, refIndex: string) => {
let arr = refs.get(refIndex);
if (!arr) {
refs.set(refIndex, arr = []);
}
arr.push({
objIndex: objIndex,
keyOrIndex: keyOrIndex
});
};
const objs = new Map<any, {
index: number,
symbol: string
}>();
objs.set(obj, {index: 0, symbol: "$"});
const objsIt = objs.entries();
let entry;
while (entry = objsIt.next().value) {
const obj = entry[0];
const objIndex = entry[1].index;
const objSymbol = entry[1].symbol;
const existedObjRefs = [];
const objType = typeof obj;
if (obj instanceof Array) {
const insArr = new Array(obj.length);
let isAllRef = true;
for (let i = 0, len = obj.length; i < len; i++) {
const value = obj[i];
if (this.isSimpleType(value)) {
insArr[i] = value;
isAllRef = false;
}
else {
let refObjInfo = objs.get(value);
if (refObjInfo == null) {
refObjInfo = {
index: objs.size,
symbol:objId(objs.size)
};
objs.set(value, refObjInfo);
}
if (refObjInfo.index <= objIndex) {
existedObjRefs.push([i, refObjInfo.symbol]);
}
else {
addRef(objSymbol, i, refObjInfo.symbol);
}
}
}
if (isAllRef) {
writer.write(`g.${objSymbol}=new Array(${obj.length});`);
}
else {
const insObjJson = JSON.stringify(insArr);
writer.write(`g.${objSymbol}=` + insObjJson + ";");
}
}
else if (objType == "object") {
const objConstructor = obj.constructor;
const newF = addClassNewFunction(objConstructor);
const transients = transientFields[objConstructor];
let insObj;
let insObjs = [];
let keyNum = 0;
for (let field in obj) {
if (transients && transients[field]) {
// 忽略字段
continue;
}
const value = obj[field];
if (this.isSimpleType(value)) {
if (keyNum % 1000 == 0) {
insObj = {};
insObjs.push(insObj);
}
insObj[field] = value;
keyNum++;
}
else {
let refObjInfo = objs.get(value);
if (refObjInfo == null) {
refObjInfo = {
index: objs.size,
symbol:objId(objs.size)
};
objs.set(value, refObjInfo);
}
if (refObjInfo.index <= objIndex) {
existedObjRefs.push([field, refObjInfo.symbol]);
}
else {
addRef(objSymbol, field, refObjInfo.symbol);
}
}
}
let insObjJson = insObjs.length > 0 ? JSON.stringify(insObjs[0]) : "{}";
writer.write(`g.${objSymbol}=` + (newF ? newF + "(" + insObjJson + ")" : insObjJson) + ";");
for (let i = 1, len = insObjs.length; i < len; i++) {
insObjJson = JSON.stringify(insObjs[i]);
writer.write(`\nObject.assign(g.${objSymbol}, ${insObjJson});`);
}
}
else if (objType == "function") {
const classInfo = classInfos.get(obj);
if (classInfo) {
writer.write(`g.${objSymbol}=getClass(${JSON.stringify(classInfo.id)});`);
}
else {
let funStr = obj.toString();
if (funStr.startsWith("class ")) {
// 未用 @Serializable 标记的类不做序列化
writer.write(`g.${objSymbol}={};`);
}
else {
// 只对简单方法进行序列化
funStr = funStr.split(/\r?\n/).filter(line => !line.trimLeft().startsWith("//")).join(";");
writer.write(`g.${objSymbol}=(${funStr});`);
}
}
}
for (let refInfo of existedObjRefs) {
writer.write(`g.${objSymbol}[${typeof refInfo[0] == "number" ? refInfo[0] : JSON.stringify(refInfo[0])}]=g.${refInfo[1]};`);
}
const refsOfThis = refs.get(objSymbol);
if (refsOfThis) {
for (let refItem of refsOfThis) {
writer.write(`g.${refItem.objIndex}[${typeof refItem.keyOrIndex == "number" ? refItem.keyOrIndex : JSON.stringify(refItem.keyOrIndex)}]=g.${objSymbol};`);
}
refs.delete(objSymbol);
}
writer.write("\n");
}
}
private static isSimpleType(obj: any) {
if (obj == null || obj == undefined) return true;
const objType = typeof obj;
return objType == "string" || objType == "number" || objType == "boolean";
}
static deserializeFromString(str: string) {
const getClass = id => getClassInfoById(id);
const g: any = {};
eval(str);
return g.$;
}
static deserializeFromFile(file: PathLike, encoding: string = "utf-8"): Promise<any> {
return new Promise<any>(async (resolve, reject) => {
const getClass = id => getClassInfoById(id);
const g: any = {};
const lineBuffer = [];
let waitReadFinishResolve;
const waitReadFinishPromise = new Promise(resolve => waitReadFinishResolve = resolve);
const evalLines =() => {
let subLinesStr = lineBuffer.join("\n");
try {
eval(subLinesStr);
}
catch (e) {
const stacks = e.stack.split("\n");
stacks.splice(1, 0, subLinesStr);
e.stack = stacks.join("\n");
waitReadFinishResolve(e);
}
lineBuffer.splice(0, lineBuffer.length);
};
const reader = readline.createInterface({
input: fs.createReadStream(file).setEncoding(encoding)
});
reader.on('line', function(line) {
lineBuffer.push(line);
lineBuffer.length >= 1000 && evalLines();
});
reader.on('close', function(line) {
lineBuffer.length > 0 && evalLines();
waitReadFinishResolve();
});
waitReadFinishPromise.then(err => {
if (err) {
reader.close();
return reject(err);
}
resolve(g.$);
});
});
}
} | the_stack |
import {DataTypes, Model, QueryTypes, Sequelize} from "sequelize";
import InventorySlot from "./InventorySlot";
import PetEntity from "./PetEntity";
import PlayerSmallEvent from "./PlayerSmallEvent";
import MissionSlot from "./MissionSlot";
import PlayerMissionsInfo from "./PlayerMissionsInfo";
import InventoryInfo from "./InventoryInfo";
import {Data} from "../Data";
import {DraftBotEmbed} from "../messages/DraftBotEmbed";
import {Constants} from "../Constants";
import Class, {Classes} from "./Class";
import MapLocation, {MapLocations} from "./MapLocation";
import {MapLinks} from "./MapLink";
import Entity from "./Entity";
import {Translations} from "../Translations";
import {Client, TextChannel} from "discord.js";
import {Maps} from "../Maps";
import {DraftBotPrivateMessage} from "../messages/DraftBotPrivateMessage";
import {minutesToMilliseconds} from "../utils/TimeUtils";
import {GenericItemModel} from "./GenericItemModel";
import {MissionsController} from "../missions/MissionsController";
import {escapeUsername} from "../utils/StringUtils";
import moment = require("moment");
declare const client: Client;
export class Player extends Model {
public readonly id!: number;
public score!: number;
public weeklyScore!: number;
public level!: number;
public experience!: number;
public money!: number;
public class!: number;
public badges: string;
public readonly entityId!: number;
public guildId: number;
public topggVoteAt!: Date;
public nextEvent!: number;
public petId!: number;
public lastPetFree!: Date;
public effect!: string;
public effectEndDate!: Date;
public effectDuration!: number;
public mapLinkId!: number;
public startTravelDate!: Date;
public dmNotification!: boolean;
public updatedAt!: Date;
public createdAt!: Date;
public InventorySlots: InventorySlot[];
public InventoryInfo: InventoryInfo;
public Pet: PetEntity;
public PlayerSmallEvents: PlayerSmallEvent[];
public MissionSlots: MissionSlot[];
public PlayerMissionsInfo: PlayerMissionsInfo;
public getEntity: () => Entity;
private pseudo: string;
public addBadge(badge: string): boolean {
if (this.badges !== null) {
if (!this.hasBadge(badge)) {
this.badges += "-" + badge;
}
else {
return false;
}
}
else {
this.badges = badge;
}
return true;
}
public hasBadge(badge: string): boolean {
return this.badges === null ? false : this.badges.split("-")
.includes(badge);
}
async getDestinationId() {
const link = await MapLinks.getById(this.mapLinkId);
return link.endMap;
}
public async getDestination(): Promise<MapLocation> {
const link = await MapLinks.getById(this.mapLinkId);
return await MapLocations.getById(link.endMap);
}
public async getPreviousMap(): Promise<MapLocation> {
const link = await MapLinks.getById(this.mapLinkId);
return await MapLocations.getById(link.startMap);
}
public async getPreviousMapId(): Promise<number> {
const link = await MapLinks.getById(this.mapLinkId);
return link.startMap;
}
public async getCurrentTripDuration(): Promise<number> {
const link = await MapLinks.getById(this.mapLinkId);
return link.tripDuration;
}
public getExperienceNeededToLevelUp(): number {
const data = Data.getModule("values");
return Math.round(data.getNumber("xp.baseValue") * Math.pow(data.getNumber("xp.coeff"), this.level + 1)) - data.getNumber("xp.minus");
}
public async addScore(entity: Entity, score: number, channel: TextChannel, language: string): Promise<void> {
this.score += score;
if (score > 0) {
await MissionsController.update(entity.discordUserId, channel, language, "earnPoints", score);
}
await this.setScore(entity, this.score, channel, language);
this.addWeeklyScore(score);
}
public async setScore(entity: Entity, score: number, channel: TextChannel, language: string): Promise<void> {
await MissionsController.update(entity.discordUserId, channel, language, "reachScore", score, null, true);
if (score > 0) {
this.score = score;
}
else {
this.score = 0;
}
}
public async addMoney(entity: Entity, money: number, channel: TextChannel, language: string): Promise<void> {
this.money += money;
if (money > 0) {
await MissionsController.update(entity.discordUserId, channel, language, "earnMoney", money);
}
this.setMoney(this.money);
}
public setMoney(money: number): void {
if (money > 0) {
this.money = money;
}
else {
this.money = 0;
}
}
private addWeeklyScore(weeklyScore: number): void {
this.weeklyScore += weeklyScore;
this.setWeeklyScore(this.weeklyScore);
}
private setWeeklyScore(weeklyScore: number): void {
if (weeklyScore > 0) {
this.weeklyScore = weeklyScore;
}
else {
this.weeklyScore = 0;
}
}
public async getPseudo(language: string): Promise<string> {
await this.setPseudo(language);
return this.pseudo;
}
public async setPseudo(language: string): Promise<void> {
const entity = await this.getEntity();
if (entity.discordUserId !== undefined) {
if (client.users.cache.get(entity.discordUserId) !== undefined) {
this.pseudo = escapeUsername(client.users.cache.get(entity.discordUserId).username);
}
else {
this.pseudo = Translations.getModule("models.players", language).get("pseudo");
}
}
else {
this.pseudo = Translations.getModule("models.players", language).get("pseudo");
}
}
public needLevelUp(): boolean {
return this.experience >= this.getExperienceNeededToLevelUp();
}
public getClassGroup(): number {
return this.level < Constants.CLASS.GROUP1LEVEL ? 0 :
this.level < Constants.CLASS.GROUP2LEVEL ? 1 :
this.level < Constants.CLASS.GROUP3LEVEL ? 2 :
3;
}
public async getLvlUpReward(language: string, entity: Entity): Promise<string[]> {
const tr = Translations.getModule("models.players", language);
const bonuses = [];
if (this.level === Constants.FIGHT.REQUIRED_LEVEL) {
bonuses.push(tr.get("levelUp.fightUnlocked"));
}
if (this.level === Constants.GUILD.REQUIRED_LEVEL) {
bonuses.push(tr.get("levelUp.guildUnlocked"));
}
if (this.level % 10 === 0) {
entity.health = await entity.getMaxHealth();
bonuses.push(tr.get("levelUp.healthRestored"));
}
if (this.level === Constants.CLASS.REQUIRED_LEVEL) {
bonuses.push(tr.get("levelUp.classUnlocked"));
}
if (this.level === Constants.CLASS.GROUP1LEVEL) {
bonuses.push(tr.get("levelUp.classTiertwo"));
}
if (this.level === Constants.CLASS.GROUP2LEVEL) {
bonuses.push(tr.get("levelUp.classTierthree"));
}
if (this.level === Constants.CLASS.GROUP3LEVEL) {
bonuses.push(tr.get("levelUp.classTierfour"));
}
if (this.level === Constants.MISSIONS.SLOT_2_LEVEL || this.level === Constants.MISSIONS.SLOT_3_LEVEL) {
bonuses.push(tr.get("levelUp.newMissionSlot"));
}
bonuses.push(tr.get("levelUp.noBonuses"));
return bonuses;
}
public async levelUpIfNeeded(entity: Entity, channel: TextChannel, language: string): Promise<void> {
if (!this.needLevelUp()) {
return;
}
const xpNeeded = this.getExperienceNeededToLevelUp();
this.experience -= xpNeeded;
this.level++;
await MissionsController.update(entity.discordUserId, channel, language, "reachLevel", this.level, null, true);
const bonuses = await this.getLvlUpReward(language, entity);
let msg = Translations.getModule("models.players", language).format("levelUp.mainMessage", {
mention: entity.getMention(),
level: this.level
});
for (let i = 0; i < bonuses.length - 1; ++i) {
msg += bonuses[i] + "\n";
}
msg += bonuses[bonuses.length - 1];
await channel.send({content: msg});
if (this.needLevelUp()) {
return this.levelUpIfNeeded(entity, channel, language);
}
}
public async setLastReportWithEffect(time: number, timeMalus: number, effectMalus: string): Promise<void> {
this.startTravelDate = new Date(time);
await this.save();
await Maps.applyEffect(this, effectMalus, timeMalus);
}
public async killIfNeeded(entity: Entity, channel: TextChannel, language: string): Promise<boolean> {
if (entity.health > 0) {
return false;
}
// TODO new logger
// log("This user is dead : " + entity.discordUserId);
await Maps.applyEffect(entity.Player, Constants.EFFECT.DEAD);
const tr = Translations.getModule("models.players", language);
await channel.send({content: tr.format("ko", {pseudo: await this.getPseudo(language)})});
const guildMember = await channel.guild.members.fetch(entity.discordUserId);
const user = guildMember.user;
this.dmNotification ? user.send({embeds: [new DraftBotPrivateMessage(user, tr.get("koPM.title"), tr.get("koPM.description"), language)]})
: channel.send({
embeds: [new DraftBotEmbed()
.setDescription(tr.get("koPM.description"))
.setTitle(tr.get("koPM.title"))
.setFooter(tr.get("dmDisabledFooter"))]
});
return true;
}
public isInactive(): boolean {
return this.startTravelDate.valueOf() + minutesToMilliseconds(120) + Data.getModule("commands.top").getNumber("fifth10days") < Date.now();
}
public currentEffectFinished(): boolean {
if (this.effect === Constants.EFFECT.DEAD || this.effect === Constants.EFFECT.BABY) {
return false;
}
if (this.effect === Constants.EFFECT.SMILEY) {
return true;
}
if (!this.effectEndDate) {
return true;
}
return this.effectEndDate.valueOf() < Date.now();
}
public effectRemainingTime(): number {
let remainingTime = 0;
if (Data.getModule("models.players").exists("effectMalus." + this.effect) || this.effect === Constants.EFFECT.OCCUPIED) {
if (!this.effectEndDate) {
return 0;
}
remainingTime = this.effectEndDate.valueOf() - Date.now();
}
if (remainingTime < 0) {
remainingTime = 0;
}
return remainingTime;
}
public checkEffect(): boolean {
return [Constants.EFFECT.BABY, Constants.EFFECT.SMILEY, Constants.EFFECT.DEAD].indexOf(this.effect) !== -1;
}
public getLevel(): number {
return this.level;
}
public async getNbPlayersOnYourMap(): Promise<number> {
const query = `SELECT COUNT(*) as count
FROM Players
WHERE (mapLinkId = :link OR mapLinkId = :linkInverse)
AND score > 100`;
const linkInverse = await MapLinks.getInverseLinkOf(this.mapLinkId);
return Math.round(
(<{ count: number }[]>(await Player.sequelize.query(query, {
replacements: {
link: this.mapLinkId,
linkInverse: linkInverse.id
},
type: QueryTypes.SELECT
})))[0].count
);
}
public getMainWeaponSlot(): InventorySlot {
const filtered = this.InventorySlots.filter(slot => slot.isEquipped() && slot.isWeapon());
if (filtered.length === 0) {
return null;
}
return filtered[0];
}
public getMainArmorSlot(): InventorySlot {
const filtered = this.InventorySlots.filter(slot => slot.isEquipped() && slot.isArmor());
if (filtered.length === 0) {
return null;
}
return filtered[0];
}
public getMainPotionSlot(): InventorySlot {
const filtered = this.InventorySlots.filter(slot => slot.isEquipped() && slot.isPotion());
if (filtered.length === 0) {
return null;
}
return filtered[0];
}
public getMainObjectSlot(): InventorySlot {
const filtered = this.InventorySlots.filter(slot => slot.isEquipped() && slot.isObject());
if (filtered.length === 0) {
return null;
}
return filtered[0];
}
public async giveItem(item: GenericItemModel): Promise<boolean> {
const category = item.getCategory();
const equippedItem = this.InventorySlots.filter(slot => slot.itemCategory === category && slot.isEquipped())[0];
if (equippedItem && equippedItem.itemId === 0) {
await InventorySlot.update({
itemId: item.id
}, {
where: {
playerId: this.id,
itemCategory: category,
slot: equippedItem.slot
}
});
return true;
}
const slotsLimit = this.InventoryInfo.slotLimitForCategory(category);
const items = this.InventorySlots.filter(slot => slot.itemCategory === category && slot.slot < slotsLimit);
if (items.length >= slotsLimit) {
return false;
}
for (let i = 0; i < slotsLimit; ++i) {
if (items.filter(slot => slot.slot === i).length === 0) {
await InventorySlot.create({
playerId: this.id,
itemCategory: category,
itemId: item.id,
slot: i
});
return true;
}
}
return false;
}
public async drinkPotion() {
await InventorySlot.update(
{
itemId: Data.getModule("models.inventories").getNumber("potionId")
},
{
where: {
slot: 0,
itemCategory: Constants.ITEM_CATEGORIES.POTION,
playerId: this.id
}
});
}
public async getMaxStatsValue() {
const playerClass = await Classes.getById(this.class);
const attackItemValue = playerClass.getAttackValue(this.level);
const defenseItemValue = playerClass.getDefenseValue(this.level);
const speedItemValue = playerClass.getSpeedValue(this.level);
return [attackItemValue, defenseItemValue, speedItemValue];
}
/**
* check if a player has an empty mission slot
*/
public hasEmptyMissionSlot(): boolean {
return this.MissionSlots.filter(slot => !slot.isCampaign()).length < this.getMissionSlots();
}
/**
* give experience to a player
* @param xpWon
* @param entity
* @param channel
* @param language
*/
public async addExperience(xpWon: number, entity: Entity, channel: TextChannel, language: string) {
this.experience += xpWon;
if (xpWon > 0) {
await MissionsController.update(entity.discordUserId, channel, language, "earnXP", xpWon);
}
while (this.needLevelUp()) {
await this.levelUpIfNeeded(entity, channel, language);
}
}
/**
* get the amount of secondary mission a player can have at maximum
*/
public getMissionSlots(): number {
return this.level >= Constants.MISSIONS.SLOT_3_LEVEL ? 3 : this.level >= Constants.MISSIONS.SLOT_2_LEVEL ? 2 : 1;
}
}
export class Players {
static async getByRank(rank: number): Promise<Player[]> {
const query = `SELECT *
FROM (SELECT entityId,
RANK() OVER (ORDER BY score desc, level desc) rank,
RANK() OVER (ORDER BY weeklyScore desc, level desc) weeklyRank
FROM players)
WHERE rank = :rank`;
return await Player.sequelize.query(query, {
replacements: {
rank: rank
},
type: QueryTypes.SELECT
});
}
static async getById(id: number): Promise<Player> {
const query = `SELECT *
FROM (SELECT id,
RANK() OVER (ORDER BY score desc, level desc) rank,
RANK() OVER (ORDER BY weeklyScore desc, level desc) weeklyRank
FROM players)
WHERE id = :id`;
return <Player><unknown>(await Player.sequelize.query(query, {
replacements: {
id: id
},
type: QueryTypes.SELECT
}));
}
static async getNbMeanPoints(): Promise<number> {
const query = `SELECT AVG(score) as avg
FROM Players
WHERE score > 100`;
return Math.round(
(<{ avg: number }[]>(await Player.sequelize.query(query, {
type: QueryTypes.SELECT
})))[0].avg
);
}
static async getMeanWeeklyScore(): Promise<number> {
const query = `SELECT AVG(weeklyScore) as avg
FROM Players
WHERE score > 100`;
return Math.round(
(<{ avg: number }[]>(await Player.sequelize.query(query, {
type: QueryTypes.SELECT
})))[0].avg
);
}
static async getNbPlayersHaventStartedTheAdventure(): Promise<number> {
const query = `SELECT COUNT(*) as count
FROM Players
WHERE effect = ":baby:"`;
return (<{ count: number }[]>(await Player.sequelize.query(query, {
type: QueryTypes.SELECT
})))[0].count;
}
static async getLevelMean(): Promise<number> {
const query = `SELECT AVG(level) as avg
FROM Players
WHERE score > 100`;
return Math.round(
(<{ avg: number }[]>(await Player.sequelize.query(query, {
type: QueryTypes.SELECT
})))[0].avg
);
}
static async getNbMeanMoney(): Promise<number> {
const query = `SELECT AVG(money) as avg
FROM Players
WHERE score > 100`;
return Math.round(
(<{ avg: number }[]>(await Player.sequelize.query(query, {
type: QueryTypes.SELECT
})))[0].avg
);
}
static async getSumAllMoney(): Promise<number> {
const query = `SELECT SUM(money) as sum
FROM Players
WHERE score > 100`;
return (<{ sum: number }[]>(await Player.sequelize.query(query, {
type: QueryTypes.SELECT
})))[0].sum;
}
static async getRichestPlayer(): Promise<number> {
const query = `SELECT MAX(money) as max
FROM Players`;
return (<{ max: number }[]>(await Player.sequelize.query(query, {
type: QueryTypes.SELECT
})))[0].max;
}
static async getNbPlayersWithClass(classEntity: Class) {
const query = `SELECT COUNT(*) as count
FROM Players
WHERE class = :class
AND score > 100`;
return Math.round(
(<{ count: number }[]>(await Player.sequelize.query(query, {
replacements: {
class: classEntity.id
},
type: QueryTypes.SELECT
})))[0].count
);
}
}
export function initModel(sequelize: Sequelize) {
const data = Data.getModule("models.players");
Player.init({
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true
},
score: {
type: DataTypes.INTEGER,
defaultValue: data.getNumber("score")
},
weeklyScore: {
type: DataTypes.INTEGER,
defaultValue: data.getNumber("weeklyScore")
},
level: {
type: DataTypes.INTEGER,
defaultValue: data.getNumber("level")
},
experience: {
type: DataTypes.INTEGER,
defaultValue: data.getNumber("experience")
},
money: {
type: DataTypes.INTEGER,
defaultValue: data.getNumber("money")
},
class: {
type: DataTypes.INTEGER,
defaultValue: data.getNumber("class")
},
badges: {
type: DataTypes.TEXT,
defaultValue: null
},
entityId: {
type: DataTypes.INTEGER
},
guildId: {
type: DataTypes.INTEGER,
defaultValue: null
},
topggVoteAt: {
type: DataTypes.DATE,
defaultValue: new Date(0)
},
nextEvent: {
type: DataTypes.INTEGER
},
petId: {
type: DataTypes.INTEGER
},
lastPetFree: {
type: DataTypes.DATE,
defaultValue: new Date(0)
},
effect: {
type: DataTypes.STRING(32), // eslint-disable-line new-cap
defaultValue: data.getString("effect")
},
effectEndDate: {
type: DataTypes.DATE,
defaultValue: new Date()
},
effectDuration: {
type: DataTypes.INTEGER,
defaultValue: 0
},
mapLinkId: {
type: DataTypes.INTEGER
},
startTravelDate: {
type: DataTypes.DATE,
defaultValue: 0
},
updatedAt: {
type: DataTypes.DATE,
defaultValue: require("moment")()
.format("YYYY-MM-DD HH:mm:ss")
},
createdAt: {
type: DataTypes.DATE,
defaultValue: require("moment")()
.format("YYYY-MM-DD HH:mm:ss")
},
dmNotification: {
type: DataTypes.BOOLEAN,
defaultValue: true
}
}, {
sequelize,
tableName: "players",
freezeTableName: true
});
Player.beforeSave(instance => {
instance.updatedAt = moment().toDate();
});
}
export default Player; | the_stack |
import {
ConfigureTimeSeriesOperation,
IDocumentStore,
InMemoryDocumentSessionOperations,
RawTimeSeriesPolicy, SessionTimeSeriesBase, TimeSeriesCollectionConfiguration, TimeSeriesConfiguration,
TimeSeriesPolicy,
TimeSeriesValue
} from "../../../src";
import { disposeTestDocumentStore, RavenTestContext, testContext } from "../../Utils/TestUtil";
import moment = require("moment");
import { User } from "../../Assets/Entities";
import { assertThat } from "../../Utils/AssertExtensions";
import { TimeValue } from "../../../src/Primitives/TimeValue";
import { StockPrice } from "../TimeSeries/TimeSeriesTypedSession";
import { delay } from "bluebird";
(RavenTestContext.isPullRequest ? describe.skip : describe)("RavenDB_16060Test", function () {
let store: IDocumentStore;
beforeEach(async function () {
store = await testContext.getDocumentStore();
});
afterEach(async () =>
await disposeTestDocumentStore(store));
it("canIncludeTypedTimeSeries", async () => {
const baseLine = moment().utc().startOf("month");
{
const session = store.openSession();
const user = new User();
user.name = "Oren";
await session.store(user, "users/ayende");
const ts = session.timeSeriesFor("users/ayende", HeartRateMeasure);
ts.append(baseLine.toDate(), HeartRateMeasure.create(59), "watches/fitbit");
await session.saveChanges();
}
{
const session = store.openSession();
const items = await session
.query(User)
.include(x => x.includeTimeSeries("heartRateMeasures"))
.all();
for (const item of items) {
const timeseries = await session.timeSeriesFor(item.id, "heartRateMeasures", HeartRateMeasure).get();
assertThat(timeseries)
.hasSize(1);
assertThat(timeseries[0].value.heartRate)
.isEqualTo(59);
}
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
}
});
it("canServeTimeSeriesFromCache_Typed", async function () {
//RavenDB-16136
const baseLine = moment().utc().startOf("month");
const id = "users/gabor";
{
const session = store.openSession();
const user = new User();
user.name = "Gabor";
await session.store(user, id);
const ts = session.timeSeriesFor(id, HeartRateMeasure);
ts.append(baseLine.toDate(), HeartRateMeasure.create(59), "watches/fitbit");
await session.saveChanges();
}
{
const session = store.openSession();
const timeseries = await session.timeSeriesFor(id, HeartRateMeasure)
.get();
assertThat(timeseries)
.hasSize(1);
assertThat(timeseries[0].value.heartRate)
.isEqualTo(59);
const timeseries2 = await session.timeSeriesFor(id, HeartRateMeasure).get();
assertThat(timeseries2)
.hasSize(1);
assertThat(timeseries2[0].value.heartRate)
.isEqualTo(59);
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
}
});
it("includeTimeSeriesAndMergeWithExistingRangesInCache_Typed", async function () {
const baseLine = moment().utc().startOf("month");
const documentId = "users/ayende";
{
const session = store.openSession();
const user = new User();
user.name = "Oren";
await session.store(user, documentId);
await session.saveChanges();
}
{
const session = store.openSession();
const tsf = session.timeSeriesFor(documentId, HeartRateMeasure);
for (let i = 0; i < 360; i++) {
const typedMeasure = HeartRateMeasure.create(6);
tsf.append(baseLine.clone().add(i * 10, "seconds").toDate(), typedMeasure, "watches/fitbit");
}
await session.saveChanges();
}
{
const session = store.openSession();
let vals = await session.timeSeriesFor(documentId, HeartRateMeasure)
.get(baseLine.clone().add(2, "minutes").toDate(), baseLine.clone().add(10, "minutes").toDate());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
assertThat(vals)
.hasSize(49);
assertThat(vals[0].timestamp.getTime())
.isEqualTo(baseLine.clone().add(2, "minutes").toDate().getTime());
assertThat(vals[48].timestamp.getTime())
.isEqualTo(baseLine.clone().add(10, "minutes").toDate().getTime());
let user = await session
.load<User>(documentId, {
documentType: User,
includes: i => i.includeTimeSeries("heartRateMeasures", baseLine.clone().add(40, "minutes").toDate(), baseLine.clone().add(50, "minutes").toDate())
});
assertThat(session.advanced.numberOfRequests)
.isEqualTo(2);
// should not go to server
vals = await session.timeSeriesFor(documentId, HeartRateMeasure)
.get(baseLine.clone().add(40, "minutes").toDate(), baseLine.clone().add(50, "minutes").toDate());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(2);
assertThat(vals)
.hasSize(61);
assertThat(vals[0].timestamp.getTime())
.isEqualTo(baseLine.clone().add(40, "minutes").toDate().getTime());
assertThat(vals[60].timestamp.getTime())
.isEqualTo(baseLine.clone().add(50, "minutes").toDate().getTime());
const sessionOperations = session as unknown as InMemoryDocumentSessionOperations;
const cache = sessionOperations.timeSeriesByDocId.get(documentId);
assertThat(cache)
.isNotNull();
const ranges = cache.get("heartRateMeasures");
assertThat(ranges)
.hasSize(2);
assertThat(ranges[0].from.getTime())
.isEqualTo(baseLine.clone().add(2, "minutes").toDate().getTime());
assertThat(ranges[0].to.getTime())
.isEqualTo(baseLine.clone().add(10, "minutes").toDate().getTime());
assertThat(ranges[1].from.getTime())
.isEqualTo(baseLine.clone().add(40, "minutes").toDate().getTime());
assertThat(ranges[1].to.getTime())
.isEqualTo(baseLine.clone().add(50, "minutes").toDate().getTime());
// we intentionally evict just the document (without it's TS data),
// so that Load request will go to server
sessionOperations.documentsByEntity.evict(user);
sessionOperations.documentsById.remove(documentId);
// should go to server to get [0, 2] and merge it into existing [2, 10]
user = await session.load(documentId, {
documentType: User,
includes: i => i.includeTimeSeries("heartRateMeasures", baseLine.toDate(), baseLine.clone().add(2, "minutes").toDate())
});
assertThat(session.advanced.numberOfRequests)
.isEqualTo(3);
// should not go to server
vals = await session.timeSeriesFor(documentId, HeartRateMeasure)
.get(baseLine.toDate(), baseLine.clone().add(2, "minutes").toDate());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(3);
assertThat(vals)
.hasSize(13);
assertThat(vals[0].timestamp.getTime())
.isEqualTo(baseLine.toDate().getTime());
assertThat(vals[12].timestamp.getTime())
.isEqualTo(baseLine.clone().add(2, "minutes").toDate().getTime());
assertThat(ranges)
.hasSize(2);
assertThat(ranges[0].from.getTime())
.isEqualTo(baseLine.toDate().getTime());
assertThat(ranges[0].to.getTime())
.isEqualTo(baseLine.clone().add(10, "minutes").toDate().getTime());
assertThat(ranges[1].from.getTime())
.isEqualTo(baseLine.clone().add(40, "minutes").toDate().getTime());
assertThat(ranges[1].to.getTime())
.isEqualTo(baseLine.clone().add(50, "minutes").toDate().getTime());
// evict just the document
sessionOperations.documentsByEntity.evict(user);
sessionOperations.documentsById.remove(documentId);
// should go to server to get [10, 16] and merge it into existing [0, 10]
user = await session.load(documentId, {
documentType: User,
includes: i => i.includeTimeSeries("heartRateMeasures", baseLine.clone().add(10, "minutes").toDate(), baseLine.clone().add(16, "minutes").toDate())
});
assertThat(session.advanced.numberOfRequests)
.isEqualTo(4);
// should not go to server
vals = await session.timeSeriesFor(documentId, HeartRateMeasure)
.get(baseLine.clone().add(10, "minutes").toDate(), baseLine.clone().add(16, "minutes").toDate());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(4);
assertThat(vals)
.hasSize(37);
assertThat(vals[0].timestamp.getTime())
.isEqualTo(baseLine.clone().add(10, "minutes").toDate().getTime());
assertThat(vals[36].timestamp.getTime())
.isEqualTo(baseLine.clone().add(16, "minutes").toDate().getTime());
assertThat(ranges)
.hasSize(2);
assertThat(ranges[0].from.getTime())
.isEqualTo(baseLine.toDate().getTime());
assertThat(ranges[0].to.getTime())
.isEqualTo(baseLine.clone().add(16, "minutes").toDate().getTime());
assertThat(ranges[1].from.getTime())
.isEqualTo(baseLine.clone().add(40, "minutes").toDate().getTime());
assertThat(ranges[1].to.getTime())
.isEqualTo(baseLine.clone().add(50, "minutes").toDate().getTime());
// evict just the document
sessionOperations.documentsByEntity.evict(user);
sessionOperations.documentsById.remove(documentId);
// should go to server to get range [17, 19]
// and add it to cache in between [10, 16] and [40, 50]
user = await session.load(documentId, {
documentType: User,
includes: i => i.includeTimeSeries("heartRateMeasures", baseLine.clone().add(17, "minutes").toDate(), baseLine.clone().add(19, "minutes").toDate())
});
assertThat(session.advanced.numberOfRequests)
.isEqualTo(5);
// should not go to server
vals = await session.timeSeriesFor(documentId, HeartRateMeasure)
.get(baseLine.clone().add(17, "minutes").toDate(), baseLine.clone().add(19, "minutes").toDate());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(5);
assertThat(vals)
.hasSize(13);
assertThat(vals[0].timestamp.getTime())
.isEqualTo(baseLine.clone().add(17, "minutes").toDate().getTime());
assertThat(vals[12].timestamp.getTime())
.isEqualTo(baseLine.clone().add(19, "minutes").toDate().getTime());
assertThat(ranges)
.hasSize(3);
assertThat(ranges[0].from.getTime())
.isEqualTo(baseLine.toDate().getTime());
assertThat(ranges[0].to.getTime())
.isEqualTo(baseLine.clone().add(16, "minutes").toDate().getTime());
assertThat(ranges[1].from.getTime())
.isEqualTo(baseLine.clone().add(17, "minutes").toDate().getTime());
assertThat(ranges[1].to.getTime())
.isEqualTo(baseLine.clone().add(19, "minutes").toDate().getTime());
assertThat(ranges[2].from.getTime())
.isEqualTo(baseLine.clone().add(40, "minutes").toDate().getTime());
assertThat(ranges[2].to.getTime())
.isEqualTo(baseLine.clone().add(50, "minutes").toDate().getTime());
// evict just the document
sessionOperations.documentsByEntity.evict(user);
sessionOperations.documentsById.remove(documentId);
// should go to server to get range [19, 40]
// and merge the result with existing ranges [17, 19] and [40, 50]
// into single range [17, 50]
user = await session.load<User>(documentId, {
documentType: User,
includes: i => i.includeTimeSeries("heartRateMeasures", baseLine.clone().add(18, "minutes").toDate(), baseLine.clone().add(48, "minutes").toDate())
});
assertThat(session.advanced.numberOfRequests)
.isEqualTo(6);
// should not go to server
vals = await session.timeSeriesFor(documentId, HeartRateMeasure)
.get(baseLine.clone().add(18, "minutes").toDate(), baseLine.clone().add(48, "minutes").toDate());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(6);
assertThat(vals)
.hasSize(181);
assertThat(vals[0].timestamp.getTime())
.isEqualTo(baseLine.clone().add(18, "minutes").toDate().getTime());
assertThat(vals[180].timestamp.getTime())
.isEqualTo(baseLine.clone().add(48, "minutes").toDate().getTime());
assertThat(ranges)
.hasSize(2);
assertThat(ranges[0].from.getTime())
.isEqualTo(baseLine.toDate().getTime());
assertThat(ranges[0].to.getTime())
.isEqualTo(baseLine.clone().add(16, "minutes").toDate().getTime());
assertThat(ranges[1].from.getTime())
.isEqualTo(baseLine.clone().add(17, "minutes").toDate().getTime());
assertThat(ranges[1].to.getTime())
.isEqualTo(baseLine.clone().add(50, "minutes").toDate().getTime());
// evict just the document
sessionOperations.documentsByEntity.evict(user);
sessionOperations.documentsById.remove(documentId);
// should go to server to get range [12, 22]
// and merge the result with existing ranges [0, 16] and [17, 50]
// into single range [0, 50]
user = await session.load<User>(documentId, {
documentType: User,
includes: i => i.includeTimeSeries("heartRateMeasures", baseLine.clone().add(12, "minutes").toDate(), baseLine.clone().add(22, "minutes").toDate())
});
assertThat(session.advanced.numberOfRequests)
.isEqualTo(7);
// should not go to server
vals = await session.timeSeriesFor(documentId, HeartRateMeasure)
.get(baseLine.clone().add(12, "minutes").toDate(), baseLine.clone().add(22, "minutes").toDate());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(7);
assertThat(vals)
.hasSize(61);
assertThat(vals[0].timestamp.getTime())
.isEqualTo(baseLine.clone().add(12, "minutes").toDate().getTime());
assertThat(vals[60].timestamp.getTime())
.isEqualTo(baseLine.clone().add(22, "minutes").toDate().getTime());
assertThat(ranges)
.hasSize(1);
assertThat(ranges[0].from.getTime())
.isEqualTo(baseLine.toDate().getTime());
assertThat(ranges[0].to.getTime())
.isEqualTo(baseLine.clone().add(50, "minutes").toDate().getTime());
// evict just the document
sessionOperations.documentsByEntity.evict(user);
sessionOperations.documentsById.remove(documentId);
// should go to server to get range [50, ∞]
// and merge the result with existing range [0, 50] into single range [0, ∞]
user = await session.load(documentId, {
documentType: User,
includes: i => i.includeTimeSeries("heartRateMeasures", "Last", TimeValue.ofMinutes(10))
});
assertThat(session.advanced.numberOfRequests)
.isEqualTo(8);
// should not go to server
vals = await session.timeSeriesFor(documentId, HeartRateMeasure)
.get(baseLine.clone().add(50, "minutes").toDate(), null);
assertThat(session.advanced.numberOfRequests)
.isEqualTo(8);
assertThat(vals)
.hasSize(60);
assertThat(vals[0].timestamp.getTime())
.isEqualTo(baseLine.clone().add(50, "minutes").toDate().getTime());
assertThat(vals[59].timestamp.getTime())
.isEqualTo(baseLine.clone().add(59, "minutes").add(50, "seconds").toDate().getTime());
assertThat(ranges)
.hasSize(1);
assertThat(ranges[0].from.getTime())
.isEqualTo(baseLine.toDate().getTime());
assertThat(ranges[0].to)
.isNull();
}
});
it("includeTimeSeriesAndUpdateExistingRangeInCache_Typed", async function () {
const baseLine = moment().utc().startOf("month");
{
const session = store.openSession();
const user = new User();
user.name = "Oren";
await session.store(user, "users/ayende");
await session.saveChanges();
}
{
const session = store.openSession();
const tsf = session.timeSeriesFor("users/ayende", HeartRateMeasure);
for (let i = 0; i < 360; i++) {
tsf.append(baseLine.clone().add(i * 10, "seconds").toDate(), HeartRateMeasure.create(6), "watches/fitbit");
}
await session.saveChanges();
}
{
const session = store.openSession();
let vals = await session.timeSeriesFor("users/ayende", HeartRateMeasure)
.get(baseLine.clone().add(2, "minutes").toDate(), baseLine.clone().add(10, "minutes").toDate());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
assertThat(vals)
.hasSize(49);
assertThat(vals[0].timestamp.getTime())
.isEqualTo(baseLine.clone().add(2, "minutes").toDate().getTime());
assertThat(vals[48].timestamp.getTime())
.isEqualTo(baseLine.clone().add(10, "minutes").toDate().getTime());
session.timeSeriesFor("users/ayende", HeartRateMeasure)
.append(baseLine.clone().add(3, "minutes").add(3, "seconds").toDate(), HeartRateMeasure.create(6), "watches/fitbit");
await session.saveChanges();
assertThat(session.advanced.numberOfRequests)
.isEqualTo(2);
const user = await session.load<User>("users/ayende", {
documentType: User,
includes: i => i.includeTimeSeries("heartRateMeasures", baseLine.clone().add(3, "minutes").toDate(), baseLine.clone().add(5, "minutes").toDate())
});
assertThat(session.advanced.numberOfRequests)
.isEqualTo(3);
// should not go to server
vals = await session.timeSeriesFor("users/ayende", HeartRateMeasure)
.get(baseLine.clone().add(3, "minutes").toDate(), baseLine.clone().add(5, "minutes").toDate());
assertThat(session.advanced.numberOfRequests)
.isEqualTo(3);
assertThat(vals)
.hasSize(14);
assertThat(vals[0].timestamp.getTime())
.isEqualTo(baseLine.clone().add(3, "minutes").toDate().getTime());
assertThat(vals[1].timestamp.getTime())
.isEqualTo(baseLine.clone().add(3, "minutes").add(3, "seconds").toDate().getTime());
assertThat(vals[13].timestamp.getTime())
.isEqualTo(baseLine.clone().add(5, "minutes").toDate().getTime());
}
});
it("canServeTimeSeriesFromCache_Rollup", async function () {
const raw = new RawTimeSeriesPolicy(TimeValue.ofHours(24));
const p1 = new TimeSeriesPolicy("By6Hours", TimeValue.ofHours(6), TimeValue.ofDays(4));
const p2 = new TimeSeriesPolicy("By1Day", TimeValue.ofDays(1), TimeValue.ofDays(5));
const p3 = new TimeSeriesPolicy("By30Minutes", TimeValue.ofMinutes(30), TimeValue.ofDays(2));
const p4 = new TimeSeriesPolicy("By1Hour", TimeValue.ofMinutes(60), TimeValue.ofDays(3));
const timeSeriesCollectionConfiguration = new TimeSeriesCollectionConfiguration();
timeSeriesCollectionConfiguration.rawPolicy = raw;
timeSeriesCollectionConfiguration.policies = [ p1, p2, p3, p4 ];
const config = new TimeSeriesConfiguration();
config.collections.set("users", timeSeriesCollectionConfiguration);
config.policyCheckFrequencyInMs = 1_000;
await store.maintenance.send(new ConfigureTimeSeriesOperation(config));
await store.timeSeries.register(User, StockPrice);
const total = TimeValue.ofDays(12).value;
const baseLine = moment().utc().startOf("month").add(-12, "days");
{
const session = store.openSession();
const user = new User();
user.name = "Karmel";
await session.store(user, "users/karmel");
const ts = session.timeSeriesFor("users/karmel", StockPrice);
const entry = new StockPrice();
let baseTime = baseLine.toDate().getTime();
for (let i = 0; i <= total; i++) {
entry.open = i;
entry.close = i + 100_000;
entry.high = i + 200_000;
entry.low = i + 300_000;
entry.volume = i + 400_000;
baseTime += 60 * 1000;
ts.append(new Date(baseTime), entry, "watches/fitbit");
}
await session.saveChanges();
}
await delay(2_000); // wait for rollups
{
const session = store.openSession();
const ts = session.timeSeriesRollupFor("users/karmel", p1.name, StockPrice);
let res = await ts.get();
assertThat(res)
.hasSize(16);
// should not go to server
res = await ts.get(baseLine.toDate(), baseLine.clone().add(1, "year").toDate());
assertThat(res)
.hasSize(16);
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
}
});
it("canIncludeTypedTimeSeries_Rollup", async function () {
const raw = new RawTimeSeriesPolicy(TimeValue.ofHours(24));
const p1 = new TimeSeriesPolicy("By6Hours", TimeValue.ofHours(6), TimeValue.ofDays(4));
const p2 = new TimeSeriesPolicy("By1Day", TimeValue.ofDays(1), TimeValue.ofDays(5));
const p3 = new TimeSeriesPolicy("By30Minutes", TimeValue.ofMinutes(30), TimeValue.ofDays(2));
const p4 = new TimeSeriesPolicy("By1Hour", TimeValue.ofMinutes(60), TimeValue.ofDays(3));
const timeSeriesCollectionConfiguration = new TimeSeriesCollectionConfiguration();
timeSeriesCollectionConfiguration.rawPolicy = raw;
timeSeriesCollectionConfiguration.policies = [ p1, p2, p3, p4 ];
const config = new TimeSeriesConfiguration();
config.collections.set("users", timeSeriesCollectionConfiguration);
config.policyCheckFrequencyInMs = 1_000;
await store.maintenance.send(new ConfigureTimeSeriesOperation(config));
await store.timeSeries.register(User, StockPrice);
const total = TimeValue.ofDays(12).value;
const baseLine = moment().utc().startOf("month").add(-12, "days");
{
const session = store.openSession();
const user = new User();
user.name = "Karmel";
await session.store(user, "users/karmel");
const ts = session.timeSeriesFor("users/karmel", StockPrice);
const entry = new StockPrice();
for (let i = 0; i <= total; i++) {
entry.open = i;
entry.close = i + 100_000;
entry.high = i + 200_000;
entry.low = i + 300_000;
entry.volume = i + 400_000;
ts.append(baseLine.clone().add(i, "minutes").toDate(), entry, "watches/fitbit");
}
await session.saveChanges();
}
await delay(2_000); // wait for rollups
{
const session = store.openSession();
const user = await session.query(User)
.include(i => i.includeTimeSeries("stockPrices@" + p1.name))
.first();
// should not go to server
const res = await session.timeSeriesRollupFor(user.id, p1.name, StockPrice).get();
assertThat(res)
.hasSize(16);
assertThat(session.advanced.numberOfRequests)
.isEqualTo(1);
}
});
});
class HeartRateMeasure {
public static readonly TIME_SERIES_VALUES: TimeSeriesValue<HeartRateMeasure> = ["heartRate"];
public heartRate: number;
public static create(heartRate: number) {
const heartRateMeasure = new HeartRateMeasure();
heartRateMeasure.heartRate = heartRate;
return heartRateMeasure;
}
} | the_stack |
/// <reference path="../../../dist/automapper-classes.d.ts" />
/// <reference path="../../../dist/automapper-interfaces.d.ts" />
/// <reference path="../../../dist/automapper-declaration.d.ts" />
var globalScope = this;
module AutoMapperJs {
'use strict';
describe('AutoMapper - Currying support', () => {
beforeEach(() => {
utils.registerTools(globalScope);
utils.registerCustomMatchers(globalScope);
});
it('should be able to use currying when calling createMap', () => {
// arrange
var fromKey = '{808D9D7F-AA89-4D07-917E-A528F055EE64}';
var toKey1 = '{B364C0A0-9E24-4424-A569-A4C14101947C}';
var toKey2 = '{1055CA5A-4FC4-44CB-B4D8-B004F43D8840}';
var source = { prop: 'Value' };
// act
var mapFromKeyCurry = automapper.createMap(fromKey);
mapFromKeyCurry(toKey1)
.forSourceMember('prop', (opts: ISourceMemberConfigurationOptions) => { opts.ignore(); });
mapFromKeyCurry(toKey2);
var result1 = automapper.map(fromKey, toKey1, source);
var result2 = automapper.map(fromKey, toKey2, source);
// assert
expect(typeof mapFromKeyCurry === 'function').toBeTruthy();
expect(result1.prop).toBeUndefined();
expect(result2.prop).toEqual(source.prop);
});
it('should be able to use currying (one parameter) when calling map', () => {
// arrange
var fromKey = 'should be able to use currying (one parameter)';
var toKey1 = 'when calling map (1)';
var toKey2 = 'when calling map (2)';
var source = { prop: 'Value' };
// act
var createMapFromKeyCurry = automapper.createMap(fromKey);
createMapFromKeyCurry(toKey1)
.forSourceMember('prop', (opts: ISourceMemberConfigurationOptions) => { opts.ignore(); });
createMapFromKeyCurry(toKey2);
var result1MapCurry = automapper.map(fromKey);
var result2MapCurry = automapper.map(fromKey);
var result1 = result1MapCurry(toKey1, source);
var result2 = result2MapCurry(toKey2, source);
// assert
expect(typeof createMapFromKeyCurry === 'function').toBeTruthy();
expect(typeof result1MapCurry === 'function').toBeTruthy();
expect(typeof result2MapCurry === 'function').toBeTruthy();
expect(result1.prop).toBeUndefined();
expect(result2.prop).toEqual(source.prop);
});
it('should be able to use currying when calling map', () => {
// arrange
var fromKey = '{FC18523B-5A7C-4193-B938-B6AA2EABB37A}';
var toKey1 = '{609202F4-15F7-4512-9178-CFAF073800E1}';
var toKey2 = '{85096AE2-92FB-43D7-8FC3-EC14DDC1DFDD}';
var source = { prop: 'Value' };
// act
var createMapFromKeyCurry = automapper.createMap(fromKey);
createMapFromKeyCurry(toKey1)
.forSourceMember('prop', (opts: ISourceMemberConfigurationOptions) => { opts.ignore(); });
createMapFromKeyCurry(toKey2);
var result1MapCurry = automapper.map(fromKey, toKey1);
var result2MapCurry = automapper.map(fromKey, toKey2);
var result1 = result1MapCurry(source);
var result2 = result2MapCurry(source);
// assert
expect(typeof createMapFromKeyCurry === 'function').toBeTruthy();
expect(typeof result1MapCurry === 'function').toBeTruthy();
expect(typeof result2MapCurry === 'function').toBeTruthy();
expect(result1.prop).toBeUndefined();
expect(result2.prop).toEqual(source.prop);
});
it('should be able to use currying when calling mapAsync', (done: () => void) => {
// arrange
var fromKey = '{1CA8523C-5A7C-4193-B938-B6AA2EABB37A}';
var toKey1 = '{409212FD-15E7-4512-9178-CFAF073800EG}';
var toKey2 = '{85096AE2-92FA-43N7-8FA3-EC14DDC1DFDE}';
var source = { prop: 'Value' };
// act
var createMapFromKeyCurry = automapper.createMap(fromKey);
createMapFromKeyCurry(toKey1)
.forSourceMember('prop', (opts: ISourceMemberConfigurationOptions, cb: IMemberCallback) => { cb('Constant Value 1'); });
createMapFromKeyCurry(toKey2)
.forMember('prop', (opts: IMemberConfigurationOptions, cb: IMemberCallback) => { cb('Constant Value 2'); });
var result1MapCurry = automapper.mapAsync(fromKey, toKey1);
var result2MapCurry = automapper.mapAsync(fromKey, toKey2);
// assert
expect(typeof createMapFromKeyCurry === 'function').toBeTruthy();
expect(typeof result1MapCurry === 'function').toBeTruthy();
expect(typeof result2MapCurry === 'function').toBeTruthy();
var resCount = 0;
var result1 = result1MapCurry(source, (result: any) => {
// assert
expect(result.prop).toEqual('Constant Value 1');
if (++resCount === 2) {
done();
}
});
var result2 = result2MapCurry(source, (result: any) => {
// assert
expect(result.prop).toEqual('Constant Value 2');
if (++resCount === 2) {
done();
}
});
});
it('should be able to use currying when calling mapAsync with one parameter', (done: () => void) => {
// arrange
var fromKey = '{1CA8523C-5AVC-4193-BS38-B6AA2EABB37A}';
var toKey = '{409212FD-1527-4512-9178-CFAG073800EG}';
var source = { prop: 'Value' };
// act
automapper.createMap(fromKey, toKey)
.forSourceMember('prop', (opts: ISourceMemberConfigurationOptions, cb: IMemberCallback) => { cb('Constant Value'); });
var mapAsyncCurry = automapper.mapAsync(fromKey);
// assert
expect(typeof mapAsyncCurry === 'function').toBeTruthy();
var result = mapAsyncCurry(toKey, source, (result: any) => {
// assert
expect(result.prop).toEqual('Constant Value');
done();
});
});
it('should be able to use currying when calling mapAsync with two parameters', (done: () => void) => {
// arrange
var fromKey = '{1CA852SC-5AVC-4193-BS38-B6AA2KABB3LA}';
var toKey = '{409212FD-1Q27-45G2-9178-CFAG073800EG}';
var source = { prop: 'Value' };
// act
automapper.createMap(fromKey, toKey)
.forMember('prop', (opts: IMemberConfigurationOptions, cb: IMemberCallback) => { cb('Constant Value'); });
var mapAsyncCurry = automapper.mapAsync(fromKey, toKey);
// assert
expect(typeof mapAsyncCurry === 'function').toBeTruthy();
var result = mapAsyncCurry(source, (result: any) => {
// assert
expect(result.prop).toEqual('Constant Value');
done();
});
});
it('should be able to use currying when calling mapAsync with three parameters', (done: () => void) => {
// NOTE BL 20151214 I wonder why anyone would like calling this one? Maybe this one will be removed in
// the future. Please get in touch if you need this one to stay in place...
// arrange
var fromKey = '{1CA852SC-5AVC-ZZ93-BS38-B6AA2KABB3LA}';
var toKey = '{409212FD-1Q27-45G2-91BB-CFAG0738WCEG}';
var source = { prop: 'Value' };
// act
automapper.createMap(fromKey, toKey)
.forMember('prop', (opts: IMemberConfigurationOptions, cb: IMemberCallback) => { cb('Constant Value'); });
var mapAsyncCurry = automapper.mapAsync(fromKey, toKey, source);
// assert
expect(typeof mapAsyncCurry === 'function').toBeTruthy();
var result = mapAsyncCurry((result: any) => {
// assert
expect(result.prop).toEqual('Constant Value');
done();
});
});
it('should fail when calling mapAsync without parameters', () => {
// arrange
// act
try {
var mapAsyncCurry = (<any>automapper).mapAsync();
} catch (e) {
// assert
expect(e.message).toEqual('The mapAsync function expects between 1 and 4 parameters, you provided 0.');
return;
}
// assert
expect(null).fail('Expected error was not raised.');
});
it('should fail when calling mapAsync with > 4 parameters', () => {
// arrange
// act
try {
var mapAsyncCurry = (<any>automapper).mapAsync(undefined, undefined, undefined, undefined, undefined);
} catch (e) {
// assert
expect(e.message).toEqual('The mapAsync function expects between 1 and 4 parameters, you provided 5.');
return;
}
// assert
expect(null).fail('Expected error was not raised.');
});
it('should fail when specifying < 2 parameters to the asynchronous map function', () => {
// arrange
// act
try {
(<any>new AsyncAutoMapper()).map(undefined);
} catch (e) {
// assert
expect(e.message).toEqual('The AsyncAutoMapper.map function expects between 2 and 5 parameters, you provided 1.');
return;
}
// assert
expect(null).fail('Expected error was not raised.');
});
it('should fail when specifying > 5 parameters to the asynchronous map function', () => {
// arrange
// act
try {
(<any>new AsyncAutoMapper()).map(undefined, undefined, undefined, undefined, undefined, undefined);
} catch (e) {
// assert
expect(e.message).toEqual('The AsyncAutoMapper.map function expects between 2 and 5 parameters, you provided 6.');
return;
}
// assert
expect(null).fail('Expected error was not raised.');
});
});
} | the_stack |
import { Promise } from "bluebird";
import { async as createSubject } from "most-subject";
import * as lodashClone from "lodash.clone";
import * as lodashCloneDeep from "lodash.clonedeep";
import { StreamDSL } from "./StreamDSL";
import { messageProduceHandle } from "../messageProduceHandle";
import { Window } from "../actions";
const NOOP = () => { };
/**
* change-log representation of a stream
*/
export class KStream extends StreamDSL {
public started: any;
/**
* creates a changelog representation of a stream
* join operations of kstream instances are synchronous
* and return new instances immediately
* @param {string} topicName
* @param {KStorage} storage
* @param {KafkaClient} kafka
* @param {boolean} isClone
*/
constructor(topicName, storage = null, kafka = null, isClone = false) {
super(topicName, storage, kafka, isClone);
this.started = false;
//readability
if (isClone) {
this.started = true;
}
}
/**
* start kafka consumption
* prepare production of messages if necessary
* when called with zero or just a single callback argument
* this function will return a promise and use the callback for errors
* @param {function|Object} kafkaReadyCallback - can also be an object (config)
* @param {function} kafkaErrorCallback
* @param {boolean} withBackPressure
* @param {Object} outputKafkaConfig
*/
start(kafkaReadyCallback = null, kafkaErrorCallback = null, withBackPressure = false, outputKafkaConfig = null) {
if (kafkaReadyCallback && typeof kafkaReadyCallback === "object" && arguments.length < 2) {
return new Promise((resolve, reject) => {
this._start(resolve, reject, kafkaReadyCallback.withBackPressure, kafkaReadyCallback.outputKafkaConfig);
});
}
if (arguments.length < 2) {
return new Promise((resolve, reject) => {
this._start(resolve, reject, withBackPressure);
});
}
return this._start(kafkaReadyCallback, kafkaErrorCallback, withBackPressure, outputKafkaConfig);
}
_start(kafkaReadyCallback = null, kafkaErrorCallback = null, withBackPressure = false, outputKafkaConfig = null) {
if (this.started) {
throw new Error("this KStream is already started.");
}
this.started = true;
if (this.noTopicProvided && !this.produceAsTopic) {
return kafkaReadyCallback();
}
let producerReady = false;
let consumerReady = false;
const onReady = (type) => {
switch (type) {
case "producer": producerReady = true; break;
case "consumer": consumerReady = true; break;
}
//consumer && producer
if (producerReady && consumerReady && kafkaReadyCallback) {
kafkaReadyCallback();
}
//consumer only
if (!this.produceAsTopic && consumerReady && kafkaReadyCallback) {
kafkaReadyCallback();
}
//producer only
if (this.produceAsTopic && producerReady && kafkaReadyCallback && !this.kafka.topic || !this.kafka.topic.length) {
kafkaReadyCallback();
}
};
//overwrite kafka topics
this.kafka.overwriteTopics(this.topicName);
this.kafka.on("message", msg => super.writeToStream(msg));
this.kafka.start(() => { onReady("consumer"); }, kafkaErrorCallback || NOOP, this.produceAsTopic, withBackPressure);
if (this.produceAsTopic) {
this.kafka.setupProducer(this.outputTopicName, this.outputPartitionsCount, () => { onReady("producer"); },
kafkaErrorCallback, outputKafkaConfig);
super.forEach(message => {
messageProduceHandle(
this.kafka,
message,
this.outputTopicName,
this.produceType,
this.produceCompressionType,
this.produceVersion,
kafkaErrorCallback
);
});
}
}
/**
* Emits an output when both input sources have records with the same key.
* s1$:{object} + s2$:{object} -> j$:{left: s1$object, right: s2$object}
* @param {StreamDSL} stream
* @param {string} key
* @param {boolean} windowed
* @param {function} combine
* @returns {KStream}
*/
innerJoin(stream, key = "key", windowed = false, combine = null) {
let join$ = null;
if (!windowed) {
join$ = this._innerJoinNoWindow(stream, key, combine);
} else {
throw new Error("not implemented yet."); //TODO implement
}
return this._cloneWith(join$);
}
_innerJoinNoWindow(stream, key, combine) {
const existingKeyFilter = (event) => {
return !!event && typeof event === "object" && typeof event[key] !== "undefined";
};
const melt = (left, right) => {
return {
left,
right
};
};
const parent$ = super.multicast().stream$.filter(existingKeyFilter);
const side$ = stream.multicast().stream$.filter(existingKeyFilter);
return parent$.zip(combine || melt, side$);
}
/**
* Emits an output for each record in either input source.
* If only one source contains a key, the other is null
* @param {StreamDSL} stream
*/
outerJoin(stream) {
throw new Error("not implemented yet."); //TODO implement
}
/**
* Emits an output for each record in the left or primary input source.
* If the other source does not have a value for a given key, it is set to null
* @param {StreamDSL} stream
*/
leftJoin(stream) {
throw new Error("not implemented yet."); //TODO implement
}
/**
* Emits an output for each record in any of the streams.
* Acts as simple merge of both streams.
* can be used with KStream or KTable instances
* returns a NEW KStream instance
* @param {StreamDSL} stream
* @returns {KStream}
*/
merge(stream) {
if (!(stream instanceof StreamDSL)) {
throw new Error("stream has to be an instance of KStream or KTable.");
}
// multicast prevents replays
// create a new internal stream that merges both KStream.stream$s
const newStream$ = this.stream$.multicast().merge(stream.stream$.multicast());
return this._cloneWith(newStream$);
}
_cloneWith(newStream$) {
const kafkaStreams = this._kafkaStreams;
if (!kafkaStreams) {
throw new Error("merging requires a kafka streams reference on the left-hand merger.");
}
const newStorage = kafkaStreams.getStorage();
const newKafkaClient = kafkaStreams.getKafkaClient();
const newInstance = new KStream(null, newStorage, newKafkaClient, true);
newInstance.replaceInternalObservable(newStream$);
newInstance._kafkaStreams = kafkaStreams;
return newInstance;
}
/**
* creates a new KStream instance from a given most.js
* stream; the consume topic will be empty and therefore
* no consumer will be build
* @param {Object} most.js stream
* @returns {KStream}
*/
fromMost(stream$) {
return this._cloneWith(stream$);
}
/**
* as only joins and window operations return new stream instances
* you might need a clone sometimes, which can be accomplished
* using this function
* @param {boolean} cloneEvents - if events in the stream should be cloned
* @param {boolean} cloneDeep - if events in the stream should be cloned deeply
* @returns {KStream}
*/
clone(cloneEvents = false, cloneDeep = false) {
let clone$ = this.stream$.multicast();
if (cloneEvents) {
clone$ = clone$.map((event) => {
if (!cloneDeep) {
return lodashClone(event);
}
return lodashCloneDeep(event);
});
}
return this._cloneWith(clone$);
}
/**
* Splits a stream into multiple branches based on cloning
* and filtering it depending on the passed predicates.
* [ (message) => message.key.startsWith("A"),
* (message) => message.key.startsWith("B"),
* (message) => true ]
* ---
* [ streamA, streamB, streamTrue ]
* @param {Array<Function>} preds
* @returns {Array<KStream>}
*/
branch(preds = []) {
if (!Array.isArray(preds)) {
throw new Error("branch predicates must be an array.");
}
return preds.map((pred) => {
if (typeof pred !== "function") {
throw new Error(`branch predicates must be an array of functions: ${pred}`);
}
return this.clone(true, true).filter(pred);
});
}
/**
* builds a window'ed stream across all events of the current kstream
* when the first event with an exceeding "to" is received (or the abort()
* callback is called) the window closes and emits its "collected" values to the
* returned kstream
* from and to must be unix epoch timestamps in milliseconds (Date.now())
* etl can be a function that should return the timestamp (event time) of
* from within the message e.g. m -> m.payload.createdAt
* if etl is not given, a timestamp of receiving will be used (processing time)
* for each event
* encapsulated refers to the result messages (defaults to true, they will be
* encapsulated in an object: {time, value}
* @param {number} from
* @param {number} to
* @param {function} etl
* @param {boolean} encapsulated - if event should stay encapsulated {time, value}
* @param {boolean} collect - if events should be collected first before publishing to result stream
* @returns {{window: *, abort: abort, stream: *}}
*/
window(from, to, etl = null, encapsulated = true, collect = true) {
if (typeof from !== "number" || typeof to !== "number") {
throw new Error("from & to should be unix epoch ms times.");
}
//use this.stream$ as base, but work on a new one
let stream$ = null;
if (!etl) {
stream$ = this.stream$.timestamp();
} else {
stream$ = this.stream$.map(element => {
return {
time: etl(element),
value: element
};
});
}
let aborted = false;
const abort$ = createSubject();
function abort() {
if (aborted) {
return;
}
aborted = true;
abort$.next(null);
}
const window = new Window([], collect);
const window$ = window.getStream();
stream$
.skipWhile(event => event.time < from)
.takeWhile(event => event.time < to)
.until(abort$)
.tap(event => window.execute(event, encapsulated))
.drain().then(_ => {
window.writeToStream();
window.flush();
})
.catch((error) => {
window$.error(error);
});
return {
window,
abort,
stream: this._cloneWith(window$)
};
}
/**
* closes the internal stream
* and all kafka open connections
* as well as KStorage connections
* @returns {Promise.<boolean>}
*/
close() {
this.stream$ = this.stream$.take(0);
this.stream$ = null;
this.kafka.close();
return this.storage.close();
}
} | the_stack |
import * as path from "path";
import * as vscode from "vscode";
import * as mkdirp from 'mkdirp';
import * as fs from 'fs';
import { denodeify } from 'q';
import { WidgetResolver } from "./resolvers/widget-resolver";
import { ParseXml } from "./parser/parser";
import { PropertyHandlerProvider } from "./providers/property-handler-provider";
import { WrapperPropertyHandler } from "./property-handlers/wrapper-property";
import { ChildWrapperPropertyHandler } from "./property-handlers/child-wrapper-property";
import { ValueTransformersProvider, IValueTransformer } from "./providers/value-transformers-provider";
import { EnumValueTransformer } from "./value-transformers/enum";
import { EdgeInsetsValueTransformer } from "./value-transformers/edge-insets";
import { ColorValueTransformer } from "./value-transformers/color";
import { LocalizationGenerator } from "./generators/localization-generator";
import { ClassCodeGenerator } from "./generators/class-generator";
import { WidgetCodeGenerator } from "./generators/widget-generator";
import { insertAutoCloseTag } from "./autoclose/autoclose";
import { Config, ConfigValueTransformer } from "./models/config";
import { registerBuiltInValueTransformers, registerBuiltInPropertyHandlers } from "./builtin-handlers";
import { PropertyResolver } from "./resolvers/property-resolver";
import { PipeValueResolver } from "./resolvers/pipe-value-resolver";
const mkdir = denodeify(mkdirp);
const writeFile = denodeify(fs.writeFile);
const readFile = denodeify(fs.readFile);
const readDir = denodeify(fs.readdir);
// const exists = denodeify(fs.exists);
const existsSync = fs.existsSync;
export default class Manager {
public readonly propertyResolver: PropertyResolver;
private readonly pipeValueResolver: PipeValueResolver;
private readonly resolver: WidgetResolver;
public readonly propertyHandlersProvider: PropertyHandlerProvider;
private readonly valueTransformersProvider: ValueTransformersProvider;
private readonly classGenerator: ClassCodeGenerator;
private readonly output: vscode.OutputChannel;
constructor(config: Config,
private readonly diagnostics: vscode.DiagnosticCollection) {
this.pipeValueResolver = new PipeValueResolver();
this.propertyHandlersProvider = new PropertyHandlerProvider();
this.propertyResolver = new PropertyResolver(config, this.propertyHandlersProvider, this.pipeValueResolver);
this.valueTransformersProvider = new ValueTransformersProvider();
this.resolver = new WidgetResolver(config, this.propertyHandlersProvider, this.propertyResolver);
const widgetGenerator = new WidgetCodeGenerator(this.propertyHandlersProvider);
this.classGenerator = new ClassCodeGenerator(widgetGenerator);
registerBuiltInPropertyHandlers(this.propertyHandlersProvider, this.propertyResolver);
registerBuiltInValueTransformers(this.valueTransformersProvider);
this.applyConfig(config);
this.output = vscode.window.createOutputChannel('Flutter XML Layout');
vscode.workspace.onDidSaveTextDocument(async (document) => {
if (this.isI18nJsonFile(document.languageId)) {
const isValidOptionsFile = path.join((vscode.workspace.workspaceFolders as vscode.WorkspaceFolder[])[0].uri.fsPath, 'fxmllayout.json') === document.fileName;
if (isValidOptionsFile) {
const newConfig = JSON.parse(document.getText());
this.applyConfig(newConfig, config);
await this.regenerateAll();
}
else {
await this.generateLocalizationFiles();
}
}
else if (this.isFxmlFile(document.languageId)) {
await this.generateWidgetDartFile(document.fileName, document.getText());
}
});
// autoclose tags
vscode.workspace.onDidChangeTextDocument(event => {
if (this.isFxmlFile(event.document.languageId)) {
insertAutoCloseTag(event);
}
});
}
private applyConfig(config: Config, original?: Config) {
if (config.wrappers) {
if (original) {
if (original.wrappers) {
const removed = original.wrappers.filter(a => (config.wrappers as any[]).filter(b => b.name === a.properties[0].handler).length);
removed.forEach(a => this.propertyHandlersProvider.remove(a.properties.map(a => a.handler)));
}
}
config.wrappers
.filter(p => p.properties[0] && p.widget)
.forEach(p => {
this.propertyHandlersProvider.register(
p.properties.map(a => a.handler),
new WrapperPropertyHandler(this.propertyResolver, p.properties, p.widget, p.defaults, p.priority !== undefined && p.priority !== null ? p.priority : 100));
});
}
if (config.childWrappers) {
if (original) {
if (original.childWrappers) {
const removed = original.childWrappers.filter(a => (config.childWrappers as any[]).filter(b => b.name === a.properties[0].handler).length);
removed.forEach(a => this.propertyHandlersProvider.remove(a.properties.map(a => a.handler)));
}
}
config.childWrappers
.filter(p => p.properties[0] && p.widget)
.forEach(p => {
this.propertyHandlersProvider.register(
p.properties.map(a => a.handler),
new ChildWrapperPropertyHandler(this.propertyResolver, p.properties, p.widget, p.defaults, p.priority !== undefined && p.priority !== null ? p.priority : 100));
});
}
if (config.valueTransformers) {
if (original) {
if (original.valueTransformers) {
// todo
// const removed = original.valueTransformers.filter(a => (config.valueTransformers as any[]).filter(b => b.name === a.name).length);
// removed.forEach(a => this.propertyHandlerProvider.remove(a.name));
}
}
config.valueTransformers.filter(p => p.properties && p.properties.length && p.type).forEach(p => {
const transformer = this.createValueTransformer(p);
if (transformer) {
this.valueTransformersProvider.register(p.properties, transformer);
}
});
}
if (original) {
original.unnamedProperties = config.unnamedProperties;
original.arrayProperties = config.arrayProperties;
original.childWrappers = config.childWrappers;
original.valueTransformers = config.valueTransformers;
original.wrappers = config.wrappers;
}
}
private createValueTransformer(p: ConfigValueTransformer): IValueTransformer | null {
switch (p.type) {
case 'enum': return p.enumType ? new EnumValueTransformer(p.enumType) : null;
case 'color': return new ColorValueTransformer();
case 'edgeInsets': return new EdgeInsetsValueTransformer();
default: return null;
}
}
private isFxmlFile(id: string): boolean {
return /*id === 'fxml' ||*/ id === 'xml';
}
async generateWidgetDartFile(docName: string, xml: string, notifyUpdate = true) {
const rootPath = (vscode.workspace.workspaceFolders as any[])[0].uri.fsPath;
if (!docName.startsWith(path.join(rootPath, 'lib'))) {
return;
}
const filePath = docName.substring(0, docName.lastIndexOf('.'));
const controllerFilePath = filePath + '.ctrl.dart';
const controllerFileName = path.parse(controllerFilePath).base;
let layoutDart, rootWidget;
const fileUri = vscode.Uri.file(filePath + '.xml');
this.diagnostics.set(fileUri, []);
try {
const parser: ParseXml = new ParseXml();
const xmlDoc = parser.parse(xml);
rootWidget = this.resolver.resolve(xmlDoc);
layoutDart = this.classGenerator.generate(rootWidget, controllerFileName);
}
catch (ex) {
const diagnostic = this.getExceptionDiagnostics(ex.message);
if (diagnostic) {
this.diagnostics.set(fileUri, [diagnostic]);
}
const customMessage = this.getCustomErrorMessage(ex.message);
if (customMessage) {
vscode.window.showErrorMessage(customMessage);
this.output.appendLine(customMessage);
return;
}
else {
vscode.window.showErrorMessage('Please check the XML structure.');
this.output.appendLine('Error parsing XML file.');
throw ex;
}
}
if (!rootWidget) {
return;
}
const layoutFileName = docName + '.dart';
await writeFile(layoutFileName, layoutDart);
try {
if (rootWidget.controller && !existsSync(controllerFilePath)) {
const fileName = path.parse(filePath).base;
const controllerDart = this.classGenerator.generateControllerFile(fileName, rootWidget);
if (!!controllerDart) {
await writeFile(controllerFilePath, controllerDart);
}
}
}
catch {
}
this.output.appendLine('XML converted to Dart code.');
if (notifyUpdate) {
await this.notifyUpdate();
}
}
private getExceptionDiagnostics(message: string): vscode.Diagnostic {
const lineIndex = message.indexOf('line ');
const colIndex = message.indexOf('column ');
if (lineIndex !== -1 && colIndex !== -1) {
const line = +message.substring(lineIndex + 5, message.indexOf(',', lineIndex)) - 1;
const col = +message.substring(colIndex + 7, message.indexOf(')', colIndex)) - 1;
const position = new vscode.Position(line, col);
return new vscode.Diagnostic(
new vscode.Range(position, position.translate({ characterDelta: 1000 })),
message.substring(0, lineIndex - 2));
}
return null;
}
private getCustomErrorMessage(error: string): string {
if (error.startsWith('::')) {
return error.substring(2);
}
else if (error.startsWith('Attribute') && error.indexOf(' redefined ') !== -1) {
return error.replace('^', '');
}
return null;
}
async generateWidgetDartFiles() {
const files = await vscode.workspace.findFiles('**/*.xml');
for (const file of files) {
const xml = await readFile(file.fsPath, 'utf8') as string;
await this.generateWidgetDartFile(file.fsPath, xml, false);
}
await this.notifyUpdate();
}
private async notifyUpdate() {
if (vscode.debug.activeDebugSession) {
await vscode.commands.executeCommand('flutter.hotReload');
}
}
private isI18nJsonFile(id: string): boolean {
return id === 'json';
}
async generateLocalizationFiles() {
const jsonDirPath = path.join((vscode.workspace.workspaceFolders as vscode.WorkspaceFolder[])[0].uri.fsPath, 'lib', 'i18n');
if (!existsSync(jsonDirPath)) {
return;
}
const langs: any = {};
// read all other lang.json files then add them to langs[langCode] = json;
let files: any = await readDir(jsonDirPath);
files = files.filter((f: string) => f.endsWith('.json'));
for (const file of files) {
const code = file.substring(0, file.lastIndexOf('.'));
const json = await readFile(path.join(jsonDirPath, file), 'utf8');
langs[code] = json;
}
// generate files
const genDirPath = path.join(jsonDirPath, 'gen');
const localizationFilePath = path.join(genDirPath, 'localizations.dart');
await mkdir(genDirPath);
const generator = new LocalizationGenerator();
const localizationCode = generator.generateLocalization(langs);
await writeFile(localizationFilePath, localizationCode);
// generated if not exists
const delegateFilePath = path.join(genDirPath, 'delegate.dart');
// if (!existsSync(delegateFilePath)) {
const supportedLangs: string[] = Object.keys(langs);
const delegateCode = generator.generateDelegate(supportedLangs);
await writeFile(delegateFilePath, delegateCode);
// }
}
async regenerateAll() {
await this.generateWidgetDartFiles();
await this.generateLocalizationFiles();
this.output.appendLine('Re-generate operation succeeded.');
}
} | the_stack |
import { ImageSource } from '@nativescript/core';
import { Canvas, ImageAsset, Path2D } from '@nativescript/canvas';
import { Screen } from '@nativescript/core';
import { doesNotReject } from 'assert';
export function fillStyle(canvas) {
const ctx = canvas.getContext('2d');
for (let i = 0; i < 6; i++) {
for (let j = 0; j < 6; j++) {
ctx.fillStyle = `rgb(
${Math.floor(255 - 42.5 * i)},
${Math.floor(255 - 42.5 * j)},
0)`;
ctx.fillRect(j * 25, i * 25, 25, 25);
}
}
}
export function font(canvas) {
const ctx = canvas.getContext('2d');
ctx.font = 'bold 48px serif';
ctx.strokeText('Hello world', 50, 100);
}
export function globalAlpha(canvas) {
const ctx = canvas.getContext('2d');
ctx.globalAlpha = 0.5;
ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 100, 100);
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 100);
}
export function globalCompositeOperation(canvas) {
const ctx = canvas.getContext('2d');
ctx.globalCompositeOperation = 'xor';
ctx.fillStyle = 'blue';
ctx.fillRect(10, 10, 100, 100);
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 100);
}
export function imageSmoothingEnabled(canvas) {
const ctx = canvas.getContext('2d');
ctx.font = '16px sans-serif';
ctx.textAlign = 'center';
const src = ImageSource.fromUrl('https://interactive-examples.mdn.mozilla.net/media/examples/star.png');
src.then(img => {
const w = img.width,
h = img.height;
ctx.fillText('Source', w * .5, 20);
ctx.drawImage(img, 0, 24, w, h);
ctx.fillText('Smoothing = TRUE', w * 2.5, 20);
ctx.imageSmoothingEnabled = true;
ctx.drawImage(img, w, 24, w * 3, h * 3);
ctx.fillText('Smoothing = FALSE', w * 5.5, 20);
ctx.imageSmoothingEnabled = false;
ctx.drawImage(img, w * 4, 24, w * 3, h * 3);
});
}
export function imageSmoothingQuality(canvas) {
const ctx = canvas.getContext('2d');
ImageSource.fromUrl('https://mdn.mozillademos.org/files/222/Canvas_createpattern.png')
.then(function (img) {
ctx.imageSmoothingQuality = 'low';
ctx.drawImage(img.ios, 0, 0, 300, 150);
});
}
export function imageBlock(canvas) {
const ctx = canvas.getContext('2d');
ctx.save();
const asset = new ImageAsset();
asset.loadFromUrlAsync('https://mdn.mozillademos.org/files/5397/rhino.jpg')
.then(done => {
for (var i = 0; i < 4; i++) {
for (var j = 0; j < 3; j++) {
ctx.drawImage(asset, (j * 50) * Screen.mainScreen.scale, (i * 38) * Screen.mainScreen.scale, 50 * Screen.mainScreen.scale, 38 * Screen.mainScreen.scale);
}
}
});
}
export function lineCap(canvas) {
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineWidth = 15;
ctx.lineCap = 'round';
ctx.lineTo(100, 100);
ctx.stroke();
}
export function lineDashOffset(canvas) {
const ctx = canvas.getContext('2d');
ctx.setLineDash([4, 16]);
// Dashed line with no offset
ctx.beginPath();
ctx.moveTo(0, 50);
ctx.lineTo(300, 50);
ctx.stroke();
// Dashed line with offset of 4
ctx.beginPath();
ctx.strokeStyle = 'red';
ctx.lineDashOffset = 4;
ctx.moveTo(0, 100);
ctx.lineTo(300, 100);
ctx.stroke();
}
export function lineJoin(canvas) {
const ctx = canvas.getContext('2d');
ctx.lineWidth = 20;
ctx.lineJoin = 'round';
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(190, 100);
ctx.lineTo(280, 20);
ctx.lineTo(280, 150);
ctx.stroke();
}
export function lineWidth(canvas) {
const ctx = canvas.getContext('2d');
ctx.lineWidth = 15;
ctx.beginPath();
ctx.moveTo(20, 20);
ctx.lineTo(130, 130);
ctx.rect(40, 40, 70, 70);
ctx.stroke();
}
export function shadowBlur(canvas) {
const ctx = canvas.getContext('2d');
ctx.shadowBlur = 3;
ctx.shadowColor = 'rgba(0, 0, 0, 0.5)';
ctx.shadowOffsetX = 3;
ctx.shadowOffsetY = 6;
ctx.beginPath();
ctx.arc(50, 50, 30, 0, 2 * Math.PI);
ctx.stroke();
ctx.fillStyle = 'red';
ctx.fillRect(100, 20, 30, 30);
}
export function miterLimit(canvas) {
const ctx = canvas.getContext('2d');
// Clear canvas
ctx.clearRect(0, 0, 150, 150);
// Draw guides
ctx.strokeStyle = '#09f';
ctx.lineWidth = 2;
ctx.strokeRect(-5, 50, 160, 50);
// Set line styles
ctx.strokeStyle = '#000';
ctx.lineWidth = 10;
ctx.miterLimit = 10;
// Draw lines
ctx.beginPath();
ctx.moveTo(0, 100);
for (let i = 0; i < 24; i++) {
var dy = i % 2 == 0 ? 25 : -25;
ctx.lineTo(Math.pow(i, 1.5) * 2, 75 + dy);
}
ctx.stroke();
}
export function filterBlur(canvas){
const ctx = canvas.getContext('2d');
ctx.filter = 'blur(4px)';
ctx.font = '48px serif';
ctx.fillText('Hello world', 50, 100);
}
export function shadowColor(canvas) {
const ctx = canvas.getContext('2d');
// Shadow
ctx.shadowColor = 'red';
ctx.shadowOffsetX = 10;
ctx.shadowOffsetY = 10;
// remove after release
ctx.shadowBlur = 1;
// Filled rectangle
ctx.fillRect(20, 20, 100, 100);
// Stroked rectangle
ctx.lineWidth = 6;
ctx.strokeRect(170, 20, 100, 100);
}
export function shadowOffsetX(canvas) {
const ctx = canvas.getContext('2d');
// Shadow
ctx.shadowColor = 'red';
ctx.shadowOffsetX = 25;
ctx.shadowBlur = 10;
// Rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(20, 20, 150, 100);
}
export function shadowOffsetY(canvas) {
const ctx = canvas.getContext('2d');
// Shadow
ctx.shadowColor = 'red';
ctx.shadowOffsetY = 25;
ctx.shadowBlur = 10;
// Rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(20, 20, 150, 80);
}
export function strokeStyle(canvas) {
const ctx = canvas.getContext('2d');
ctx.strokeStyle = 'blue';
ctx.strokeRect(10, 10, 100, 100);
}
export function multiStrokeStyle(canvas) {
const ctx = canvas.getContext('2d');
for (let i = 0; i < 6; i++) {
for (let j = 0; j < 6; j++) {
ctx.strokeStyle = `rgb(
0,
${Math.floor(255 - 42.5 * i)},
${Math.floor(255 - 42.5 * j)})`;
ctx.beginPath();
ctx.arc(12.5 + j * 25, 12.5 + i * 25, 10, 0, Math.PI * 2, true);
ctx.stroke();
}
}
}
export function textAlign(canvas) {
const ctx = canvas.getContext('2d');
canvas.width = 350;
const x = canvas.width / 2;
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, canvas.height);
ctx.stroke();
ctx.font = '30px serif';
ctx.textAlign = 'left';
ctx.fillText('left-aligned', x, 40);
ctx.textAlign = 'center';
ctx.fillText('center-aligned', x, 85);
ctx.textAlign = 'right';
ctx.fillText('right-aligned', x, 130);
}
export function arc(canvas) {
const ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(100, 75, 50, 0, 2 * Math.PI);
ctx.stroke();
}
export function arcMultiple(canvas) {
const ctx = canvas.getContext('2d');
// Draw shapes
for (let i = 0; i <= 3; i++) {
for (let j = 0; j <= 2; j++) {
ctx.beginPath();
let x = 25 + j * 50; // x coordinate
let y = 25 + i * 50; // y coordinate
let radius = 20; // Arc radius
let startAngle = 0; // Starting point on circle
let endAngle = Math.PI + (Math.PI * j) / 2; // End point on circle
let anticlockwise = i % 2 == 1; // Draw anticlockwise
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
if (i > 1) {
ctx.fill();
} else {
ctx.stroke();
}
}
}
}
export function arcTo(canvas) {
const ctx = canvas.getContext('2d');
// Tangential lines
ctx.beginPath();
ctx.strokeStyle = 'gray';
ctx.moveTo(200, 20);
ctx.lineTo(200, 130);
ctx.lineTo(50, 20);
ctx.stroke();
// Arc
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.lineWidth = 5;
ctx.moveTo(200, 20);
ctx.arcTo(200, 130, 50, 20, 40);
ctx.stroke();
// Start point
ctx.beginPath();
ctx.fillStyle = 'blue';
ctx.arc(200, 20, 5, 0, 2 * Math.PI);
ctx.fill();
// Control points
ctx.beginPath();
ctx.fillStyle = 'red';
ctx.arc(200, 130, 5, 0, 2 * Math.PI); // Control point one
ctx.arc(50, 20, 5, 0, 2 * Math.PI); // Control point two
ctx.fill();
}
export function arcToAnimation(canvas) {
const ctx = canvas.getContext('2d');
ctx.scale(3, 3);
const mouse = { x: 0, y: 0 };
let r = 100; // Radius
const p0 = { x: 0, y: 50 };
const p1 = { x: 100, y: 100 };
const p2 = { x: 150, y: 50 };
const p3 = { x: 200, y: 100 };
const labelPoint = function (p, offset, i = 0) {
const { x, y } = offset;
ctx.beginPath();
ctx.arc(p.x, p.y, 2, 0, Math.PI * 2);
ctx.fill();
ctx.fillText(`${i}:(${p.x}, ${p.y})`, p.x + x, p.y + y);
};
const drawPoints = function (points) {
for (let i = 0; i < points.length; i++) {
var p = points[i];
labelPoint(p, { x: 0, y: -20 }, i);
}
};
// Draw arc
const drawArc = function ([p0, p1, p2], r) {
ctx.beginPath();
ctx.moveTo(p0.x, p0.y);
ctx.arcTo(p1.x, p1.y, p2.x, p2.y, r);
ctx.lineTo(p2.x, p2.y);
ctx.stroke();
};
let t0 = 0;
let rr = 0; // the radius that changes over time
let a = 0; // angle
let PI2 = Math.PI * 2;
const loop = function (t) {
t0 = t / 1000;
a = t0 % PI2;
rr = Math.abs(Math.cos(a) * r);
ctx.clearRect(0, 0, canvas.width, canvas.height);
drawArc([p1, p2, p3], rr);
drawPoints([p1, p2, p3]);
requestAnimationFrame(loop);
};
loop(0);
}
export function ellipse(canvas) {
const ctx = canvas.getContext('2d');
// Draw the ellipse
ctx.beginPath();
ctx.ellipse(100, 100, 50, 75, Math.PI / 4, 0, 2 * Math.PI);
ctx.stroke();
// Draw the ellipse's line of reflection
ctx.beginPath();
ctx.setLineDash([5, 5]);
ctx.moveTo(0, 200);
ctx.lineTo(200, 0);
ctx.stroke();
}
export function fill(ctx) {
}
export function fillPath(canvas) {
const ctx = canvas.getContext('2d');
// Create path
let region = new Path2D();
region.moveTo(30, 90);
region.lineTo(110, 20);
region.lineTo(240, 130);
region.lineTo(60, 130);
region.lineTo(190, 20);
region.lineTo(270, 90);
region.closePath();
// Fill path
ctx.fillStyle = 'green';
ctx.fill(region, 'evenodd');
}
export function createLinearGradient(canvas) {
const ctx = canvas.getContext('2d');
// Create a linear gradient
// The start gradient point is at x=20, y=0
// The end gradient point is at x=220, y=0
var gradient = ctx.createLinearGradient(20, 0, 220, 0);
// Add three color stops
gradient.addColorStop(0, 'green');
gradient.addColorStop(.5, 'cyan');
gradient.addColorStop(1, 'green');
// Set the fill style and draw a rectangle
ctx.fillStyle = gradient;
ctx.fillRect(20, 20, 200, 100);
}
export function createRadialGradient(canvas) {
const ctx = canvas.getContext('2d');
// Create a radial gradient
// The inner circle is at x=110, y=90, with radius=30
// The outer circle is at x=100, y=100, with radius=70
var gradient = ctx.createRadialGradient(110, 90, 30, 100, 100, 70);
// Add three color stops
gradient.addColorStop(0, 'pink');
gradient.addColorStop(.9, 'white');
gradient.addColorStop(1, 'green');
// Set the fill style and draw a rectangle
ctx.fillStyle = gradient;
ctx.fillRect(20, 20, 160, 160);
}
export function fillRule(canvas) {
const ctx = canvas.getContext('2d');
// Create path
let region = new Path2D();
region.moveTo(30, 90);
region.lineTo(110, 20);
region.lineTo(240, 130);
region.lineTo(60, 130);
region.lineTo(190, 20);
region.lineTo(270, 90);
region.closePath();
// Fill path
ctx.fillStyle = 'green';
ctx.fill(region, 'evenodd');
}
export function scale(canvas) {
const ctx = canvas.getContext('2d');
// Scaled rectangle
ctx.scale(9, 3);
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 8, 20);
// Reset current transformation matrix to the identity matrix
ctx.setTransform(1, 0, 0, 1, 0, 0);
// Non-scaled rectangle
ctx.fillStyle = 'gray';
ctx.fillRect(10, 10, 8, 20);
}
export function pattern(canvas) {
const ctx = canvas.getContext('2d');
ImageSource.fromUrl('https://mdn.mozillademos.org/files/222/Canvas_createpattern.png')
.then(function (img) {
ctx.fillStyle = ctx.createPattern(img, 'repeat');
ctx.fillRect(0, 0, 300, 300);
});
}
export function patternWithCanvas(canvas) {
const patternCanvas = Canvas.createCustomView();
const patternContext = patternCanvas.getContext('2d') as any;
// Give the pattern a width and height of 50
patternCanvas.width = 50;
patternCanvas.height = 50;
// Give the pattern a background color and draw an arc
patternContext.fillStyle = '#fec';
patternContext.fillRect(0, 0, patternCanvas.width, patternCanvas.height);
patternContext.arc(0, 0, 50, 0, .5 * Math.PI);
patternContext.stroke();
const ctx = canvas.getContext('2d');
// Create our primary canvas and fill it with the pattern
ctx.fillStyle = ctx.createPattern(patternCanvas, 'repeat');
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
}
export function clip(canvas) {
const ctx = canvas.getContext('2d');
// Create circular clipping region
ctx.beginPath();
ctx.arc(100, 75, 50, 0, Math.PI * 2);
ctx.clip();
// Draw stuff that gets clipped
ctx.fillStyle = 'blue';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'orange';
ctx.fillRect(0, 0, 100, 100);
}
export function isPointInStrokeTouch(canvas) {
const ctx = canvas.getContext('2d');
// Create ellipse
const ellipse = new Path2D();
ellipse.ellipse(150, 75, 40, 60, Math.PI * .25, 0, 2 * Math.PI);
ctx.lineWidth = 25;
ctx.strokeStyle = 'red';
ctx.fill(ellipse);
ctx.stroke(ellipse);
// Listen for mouse moves
canvas.addEventListener('touchmove', function (args) {
// Check whether point is inside ellipse's stroke
const event = args.changedTouches[0];
//console.log(event.clientX, event.clientY);
// event.offsetX, event.offsetY
if (ctx.isPointInStroke(ellipse, event.offsetX, event.offsetY)) {
ctx.strokeStyle = 'green';
} else {
ctx.strokeStyle = 'red';
}
// Draw ellipse
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fill(ellipse);
ctx.stroke(ellipse);
});
}
export function march(canvas) {
const ctx = canvas.getContext('2d');
var offset = 0;
ctx.scale(3, 3);
function draw() {
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.setLineDash([4, 2]);
ctx.lineDashOffset = -offset;
ctx.strokeRect(10, 10, 100, 100);
}
function _march() {
offset++;
if (offset > 16) {
offset = 0;
}
draw();
setTimeout(_march, 20);
}
_march();
} | the_stack |
import type {
RenderPipelineProps,
RenderPipelineParameters,
RenderPass,
Buffer,
Binding,
ShaderLayout,
PrimitiveTopology,
BindingLayout,
AttributeLayout
} from '@luma.gl/api';
import {RenderPipeline, cast, log, decodeVertexFormat} from '@luma.gl/api';
import GL from '@luma.gl/constants';
import {getWebGLDataType} from '../converters/texture-formats';
import {getShaderLayout} from '../helpers/get-shader-layout';
import {withDeviceParameters} from '../converters/device-parameters';
import {setUniform} from '../helpers/set-uniform';
// import {copyUniform, checkUniformValues} from '../../classes/uniforms';
import WebGLDevice from '../webgl-device';
import WEBGLBuffer from './webgl-buffer';
import WEBGLShader from './webgl-shader';
import WEBGLTexture from './webgl-texture';
import WEBGLVertexArrayObject from '../objects/webgl-vertex-array-object';
const LOG_PROGRAM_PERF_PRIORITY = 4;
/** Creates a new render pipeline */
export default class WEBGLRenderPipeline extends RenderPipeline {
device: WebGLDevice;
handle: WebGLProgram;
vs: WEBGLShader;
fs: WEBGLShader;
layout: ShaderLayout;
// configuration: ProgramConfiguration;
// Experimental flag to avoid deleting Program object while it is cached
varyings: string[];
vertexArrayObject: WEBGLVertexArrayObject;
_indexBuffer?: Buffer;
uniforms: Record<string, any> = {};
bindings: Record<string, any> = {};
_textureUniforms: Record<string, any> = {};
_textureIndexCounter: number = 0;
_uniformCount: number = 0;
_uniformSetters: Record<string, Function>;
constructor(device: WebGLDevice, props: RenderPipelineProps) {
super(device, props);
this.device = device;
this.handle = this.props.handle || this.device.gl.createProgram();
// @ts-expect-error
this.handle.__SPECTOR_Metadata = {id: this.props.id};
// Create shaders if needed
this.vs = cast<WEBGLShader>(props.vs);
this.fs = cast<WEBGLShader>(props.fs);
// assert(this.vs.stage === 'vertex');
// assert(this.fs.stage === 'fragment');
// Setup varyings if supplied
// @ts-expect-error WebGL only
const {varyings, bufferMode = GL.SEPARATE_ATTRIBS} = props;
if (varyings && varyings.length > 0) {
this.device.assertWebGL2();
this.varyings = varyings;
this.device.gl2.transformFeedbackVaryings(this.handle, varyings, bufferMode);
}
this._compileAndLink();
this.layout = props.layout || getShaderLayout(this.device.gl, this.handle);
this.vertexArrayObject = new WEBGLVertexArrayObject(this.device);
}
destroy(): void {
if (this.handle) {
this.device.gl.deleteProgram(this.handle);
this.handle = null;
}
}
setIndexBuffer(indexBuffer: Buffer): void {
const webglBuffer = cast<WEBGLBuffer>(indexBuffer);
this.vertexArrayObject.setElementBuffer(webglBuffer);
this._indexBuffer = indexBuffer;
}
/** @todo needed for portable model */
setAttributes(attributes: Record<string, Buffer>): void {
for (const [name, buffer] of Object.entries(attributes)) {
const webglBuffer = cast<WEBGLBuffer>(buffer);
const attribute = getAttributeLayout(this.layout, name);
if (!attribute) {
log.warn(`Ignoring buffer supplied for unknown attribute "${name}" in pipeline "${this.id}" (buffer "${buffer.id}")`)();
continue;
}
const decoded = decodeVertexFormat(attribute.format);
const {type: typeString, components: size, byteLength: stride, normalized, integer} = decoded;
const divisor = attribute.stepMode === 'instance' ? 1 : 0;
const type = getWebGLDataType(typeString);
this.vertexArrayObject.setBuffer(attribute.location, webglBuffer, {
size,
type,
stride,
offset: 0,
normalized,
integer,
divisor: attribute.stepMode === 'instance' ? 1 : 0
});
}
}
/** @todo needed for portable model */
setBindings(bindings: Record<string, Binding>): void {
// if (log.priority >= 2) {
// checkUniformValues(uniforms, this.id, this._uniformSetters);
// }
for (const [name, value] of Object.entries(bindings)) {
const binding = this.layout.bindings.find((binding) => binding.name === name);
if (!binding) {
log.warn(`Unknown binding ${name} in render pipeline ${this.id}`)();
}
if (!value) {
log.warn(`Unsetting binding ${name} in render pipeline ${this.id}`)();
}
switch (binding.type) {
case 'uniform':
// @ts-expect-error
if (!(value instanceof WEBGLBuffer) && !(value.buffer instanceof WEBGLBuffer)) {
throw new Error('buffer value');
}
break;
case 'texture':
if (!(value instanceof WEBGLTexture)) {
throw new Error('texture value');
}
break;
case 'sampler':
log.warn(`Ignoring sampler ${name}`)();
break;
default:
throw new Error(binding.type);
}
this.bindings[name] = value;
}
}
setUniforms(uniforms: Record<string, any>) {
// TODO - check against layout
Object.assign(this.uniforms, uniforms);
}
/** @todo needed for portable model
* @note The WebGL API is offers many ways to draw things
* This function unifies those ways into a single call using common parameters with sane defaults
*/
draw(options: {
renderPass?: RenderPass;
vertexCount?: number;
indexCount?: number;
instanceCount?: number;
firstVertex?: number;
firstIndex?: number;
firstInstance?: number;
baseVertex?: number;
}): boolean {
const {
renderPass = this.device.getDefaultRenderPass(),
vertexCount,
indexCount,
instanceCount,
firstVertex = 0,
firstIndex,
firstInstance,
baseVertex
} = options;
const drawMode = getDrawMode(this.props.topology);
const isIndexed: boolean = Boolean(this._indexBuffer);
const indexType = this._indexBuffer?.props.indexType === 'uint16' ? GL.UNSIGNED_SHORT : GL.UNSIGNED_INT;
const isInstanced: boolean = options.instanceCount > 0;
// Avoid WebGL draw call when not rendering any data or values are incomplete
// Note: async textures set as uniforms might still be loading.
// Now that all uniforms have been updated, check if any texture
// in the uniforms is not yet initialized, then we don't draw
if (!this._areTexturesRenderable() || options.vertexCount === 0) {
// (isInstanced && instanceCount === 0)
return false;
}
this.device.gl.useProgram(this.handle);
this.vertexArrayObject.bind(() => {
const parameters = {...this.props.parameters, framebuffer: renderPass.props.framebuffer};
const primitiveMode = getGLPrimitive(this.props.topology);
const transformFeedback: any = null;
if (transformFeedback) {
transformFeedback.begin(primitiveMode);
}
// We have to apply bindings before every draw call since other draw calls will overwrite
this._applyBindings();
this._applyUniforms();
// TODO - double context push/pop
withDeviceParameters(this.device, parameters, () => {
// TODO - Use polyfilled WebGL2RenderingContext instead of ANGLE extension
if (isIndexed && isInstanced) {
// ANGLE_instanced_arrays extension
this.device.gl2.drawElementsInstanced(
drawMode,
vertexCount,
indexType,
firstVertex,
instanceCount
);
// } else if (isIndexed && this.device.isWebGL2 && !isNaN(start) && !isNaN(end)) {
// this.device.gl2.drawRangeElements(drawMode, start, end, vertexCount, indexType, offset);
} else if (isIndexed) {
this.device.gl.drawElements(drawMode, vertexCount, indexType, firstVertex);
} else if (isInstanced) {
this.device.gl2.drawArraysInstanced(drawMode, firstVertex, vertexCount, instanceCount);
} else {
this.device.gl.drawArrays(drawMode, firstVertex, vertexCount);
}
});
if (transformFeedback) {
transformFeedback.end();
}
});
return true;
}
// setAttributes(attributes: Record<string, Buffer>): void {}
// setBindings(bindings: Record<string, Binding>): void {}
protected _compileAndLink() {
const {gl} = this.device;
gl.attachShader(this.handle, this.vs.handle);
gl.attachShader(this.handle, this.fs.handle);
log.time(LOG_PROGRAM_PERF_PRIORITY, `linkProgram for ${this.id}`)();
gl.linkProgram(this.handle);
log.timeEnd(LOG_PROGRAM_PERF_PRIORITY, `linkProgram for ${this.id}`)();
// Avoid checking program linking error in production
// @ts-expect-error
if (gl.debug || log.level > 0) {
const linked = gl.getProgramParameter(this.handle, gl.LINK_STATUS);
if (!linked) {
throw new Error(`Error linking: ${gl.getProgramInfoLog(this.handle)}`);
}
gl.validateProgram(this.handle);
const validated = gl.getProgramParameter(this.handle, gl.VALIDATE_STATUS);
if (!validated) {
throw new Error(`Error validating: ${gl.getProgramInfoLog(this.handle)}`);
}
}
}
// PRIVATE METHODS
/**
* Checks if all texture-values uniforms are renderable (i.e. loaded)
* Update a texture if needed (e.g. from video)
* Note: This is currently done before every draw call
*/
_areTexturesRenderable() {
let texturesRenderable = true;
for (const [name, texture] of Object.entries(this._textureUniforms)) {
texture.update();
texturesRenderable = texturesRenderable && texture.loaded;
}
for (const [name, texture] of Object.entries(this.bindings)) {
// texture.update();
if (texture.loaded !== undefined) {
texturesRenderable = texturesRenderable && texture.loaded;
}
}
return texturesRenderable;
}
/** Apply any bindings */
_applyBindings() {
this.device.gl.useProgram(this.handle);
const {gl2} = this.device;
let textureUnit = 0;
let uniformBufferIndex = 0;
for (const binding of this.layout.bindings) {
const value = this.bindings[binding.name];
if (!value) {
throw new Error(`No value for binding ${binding.name} in ${this.id}`);
}
switch (binding.type) {
case 'uniform':
// Set buffer
const {name} = binding;
const location = gl2.getUniformBlockIndex(this.handle, name);
if (location === GL.INVALID_INDEX) {
throw new Error(`Invalid uniform block name ${name}`);
}
gl2.uniformBlockBinding(this.handle, uniformBufferIndex, location);
// console.debug(binding, location);
if (value instanceof WEBGLBuffer) {
gl2.bindBufferBase(GL.UNIFORM_BUFFER, uniformBufferIndex, value.handle);
} else {
gl2.bindBufferRange(
GL.UNIFORM_BUFFER,
uniformBufferIndex,
value.buffer.handle,
value.offset || 0,
value.size || value.buffer.byteLength - value.offset
);
}
uniformBufferIndex += 1;
break;
case 'texture':
if (!(value instanceof WEBGLTexture)) {
throw new Error('texture');
}
const texture: WEBGLTexture = value;
gl2.activeTexture(GL.TEXTURE0 + textureUnit);
gl2.bindTexture(texture.target, texture.handle);
// gl2.bindSampler(textureUnit, sampler.handle);
textureUnit += 1;
break;
case 'sampler':
// ignore
break;
case 'storage':
case 'read-only-storage':
throw new Error(`binding type '${binding.type}' not supported in WebGL`);
}
}
}
_applyUniforms() {
for (const uniformLayout of this.layout.uniforms || []) {
const {name, location, type, textureUnit} = uniformLayout;
const value = this.uniforms[name] || textureUnit;
if (value !== undefined) {
setUniform(this.device.gl, location, type, value);
}
}
}
}
/** Get the primitive type for transform feedback */
function getDrawMode(
topology: PrimitiveTopology
): GL.POINTS | GL.LINES | GL.LINE_STRIP | GL.TRIANGLES | GL.TRIANGLE_STRIP {
// prettier-ignore
switch (topology) {
case 'point-list': return GL.POINTS;
case 'line-list': return GL.LINES;
case 'line-strip': return GL.LINE_STRIP;
case 'triangle-list': return GL.TRIANGLES;
case 'triangle-strip': return GL.TRIANGLE_STRIP;
default: throw new Error(topology);
}
}
/** Get the primitive type for transform feedback */
function getGLPrimitive(topology: PrimitiveTopology): GL.POINTS | GL.LINES | GL.TRIANGLES {
// prettier-ignore
switch (topology) {
case 'point-list': return GL.POINTS;
case 'line-list': return GL.LINES;
case 'line-strip': return GL.LINES;
case 'triangle-list': return GL.TRIANGLES;
case 'triangle-strip': return GL.TRIANGLES;
default: throw new Error(topology);
}
}
function getAttributesByLocation(
attributes: Record<string, Buffer>,
layout: ShaderLayout
): Record<number, Buffer> {
const byLocation: Record<number, Buffer> = {};
for (const [name, buffer] of Object.entries(attributes)) {
const attribute = getAttributeLayout(layout, name);
byLocation[attribute.location] = buffer;
}
return byLocation;
}
function getAttributeLayout(layout: ShaderLayout, name: string): AttributeLayout | undefined {
return layout.attributes.find((binding) => binding.name === name);
}
function getBindingLayout(layout: ShaderLayout, name: string): BindingLayout {
const binding = layout.bindings.find((binding) => binding.name === name);
if (!binding) {
throw new Error(`Unknown binding ${name}`);
}
return binding;
} | the_stack |
import MockDate from 'mockdate';
// eslint-disable-next-line @shopify/strict-component-boundaries
import {StorageServiceMock} from '../StorageService/tests/StorageServiceMock';
import {ExposureStatusType} from '../ExposureNotificationService';
import PushNotification from '../../bridge/PushNotification';
import {OutbreakService, isDiagnosed} from './OutbreakService';
import {checkIns, toSeconds, addHours, subtractHours, addMinutes, subtractMinutes} from './tests/utils';
const i18n: any = {
translate: jest.fn().mockReturnValue('foo'),
};
const bridge: any = {
retrieveOutbreakEvents: jest.fn(),
};
jest.mock('react-native-zip-archive', () => ({
unzip: jest.fn(),
}));
jest.mock('react-native-permissions', () => {
return {checkNotifications: jest.fn().mockReturnValue(Promise.reject()), requestNotifications: jest.fn()};
});
jest.mock('react-native-background-fetch', () => {
return {
configure: jest.fn(),
scheduleTask: jest.fn(),
};
});
jest.mock('../../bridge/CovidShield', () => ({
getRandomBytes: jest.fn().mockResolvedValue(new Uint8Array(32)),
downloadDiagnosisKeysFile: jest.fn(),
}));
jest.mock('react-native-system-setting', () => {
return {
addBluetoothListener: jest.fn(),
addLocationListener: jest.fn(),
};
});
jest.mock('../../bridge/PushNotification', () => ({
...jest.requireActual('bridge/PushNotification'),
presentLocalNotification: jest.fn(),
}));
describe('OutbreakService', () => {
let service: OutbreakService;
beforeEach(async () => {
service = new OutbreakService(i18n, bridge, new StorageServiceMock(), [], []);
MockDate.set('2021-02-01T12:00Z');
});
afterEach(() => {
jest.clearAllMocks();
});
it('adds a checkin', async () => {
await service.addCheckIn(checkIns[0]);
await service.addCheckIn(checkIns[1]);
const checkInHistory = service.checkInHistory.get();
expect(checkInHistory[0].id).toStrictEqual('123');
expect(checkInHistory).toHaveLength(2);
});
it('removes a checkin', async () => {
// add checkins
await service.addCheckIn(checkIns[0]);
await service.addCheckIn(checkIns[1]);
await service.addCheckIn(checkIns[2]);
let checkInHistory = service.checkInHistory.get();
expect(checkInHistory[2].id).toStrictEqual('125');
expect(checkInHistory).toHaveLength(3);
// remove a checkin with id and timestamp
await service.removeCheckIn(checkInHistory[2].id, checkInHistory[2].timestamp);
checkInHistory = service.checkInHistory.get();
expect(checkInHistory).toHaveLength(2);
// add another checkin
await service.addCheckIn(checkIns[3]);
checkInHistory = service.checkInHistory.get();
expect(checkInHistory).toHaveLength(3);
// ensure the new item exists
expect(checkInHistory[checkInHistory.length - 1].id).toStrictEqual(checkIns[3].id);
// remove the latest checkin without using an id / timestamp
await service.removeCheckIn();
checkInHistory = service.checkInHistory.get();
expect(checkInHistory).toHaveLength(2);
expect(checkInHistory[checkInHistory.length - 1].id).toStrictEqual(checkIns[1].id);
});
it('clears checkin history', async () => {
// add checkins
await service.addCheckIn(checkIns[0]);
await service.addCheckIn(checkIns[1]);
let checkInHistory = service.checkInHistory.get();
expect(checkInHistory).toHaveLength(2);
// clear the history
await service.clearCheckInHistory();
checkInHistory = service.checkInHistory.get();
expect(checkInHistory).toHaveLength(0);
});
it('finds outbreak match', async () => {
jest.spyOn(service, 'extractOutbreakEventsFromZipFiles').mockImplementation(async () => {
return service.convertOutbreakEvents([
{
locationId: checkIns[0].id,
startTime: {seconds: toSeconds(subtractHours(checkIns[0].timestamp, 2))},
endTime: {seconds: toSeconds(addHours(checkIns[0].timestamp, 4))},
severity: 1,
},
]);
});
await service.addCheckIn(checkIns[0]);
await service.addCheckIn(checkIns[1]);
await service.checkForOutbreaks();
const outbreakHistory = service.outbreakHistory.get();
expect(outbreakHistory).toHaveLength(1);
});
it('auto deletes outbreaks after OUTBREAK_EXPOSURE_DURATION_DAYS', async () => {
jest.spyOn(service, 'extractOutbreakEventsFromZipFiles').mockImplementation(async () => {
const outbreakData = [
{
locationId: checkIns[0].id,
startTime: {seconds: toSeconds(subtractHours(checkIns[0].timestamp, 2))},
endTime: {seconds: toSeconds(addHours(checkIns[0].timestamp, 4))},
severity: 1,
},
];
return service.convertOutbreakEvents(outbreakData);
});
MockDate.set('2021-02-01T12:00Z');
await service.addCheckIn(checkIns[0]);
await service.addCheckIn(checkIns[1]);
// set as exposed
await service.checkForOutbreaks(true);
const outbreakHistory = service.outbreakHistory.get();
expect(outbreakHistory[0].isExpired).toStrictEqual(false);
expect(outbreakHistory).toHaveLength(1);
// move ahead in time to ensure we're not marking as expired too soon
MockDate.set('2021-02-05T12:00Z');
await service.checkForOutbreaks(true);
const outbreakHistoryNotExpired = service.outbreakHistory.get();
expect(outbreakHistoryNotExpired[0].isExpired).toStrictEqual(false);
expect(outbreakHistoryNotExpired).toHaveLength(1);
// move past the OUTBREAK_EXPOSURE_DURATION_DAYS day mark
MockDate.set('2021-02-15T14:00Z');
await service.checkForOutbreaks(true);
const outbreakRemoved = service.outbreakHistory.get();
expect(outbreakRemoved).toHaveLength(0);
// reset back to default
MockDate.set('2021-02-01T12:00Z');
});
it('no outbreaks if checkins outside time window', async () => {
jest.spyOn(service, 'extractOutbreakEventsFromZipFiles').mockImplementation(async () => {
return service.convertOutbreakEvents([
{
// if outbreak started before checkin
locationId: checkIns[0].id,
startTime: {seconds: toSeconds(subtractHours(checkIns[0].timestamp, 24))},
endTime: {seconds: toSeconds(subtractHours(checkIns[0].timestamp, 4))},
severity: 1,
},
{
// if outbreak started after checkin
locationId: checkIns[1].id,
startTime: {seconds: toSeconds(addHours(checkIns[1].timestamp, 2))},
endTime: {seconds: toSeconds(addHours(checkIns[1].timestamp, 4))},
severity: 1,
},
]);
});
await service.addCheckIn(checkIns[0]);
await service.addCheckIn(checkIns[1]);
await service.checkForOutbreaks(true);
const outbreakHistory = service.outbreakHistory.get();
expect(outbreakHistory).toHaveLength(0);
});
it('returns proper status when diagnosed', async () => {
expect(isDiagnosed(ExposureStatusType.Monitoring)).toStrictEqual(false);
expect(isDiagnosed(ExposureStatusType.Exposed)).toStrictEqual(false);
expect(isDiagnosed(ExposureStatusType.Diagnosed)).toStrictEqual(true);
});
it('sets all outbreaks to ignored', async () => {
jest.spyOn(service, 'extractOutbreakEventsFromZipFiles').mockImplementation(async () => {
return service.convertOutbreakEvents([
{
locationId: checkIns[0].id,
startTime: {seconds: toSeconds(subtractHours(checkIns[0].timestamp, 2))},
endTime: {seconds: toSeconds(addHours(checkIns[0].timestamp, 4))},
severity: 1,
},
{
locationId: checkIns[1].id,
startTime: {seconds: toSeconds(subtractHours(checkIns[1].timestamp, 2))},
endTime: {seconds: toSeconds(addHours(checkIns[1].timestamp, 4))},
severity: 1,
},
]);
});
// add checkins
await service.addCheckIn(checkIns[0]);
await service.addCheckIn(checkIns[1]);
await service.checkForOutbreaks(true);
let outbreakHistory = service.outbreakHistory.get();
expect(outbreakHistory[0].isIgnored).toStrictEqual(false);
expect(outbreakHistory[1].isIgnored).toStrictEqual(false);
expect(outbreakHistory[0].isIgnoredFromHistory).toStrictEqual(false);
expect(outbreakHistory[1].isIgnoredFromHistory).toStrictEqual(false);
// ignore all outbreaks
await service.ignoreAllOutbreaks();
await service.ignoreAllOutbreaksFromHistory();
outbreakHistory = service.outbreakHistory.get();
expect(outbreakHistory[0].isIgnored).toStrictEqual(true);
expect(outbreakHistory[1].isIgnored).toStrictEqual(true);
expect(outbreakHistory[0].isIgnoredFromHistory).toStrictEqual(true);
expect(outbreakHistory[1].isIgnoredFromHistory).toStrictEqual(true);
});
it('sets single outbreak to ignored', async () => {
jest.spyOn(service, 'extractOutbreakEventsFromZipFiles').mockImplementation(async () => {
return service.convertOutbreakEvents([
{
locationId: checkIns[0].id,
startTime: {seconds: toSeconds(subtractHours(checkIns[0].timestamp, 2))},
endTime: {seconds: toSeconds(addHours(checkIns[0].timestamp, 4))},
severity: 1,
},
{
locationId: checkIns[1].id,
startTime: {seconds: toSeconds(subtractHours(checkIns[1].timestamp, 2))},
endTime: {seconds: toSeconds(addHours(checkIns[1].timestamp, 4))},
severity: 1,
},
]);
});
// add checkins
await service.addCheckIn(checkIns[0]);
await service.addCheckIn(checkIns[1]);
await service.checkForOutbreaks(true);
let outbreakHistory = service.outbreakHistory.get();
expect(outbreakHistory[0].isIgnored).toStrictEqual(false);
expect(outbreakHistory[1].isIgnored).toStrictEqual(false);
// ignore the second outbreak
await service.ignoreOutbreak(outbreakHistory[1].id);
outbreakHistory = service.outbreakHistory.get();
expect(outbreakHistory[1].isIgnored).toStrictEqual(true);
});
it('returns outbreak when 10 minute overlap', async () => {
jest.spyOn(service, 'extractOutbreakEventsFromZipFiles').mockImplementation(async () => {
return service.convertOutbreakEvents([
{
locationId: checkIns[0].id,
startTime: {seconds: toSeconds(subtractMinutes(checkIns[0].timestamp, 5))},
endTime: {seconds: toSeconds(addMinutes(checkIns[0].timestamp, 5))},
severity: 1,
},
]);
});
await service.addCheckIn(checkIns[0]);
await service.addCheckIn(checkIns[1]);
await service.checkForOutbreaks();
const outbreakHistory = service.outbreakHistory.get();
expect(outbreakHistory).toHaveLength(1);
});
it('returns outbreak when 2 hour overlap', async () => {
jest.spyOn(service, 'extractOutbreakEventsFromZipFiles').mockImplementation(async () => {
return service.convertOutbreakEvents([
{
locationId: checkIns[0].id,
startTime: {seconds: toSeconds(subtractHours(checkIns[0].timestamp, 1))},
endTime: {seconds: toSeconds(addHours(checkIns[0].timestamp, 1))},
severity: 1,
},
]);
});
await service.addCheckIn(checkIns[0]);
await service.addCheckIn(checkIns[1]);
await service.checkForOutbreaks();
const outbreakHistory = service.outbreakHistory.get();
expect(outbreakHistory).toHaveLength(1);
});
it('returns outbreak when 1 day overlap', async () => {
jest.spyOn(service, 'extractOutbreakEventsFromZipFiles').mockImplementation(async () => {
return service.convertOutbreakEvents([
{
locationId: checkIns[0].id,
startTime: {seconds: toSeconds(subtractHours(checkIns[0].timestamp, 12))},
endTime: {seconds: toSeconds(addHours(checkIns[0].timestamp, 12))},
severity: 1,
},
]);
});
await service.addCheckIn(checkIns[0]);
await service.addCheckIn(checkIns[1]);
await service.checkForOutbreaks();
const outbreakHistory = service.outbreakHistory.get();
expect(outbreakHistory).toHaveLength(1);
});
it('auto deletes checkin after CHECKIN_NOTIFICATION_CYCLE', async () => {
await service.addCheckIn(checkIns[4]);
await service.addCheckIn(checkIns[5]);
// day 1
MockDate.set('2021-01-01T10:00Z');
let checkins = service.checkInHistory.get();
expect(checkins).toHaveLength(2);
// checkForOutbreaks calls autoDeleteCheckinAfterPeriod
// this would run from the background task
await service.checkForOutbreaks();
checkins = service.checkInHistory.get();
expect(checkins).toHaveLength(2);
// move past the CHECKIN_NOTIFICATION_CYCLE day mark
MockDate.set('2021-01-30T10:00Z');
await service.checkForOutbreaks();
checkins = service.checkInHistory.get();
expect(checkins).toHaveLength(0);
});
it('performs an outbreak check if past the min minutes threshold', async () => {
jest.spyOn(service, 'extractOutbreakEventsFromZipFiles').mockImplementation(async () => {
return service.convertOutbreakEvents([
{
locationId: checkIns[0].id,
startTime: {seconds: toSeconds(subtractHours(checkIns[0].timestamp, 2))},
endTime: {seconds: toSeconds(addHours(checkIns[0].timestamp, 4))},
severity: 1,
},
]);
});
await service.addCheckIn(checkIns[0]);
await service.addCheckIn(checkIns[1]);
await service.checkForOutbreaks();
// Current Date: 2021-02-01T12:00:00.000Z
MockDate.set('2021-02-01T12:30Z');
// First check 30 minutes later
const performOutbreakCheck30Mins = await service.shouldPerformOutbreaksCheck();
expect(performOutbreakCheck30Mins).toStrictEqual(false);
MockDate.set('2021-02-01T15:00Z');
// Second check 3 hours later
const performOutbreakCheck3Hours = await service.shouldPerformOutbreaksCheck();
expect(performOutbreakCheck30Mins).toStrictEqual(false);
MockDate.set('2021-02-01T18:00Z');
// third check 6 hours later
const performOutbreakCheck6Hours = await service.shouldPerformOutbreaksCheck();
expect(performOutbreakCheck6Hours).toStrictEqual(true);
});
it('performs one check returns two outbreaks', async () => {
jest.spyOn(service, 'extractOutbreakEventsFromZipFiles').mockImplementation(async () => {
return service.convertOutbreakEvents([
{
locationId: checkIns[0].id,
startTime: {seconds: toSeconds(subtractHours(checkIns[0].timestamp, 2))},
endTime: {seconds: toSeconds(addHours(checkIns[0].timestamp, 4))},
severity: 1,
},
{
locationId: checkIns[1].id,
startTime: {seconds: toSeconds(subtractHours(checkIns[1].timestamp, 2))},
endTime: {seconds: toSeconds(addHours(checkIns[1].timestamp, 4))},
severity: 1,
},
]);
});
// First check occurs: 2021-02-01T12:00:00.000Z
MockDate.set('2021-02-01T11:00Z');
await service.checkForOutbreaks();
await service.addCheckIn(checkIns[0]);
await service.addCheckIn(checkIns[1]);
await service.addCheckIn(checkIns[2]);
MockDate.set('2021-02-01T14:30Z');
// This check is 2.5 hours after first scan and 30 mins after second so it will not perform an outbreak check
let performOutbreakCheck = await service.shouldPerformOutbreaksCheck();
await service.checkForOutbreaks(performOutbreakCheck);
let outbreakHistory = service.outbreakHistory.get();
expect(outbreakHistory).toHaveLength(0);
MockDate.set('2021-02-01T17:30Z');
// This check is 5.5 hours after first scan and 3.5 hours after second so it will perform an outbreak check
performOutbreakCheck = await service.shouldPerformOutbreaksCheck();
await service.checkForOutbreaks(performOutbreakCheck);
outbreakHistory = service.outbreakHistory.get();
expect(outbreakHistory).toHaveLength(2);
});
it('sends a notification if there is an outbreak', async () => {
jest.spyOn(service, 'extractOutbreakEventsFromZipFiles').mockImplementation(async () => {
return service.convertOutbreakEvents([
{
locationId: checkIns[0].id,
startTime: {seconds: toSeconds(subtractHours(checkIns[0].timestamp, 2))},
endTime: {seconds: toSeconds(addHours(checkIns[0].timestamp, 4))},
severity: 1,
},
{
locationId: checkIns[1].id,
startTime: {seconds: toSeconds(subtractHours(checkIns[1].timestamp, 2))},
endTime: {seconds: toSeconds(addHours(checkIns[1].timestamp, 4))},
severity: 1,
},
]);
});
await service.addCheckIn(checkIns[0]);
await service.addCheckIn(checkIns[1]);
await service.checkForOutbreaks();
expect(PushNotification.presentLocalNotification).toHaveBeenCalledTimes(1);
});
it('does not send a notification is outbreak history is empty', async () => {
jest.spyOn(service, 'extractOutbreakEventsFromZipFiles').mockImplementation(async () => {
return service.convertOutbreakEvents([
{
locationId: checkIns[0].id,
startTime: {seconds: toSeconds(subtractHours(checkIns[0].timestamp, 2))},
endTime: {seconds: toSeconds(addHours(checkIns[0].timestamp, 4))},
severity: 1,
},
]);
});
await service.addCheckIn(checkIns[0]);
await service.addCheckIn(checkIns[1]);
MockDate.set('2021-02-16T12:00Z');
await service.checkForOutbreaks();
const outbreakHistory = service.outbreakHistory.get();
expect(outbreakHistory).toHaveLength(0);
expect(PushNotification.presentLocalNotification).not.toHaveBeenCalled();
});
}); | the_stack |
import { fromTheme } from './from-theme'
import {
isAny,
isArbitraryLength,
isArbitraryPosition,
isArbitraryShadow,
isArbitrarySize,
isArbitraryUrl,
isArbitraryValue,
isArbitraryWeight,
isInteger,
isLength,
isTshirtSize,
} from './validators'
export function getDefaultConfig() {
const colors = fromTheme('colors')
const spacing = fromTheme('spacing')
const blur = fromTheme('blur')
const brightness = fromTheme('brightness')
const borderColor = fromTheme('borderColor')
const borderRadius = fromTheme('borderRadius')
const borderWidth = fromTheme('borderWidth')
const contrast = fromTheme('contrast')
const grayscale = fromTheme('grayscale')
const hueRotate = fromTheme('hueRotate')
const invert = fromTheme('invert')
const gap = fromTheme('gap')
const gradientColorStops = fromTheme('gradientColorStops')
const inset = fromTheme('inset')
const margin = fromTheme('margin')
const opacity = fromTheme('opacity')
const padding = fromTheme('padding')
const saturate = fromTheme('saturate')
const scale = fromTheme('scale')
const sepia = fromTheme('sepia')
const skew = fromTheme('skew')
const space = fromTheme('space')
const translate = fromTheme('translate')
const getOverscroll = () => ['auto', 'contain', 'none'] as const
const getOverflow = () => ['auto', 'hidden', 'clip', 'visible', 'scroll'] as const
const getSpacingWithAuto = () => ['auto', spacing] as const
const getLengthWithEmpty = () => ['', isLength] as const
const getIntegerWithAuto = () => ['auto', isInteger] as const
const getPositions = () =>
[
'bottom',
'center',
'left',
'left-bottom',
'left-top',
'right',
'right-bottom',
'right-top',
'top',
] as const
const getLineStyles = () => ['solid', 'dashed', 'dotted', 'double', 'none'] as const
const getBlendModes = () =>
[
'normal',
'multiply',
'screen',
'overlay',
'darken',
'lighten',
'color-dodge',
'color-burn',
'hard-light',
'soft-light',
'difference',
'exclusion',
'hue',
'saturation',
'color',
'luminosity',
] as const
const getAlign = () => ['start', 'end', 'center', 'between', 'around', 'evenly'] as const
const getZeroAndEmpty = () => ['', '0', isArbitraryValue] as const
const getBreaks = () =>
['auto', 'avoid', 'all', 'avoid-page', 'page', 'left', 'right', 'column'] as const
return {
cacheSize: 500,
theme: {
colors: [isAny],
spacing: [isLength],
blur: ['none', '', isTshirtSize, isArbitraryLength],
brightness: [isInteger],
borderColor: [colors],
borderRadius: ['none', '', 'full', isTshirtSize, isArbitraryLength],
borderWidth: getLengthWithEmpty(),
contrast: [isInteger],
grayscale: getZeroAndEmpty(),
hueRotate: [isInteger],
invert: getZeroAndEmpty(),
gap: [spacing],
gradientColorStops: [colors],
inset: getSpacingWithAuto(),
margin: getSpacingWithAuto(),
opacity: [isInteger],
padding: [spacing],
saturate: [isInteger],
scale: [isInteger],
sepia: getZeroAndEmpty(),
skew: [isInteger, isArbitraryValue],
space: [spacing],
translate: [spacing],
},
classGroups: {
// Layout
/**
* Aspect Ratio
* @see https://tailwindcss.com/docs/aspect-ratio
*/
aspect: [{ aspect: ['auto', 'square', 'video', isArbitraryValue] }],
/**
* Container
* @see https://tailwindcss.com/docs/container
*/
container: ['container'],
/**
* Columns
* @see https://tailwindcss.com/docs/columns
*/
columns: [{ columns: [isTshirtSize] }],
/**
* Break After
* @see https://tailwindcss.com/docs/break-after
*/
'break-after': [{ 'break-after': getBreaks() }],
/**
* Break Before
* @see https://tailwindcss.com/docs/break-before
*/
'break-before': [{ 'break-before': getBreaks() }],
/**
* Break Inside
* @see https://tailwindcss.com/docs/break-inside
*/
'break-inside': [{ 'break-inside': ['auto', 'avoid', 'avoid-page', 'avoid-column'] }],
/**
* Box Decoration Break
* @see https://tailwindcss.com/docs/box-decoration-break
*/
'box-decoration': [{ 'box-decoration': ['slice', 'clone'] }],
/**
* Box Sizing
* @see https://tailwindcss.com/docs/box-sizing
*/
box: [{ box: ['border', 'content'] }],
/**
* Display
* @see https://tailwindcss.com/docs/display
*/
display: [
'block',
'inline-block',
'inline',
'flex',
'inline-flex',
'table',
'inline-table',
'table-caption',
'table-cell',
'table-column',
'table-column-group',
'table-footer-group',
'table-header-group',
'table-row-group',
'table-row',
'flow-root',
'grid',
'inline-grid',
'contents',
'list-item',
'hidden',
],
/**
* Floats
* @see https://tailwindcss.com/docs/float
*/
float: [{ float: ['right', 'left', 'none'] }],
/**
* Clear
* @see https://tailwindcss.com/docs/clear
*/
clear: [{ clear: ['left', 'right', 'both', 'none'] }],
/**
* Isolation
* @see https://tailwindcss.com/docs/isolation
*/
isolation: ['isolate', 'isolation-auto'],
/**
* Object Fit
* @see https://tailwindcss.com/docs/object-fit
*/
'object-fit': [{ object: ['contain', 'cover', 'fill', 'none', 'scale-down'] }],
/**
* Object Position
* @see https://tailwindcss.com/docs/object-position
*/
'object-position': [{ object: [...getPositions(), isArbitraryValue] }],
/**
* Overflow
* @see https://tailwindcss.com/docs/overflow
*/
overflow: [{ overflow: getOverflow() }],
/**
* Overflow X
* @see https://tailwindcss.com/docs/overflow
*/
'overflow-x': [{ 'overflow-x': getOverflow() }],
/**
* Overflow Y
* @see https://tailwindcss.com/docs/overflow
*/
'overflow-y': [{ 'overflow-y': getOverflow() }],
/**
* Overscroll Behavior
* @see https://tailwindcss.com/docs/overscroll-behavior
*/
overscroll: [{ overscroll: getOverscroll() }],
/**
* Overscroll Behavior X
* @see https://tailwindcss.com/docs/overscroll-behavior
*/
'overscroll-x': [{ 'overscroll-x': getOverscroll() }],
/**
* Overscroll Behavior Y
* @see https://tailwindcss.com/docs/overscroll-behavior
*/
'overscroll-y': [{ 'overscroll-y': getOverscroll() }],
/**
* Position
* @see https://tailwindcss.com/docs/position
*/
position: ['static', 'fixed', 'absolute', 'relative', 'sticky'],
/**
* Top / Right / Bottom / Left
* @see https://tailwindcss.com/docs/top-right-bottom-left
*/
inset: [{ inset: [inset] }],
/**
* Right / Left
* @see https://tailwindcss.com/docs/top-right-bottom-left
*/
'inset-x': [{ 'inset-x': [inset] }],
/**
* Top / Bottom
* @see https://tailwindcss.com/docs/top-right-bottom-left
*/
'inset-y': [{ 'inset-y': [inset] }],
/**
* Top
* @see https://tailwindcss.com/docs/top-right-bottom-left
*/
top: [{ top: [inset] }],
/**
* Right
* @see https://tailwindcss.com/docs/top-right-bottom-left
*/
right: [{ right: [inset] }],
/**
* Bottom
* @see https://tailwindcss.com/docs/top-right-bottom-left
*/
bottom: [{ bottom: [inset] }],
/**
* Left
* @see https://tailwindcss.com/docs/top-right-bottom-left
*/
left: [{ left: [inset] }],
/**
* Visibility
* @see https://tailwindcss.com/docs/visibility
*/
visibility: ['visible', 'invisible'],
/**
* Z-Index
* @see https://tailwindcss.com/docs/z-index
*/
z: [{ z: [isLength] }],
// Flexbox and Grid
/**
* Flex Basis
* @see https://tailwindcss.com/docs/flex-basis
*/
basis: [{ basis: [spacing] }],
/**
* Flex Direction
* @see https://tailwindcss.com/docs/flex-direction
*/
'flex-direction': [{ flex: ['row', 'row-reverse', 'col', 'col-reverse'] }],
/**
* Flex Wrap
* @see https://tailwindcss.com/docs/flex-wrap
*/
'flex-wrap': [{ flex: ['wrap', 'wrap-reverse', 'nowrap'] }],
/**
* Flex
* @see https://tailwindcss.com/docs/flex
*/
flex: [{ flex: ['1', 'auto', 'initial', 'none', isArbitraryValue] }],
/**
* Flex Grow
* @see https://tailwindcss.com/docs/flex-grow
*/
grow: [{ grow: getZeroAndEmpty() }],
/**
* Flex Shrink
* @see https://tailwindcss.com/docs/flex-shrink
*/
shrink: [{ shrink: getZeroAndEmpty() }],
/**
* Order
* @see https://tailwindcss.com/docs/order
*/
order: [{ order: ['first', 'last', 'none', isInteger] }],
/**
* Grid Template Columns
* @see https://tailwindcss.com/docs/grid-template-columns
*/
'grid-cols': [{ 'grid-cols': [isAny] }],
/**
* Grid Column Start / End
* @see https://tailwindcss.com/docs/grid-column
*/
'col-start-end': [{ col: ['auto', { span: [isInteger] }] }],
/**
* Grid Column Start
* @see https://tailwindcss.com/docs/grid-column
*/
'col-start': [{ 'col-start': getIntegerWithAuto() }],
/**
* Grid Column End
* @see https://tailwindcss.com/docs/grid-column
*/
'col-end': [{ 'col-end': getIntegerWithAuto() }],
/**
* Grid Template Rows
* @see https://tailwindcss.com/docs/grid-template-rows
*/
'grid-rows': [{ 'grid-rows': [isAny] }],
/**
* Grid Row Start / End
* @see https://tailwindcss.com/docs/grid-row
*/
'row-start-end': [{ row: ['auto', { span: [isInteger] }] }],
/**
* Grid Row Start
* @see https://tailwindcss.com/docs/grid-row
*/
'row-start': [{ 'row-start': getIntegerWithAuto() }],
/**
* Grid Row End
* @see https://tailwindcss.com/docs/grid-row
*/
'row-end': [{ 'row-end': getIntegerWithAuto() }],
/**
* Grid Auto Flow
* @see https://tailwindcss.com/docs/grid-auto-flow
*/
'grid-flow': [{ 'grid-flow': ['row', 'col', 'row-dense', 'col-dense'] }],
/**
* Grid Auto Columns
* @see https://tailwindcss.com/docs/grid-auto-columns
*/
'auto-cols': [{ 'auto-cols': ['auto', 'min', 'max', 'fr', isArbitraryValue] }],
/**
* Grid Auto Rows
* @see https://tailwindcss.com/docs/grid-auto-rows
*/
'auto-rows': [{ 'auto-rows': ['auto', 'min', 'max', 'fr', isArbitraryValue] }],
/**
* Gap
* @see https://tailwindcss.com/docs/gap
*/
gap: [{ gap: [gap] }],
/**
* Gap X
* @see https://tailwindcss.com/docs/gap
*/
'gap-x': [{ 'gap-x': [gap] }],
/**
* Gap Y
* @see https://tailwindcss.com/docs/gap
*/
'gap-y': [{ 'gap-y': [gap] }],
/**
* Justify Content
* @see https://tailwindcss.com/docs/justify-content
*/
'justify-content': [{ justify: getAlign() }],
/**
* Justify Items
* @see https://tailwindcss.com/docs/justify-items
*/
'justify-items': [{ 'justify-items': ['start', 'end', 'center', 'stretch'] }],
/**
* Justify Self
* @see https://tailwindcss.com/docs/justify-self
*/
'justify-self': [{ 'justify-self': ['auto', 'start', 'end', 'center', 'stretch'] }],
/**
* Align Content
* @see https://tailwindcss.com/docs/align-content
*/
'align-content': [{ content: getAlign() }],
/**
* Align Items
* @see https://tailwindcss.com/docs/align-items
*/
'align-items': [{ items: ['start', 'end', 'center', 'baseline', 'stretch'] }],
/**
* Align Self
* @see https://tailwindcss.com/docs/align-self
*/
'align-self': [{ self: ['auto', 'start', 'end', 'center', 'stretch', 'baseline'] }],
/**
* Place Content
* @see https://tailwindcss.com/docs/place-content
*/
'place-content': [{ 'place-content': [...getAlign(), 'stretch'] }],
/**
* Place Items
* @see https://tailwindcss.com/docs/place-items
*/
'place-items': [{ 'place-items': ['start', 'end', 'center', 'stretch'] }],
/**
* Place Self
* @see https://tailwindcss.com/docs/place-self
*/
'place-self': [{ 'place-self': ['auto', 'start', 'end', 'center', 'stretch'] }],
// Spacing
/**
* Padding
* @see https://tailwindcss.com/docs/padding
*/
p: [{ p: [padding] }],
/**
* Padding X
* @see https://tailwindcss.com/docs/padding
*/
px: [{ px: [padding] }],
/**
* Padding Y
* @see https://tailwindcss.com/docs/padding
*/
py: [{ py: [padding] }],
/**
* Padding Top
* @see https://tailwindcss.com/docs/padding
*/
pt: [{ pt: [padding] }],
/**
* Padding Right
* @see https://tailwindcss.com/docs/padding
*/
pr: [{ pr: [padding] }],
/**
* Padding Bottom
* @see https://tailwindcss.com/docs/padding
*/
pb: [{ pb: [padding] }],
/**
* Padding Left
* @see https://tailwindcss.com/docs/padding
*/
pl: [{ pl: [padding] }],
/**
* Margin
* @see https://tailwindcss.com/docs/margin
*/
m: [{ m: [margin] }],
/**
* Margin X
* @see https://tailwindcss.com/docs/margin
*/
mx: [{ mx: [margin] }],
/**
* Margin Y
* @see https://tailwindcss.com/docs/margin
*/
my: [{ my: [margin] }],
/**
* Margin Top
* @see https://tailwindcss.com/docs/margin
*/
mt: [{ mt: [margin] }],
/**
* Margin Right
* @see https://tailwindcss.com/docs/margin
*/
mr: [{ mr: [margin] }],
/**
* Margin Bottom
* @see https://tailwindcss.com/docs/margin
*/
mb: [{ mb: [margin] }],
/**
* Margin Left
* @see https://tailwindcss.com/docs/margin
*/
ml: [{ ml: [margin] }],
/**
* Space Between X
* @see https://tailwindcss.com/docs/space
*/
'space-x': [{ 'space-x': [space] }],
/**
* Space Between X Reverse
* @see https://tailwindcss.com/docs/space
*/
'space-x-reverse': ['space-x-reverse'],
/**
* Space Between Y
* @see https://tailwindcss.com/docs/space
*/
'space-y': [{ 'space-y': [space] }],
/**
* Space Between Y Reverse
* @see https://tailwindcss.com/docs/space
*/
'space-y-reverse': ['space-y-reverse'],
// Sizing
/**
* Width
* @see https://tailwindcss.com/docs/width
*/
w: [{ w: ['auto', 'min', 'max', spacing] }],
/**
* Min-Width
* @see https://tailwindcss.com/docs/min-width
*/
'min-w': [{ 'min-w': ['min', 'max', 'fit', isLength] }],
/**
* Max-Width
* @see https://tailwindcss.com/docs/max-width
*/
'max-w': [
{
'max-w': [
'0',
'none',
'full',
'min',
'max',
'fit',
'prose',
{ screen: [isTshirtSize] },
isTshirtSize,
isArbitraryLength,
],
},
],
/**
* Height
* @see https://tailwindcss.com/docs/height
*/
h: [{ h: getSpacingWithAuto() }],
/**
* Min-Height
* @see https://tailwindcss.com/docs/min-height
*/
'min-h': [{ 'min-h': ['min', 'max', 'fit', isLength] }],
/**
* Max-Height
* @see https://tailwindcss.com/docs/max-height
*/
'max-h': [{ 'max-h': [spacing, 'min', 'max', 'fit'] }],
// Typography
/**
* Font Size
* @see https://tailwindcss.com/docs/font-size
*/
'font-size': [{ text: ['base', isTshirtSize, isArbitraryLength] }],
/**
* Font Smoothing
* @see https://tailwindcss.com/docs/font-smoothing
*/
'font-smoothing': ['antialiased', 'subpixel-antialiased'],
/**
* Font Style
* @see https://tailwindcss.com/docs/font-style
*/
'font-style': ['italic', 'not-italic'],
/**
* Font Weight
* @see https://tailwindcss.com/docs/font-weight
*/
'font-weight': [
{
font: [
'thin',
'extralight',
'light',
'normal',
'medium',
'semibold',
'bold',
'extrabold',
'black',
isArbitraryWeight,
],
},
],
/**
* Font Family
* @see https://tailwindcss.com/docs/font-family
*/
'font-family': [{ font: [isAny] }],
/**
* Font Variant Numeric
* @see https://tailwindcss.com/docs/font-variant-numeric
*/
'fvn-normal': ['normal-nums'],
/**
* Font Variant Numeric
* @see https://tailwindcss.com/docs/font-variant-numeric
*/
'fvn-ordinal': ['ordinal'],
/**
* Font Variant Numeric
* @see https://tailwindcss.com/docs/font-variant-numeric
*/
'fvn-slashed-zero': ['slashed-zero'],
/**
* Font Variant Numeric
* @see https://tailwindcss.com/docs/font-variant-numeric
*/
'fvn-figure': ['lining-nums', 'oldstyle-nums'],
/**
* Font Variant Numeric
* @see https://tailwindcss.com/docs/font-variant-numeric
*/
'fvn-spacing': ['proportional-nums', 'tabular-nums'],
/**
* Font Variant Numeric
* @see https://tailwindcss.com/docs/font-variant-numeric
*/
'fvn-fraction': ['diagonal-fractions', 'stacked-fractons'],
/**
* Letter Spacing
* @see https://tailwindcss.com/docs/letter-spacing
*/
tracking: [
{
tracking: [
'tighter',
'tight',
'normal',
'wide',
'wider',
'widest',
isArbitraryLength,
],
},
],
/**
* Line Height
* @see https://tailwindcss.com/docs/line-height
*/
leading: [
{ leading: ['none', 'tight', 'snug', 'normal', 'relaxed', 'loose', isLength] },
],
/**
* List Style Type
* @see https://tailwindcss.com/docs/list-style-type
*/
'list-style-type': [{ list: ['none', 'disc', 'decimal', isArbitraryValue] }],
/**
* List Style Position
* @see https://tailwindcss.com/docs/list-style-position
*/
'list-style-position': [{ list: ['inside', 'outside'] }],
/**
* Placeholder Color
* @deprecated since Tailwind CSS v3.0.0
* @see https://tailwindcss.com/docs/placeholder-color
*/
'placeholder-color': [{ placeholder: [colors] }],
/**
* Placeholder Opacity
* @see https://tailwindcss.com/docs/placeholder-opacity
*/
'placeholder-opacity': [{ 'placeholder-opacity': [opacity] }],
/**
* Text Alignment
* @see https://tailwindcss.com/docs/text-align
*/
'text-alignment': [{ text: ['left', 'center', 'right', 'justify'] }],
/**
* Text Color
* @see https://tailwindcss.com/docs/text-color
*/
'text-color': [{ text: [colors] }],
/**
* Text Opacity
* @see https://tailwindcss.com/docs/text-opacity
*/
'text-opacity': [{ 'text-opacity': [opacity] }],
/**
* Text Decoration
* @see https://tailwindcss.com/docs/text-decoration
*/
'text-decoration': ['underline', 'overline', 'line-through', 'no-underline'],
/**
* Text Decoration Style
* @see https://tailwindcss.com/docs/text-decoration-style
*/
'text-decoration-style': [{ decoration: [...getLineStyles(), 'wavy'] }],
/**
* Text Decoration Thickness
* @see https://tailwindcss.com/docs/text-decoration-thickness
*/
'text-decoration-thickness': [{ decoration: ['auto', 'from-font', isLength] }],
/**
* Text Underline Offset
* @see https://tailwindcss.com/docs/text-underline-offset
*/
'underline-offset': [{ 'underline-offset': ['auto', isLength] }],
/**
* Text Decoration Color
* @see https://tailwindcss.com/docs/text-decoration-color
*/
'text-decoration-color': [{ decoration: [colors] }],
/**
* Text Transform
* @see https://tailwindcss.com/docs/text-transform
*/
'text-transform': ['uppercase', 'lowercase', 'capitalize', 'normal-case'],
/**
* Text Overflow
* @see https://tailwindcss.com/docs/text-overflow
*/
'text-overflow': ['truncate', 'text-ellipsis', 'text-clip'],
/**
* Text Indent
* @see https://tailwindcss.com/docs/text-indent
*/
indent: [{ indent: [spacing] }],
/**
* Vertical Alignment
* @see https://tailwindcss.com/docs/vertical-align
*/
'vertical-align': [
{
align: [
'baseline',
'top',
'middle',
'bottom',
'text-top',
'text-bottom',
'sub',
'super',
isArbitraryLength,
],
},
],
/**
* Whitespace
* @see https://tailwindcss.com/docs/whitespace
*/
whitespace: [{ whitespace: ['normal', 'nowrap', 'pre', 'pre-line', 'pre-wrap'] }],
/**
* Word Break
* @see https://tailwindcss.com/docs/word-break
*/
break: [{ break: ['normal', 'words', 'all'] }],
/**
* Content
* @see https://tailwindcss.com/docs/content
*/
content: [{ content: ['none', isArbitraryValue] }],
// Backgrounds
/**
* Background Attachment
* @see https://tailwindcss.com/docs/background-attachment
*/
'bg-attachment': [{ bg: ['fixed', 'local', 'scroll'] }],
/**
* Background Clip
* @see https://tailwindcss.com/docs/background-clip
*/
'bg-clip': [{ 'bg-clip': ['border', 'padding', 'content', 'text'] }],
/**
* Background Opacity
* @deprecated since Tailwind CSS v3.0.0
* @see https://tailwindcss.com/docs/background-opacity
*/
'bg-opacity': [{ 'bg-opacity': [opacity] }],
/**
* Background Origin
* @see https://tailwindcss.com/docs/background-origin
*/
'bg-origin': [{ 'bg-origin': ['border', 'padding', 'content'] }],
/**
* Background Position
* @see https://tailwindcss.com/docs/background-position
*/
'bg-position': [{ bg: [...getPositions(), isArbitraryPosition] }],
/**
* Background Repeat
* @see https://tailwindcss.com/docs/background-repeat
*/
'bg-repeat': [{ bg: ['no-repeat', { repeat: ['', 'x', 'y', 'round', 'space'] }] }],
/**
* Background Size
* @see https://tailwindcss.com/docs/background-size
*/
'bg-size': [{ bg: ['auto', 'cover', 'contain', isArbitrarySize] }],
/**
* Background Image
* @see https://tailwindcss.com/docs/background-image
*/
'bg-image': [
{
bg: [
'none',
{ 'gradient-to': ['t', 'tr', 'r', 'br', 'b', 'bl', 'l', 'tl'] },
isArbitraryUrl,
],
},
],
/**
* Background Color
* @see https://tailwindcss.com/docs/background-color
*/
'bg-color': [{ bg: [colors] }],
/**
* Gradient Color Stops From
* @see https://tailwindcss.com/docs/gradient-color-stops
*/
'gradient-from': [{ from: [gradientColorStops] }],
/**
* Gradient Color Stops Via
* @see https://tailwindcss.com/docs/gradient-color-stops
*/
'gradient-via': [{ via: [gradientColorStops] }],
/**
* Gradient Color Stops To
* @see https://tailwindcss.com/docs/gradient-color-stops
*/
'gradient-to': [{ to: [gradientColorStops] }],
// Borders
/**
* Border Radius
* @see https://tailwindcss.com/docs/border-radius
*/
rounded: [{ rounded: [borderRadius] }],
/**
* Border Radius Top
* @see https://tailwindcss.com/docs/border-radius
*/
'rounded-t': [{ 'rounded-t': [borderRadius] }],
/**
* Border Radius Right
* @see https://tailwindcss.com/docs/border-radius
*/
'rounded-r': [{ 'rounded-r': [borderRadius] }],
/**
* Border Radius Bottom
* @see https://tailwindcss.com/docs/border-radius
*/
'rounded-b': [{ 'rounded-b': [borderRadius] }],
/**
* Border Radius Left
* @see https://tailwindcss.com/docs/border-radius
*/
'rounded-l': [{ 'rounded-l': [borderRadius] }],
/**
* Border Radius Top Left
* @see https://tailwindcss.com/docs/border-radius
*/
'rounded-tl': [{ 'rounded-tl': [borderRadius] }],
/**
* Border Radius Top Right
* @see https://tailwindcss.com/docs/border-radius
*/
'rounded-tr': [{ 'rounded-tr': [borderRadius] }],
/**
* Border Radius Bottom Right
* @see https://tailwindcss.com/docs/border-radius
*/
'rounded-br': [{ 'rounded-br': [borderRadius] }],
/**
* Border Radius Bottom Left
* @see https://tailwindcss.com/docs/border-radius
*/
'rounded-bl': [{ 'rounded-bl': [borderRadius] }],
/**
* Border Width
* @see https://tailwindcss.com/docs/border-width
*/
'border-w': [{ border: [borderWidth] }],
/**
* Border Width X
* @see https://tailwindcss.com/docs/border-width
*/
'border-w-x': [{ 'border-x': [borderWidth] }],
/**
* Border Width Y
* @see https://tailwindcss.com/docs/border-width
*/
'border-w-y': [{ 'border-y': [borderWidth] }],
/**
* Border Width Top
* @see https://tailwindcss.com/docs/border-width
*/
'border-w-t': [{ 'border-t': [borderWidth] }],
/**
* Border Width Right
* @see https://tailwindcss.com/docs/border-width
*/
'border-w-r': [{ 'border-r': [borderWidth] }],
/**
* Border Width Bottom
* @see https://tailwindcss.com/docs/border-width
*/
'border-w-b': [{ 'border-b': [borderWidth] }],
/**
* Border Width Left
* @see https://tailwindcss.com/docs/border-width
*/
'border-w-l': [{ 'border-l': [borderWidth] }],
/**
* Border Opacity
* @see https://tailwindcss.com/docs/border-opacity
*/
'border-opacity': [{ 'border-opacity': [opacity] }],
/**
* Border Style
* @see https://tailwindcss.com/docs/border-style
*/
'border-style': [{ border: [...getLineStyles(), 'hidden'] }],
/**
* Divide Width X
* @see https://tailwindcss.com/docs/divide-width
*/
'divide-x': [{ 'divide-x': [borderWidth] }],
/**
* Divide Width X Reverse
* @see https://tailwindcss.com/docs/divide-width
*/
'divide-x-reverse': ['divide-x-reverse'],
/**
* Divide Width Y
* @see https://tailwindcss.com/docs/divide-width
*/
'divide-y': [{ 'divide-y': [borderWidth] }],
/**
* Divide Width Y Reverse
* @see https://tailwindcss.com/docs/divide-width
*/
'divide-y-reverse': ['divide-y-reverse'],
/**
* Divide Opacity
* @see https://tailwindcss.com/docs/divide-opacity
*/
'divide-opacity': [{ 'divide-opacity': [opacity] }],
/**
* Divide Style
* @see https://tailwindcss.com/docs/divide-style
*/
'divide-style': [{ divide: getLineStyles() }],
/**
* Border Color
* @see https://tailwindcss.com/docs/border-color
*/
'border-color': [{ border: [borderColor] }],
/**
* Border Color X
* @see https://tailwindcss.com/docs/border-color
*/
'border-color-x': [{ 'border-x': [borderColor] }],
/**
* Border Color Y
* @see https://tailwindcss.com/docs/border-color
*/
'border-color-y': [{ 'border-y': [borderColor] }],
/**
* Border Color Top
* @see https://tailwindcss.com/docs/border-color
*/
'border-color-t': [{ 'border-t': [borderColor] }],
/**
* Border Color Right
* @see https://tailwindcss.com/docs/border-color
*/
'border-color-r': [{ 'border-r': [borderColor] }],
/**
* Border Color Bottom
* @see https://tailwindcss.com/docs/border-color
*/
'border-color-b': [{ 'border-b': [borderColor] }],
/**
* Border Color Left
* @see https://tailwindcss.com/docs/border-color
*/
'border-color-l': [{ 'border-l': [borderColor] }],
/**
* Divide Color
* @see https://tailwindcss.com/docs/divide-color
*/
'divide-color': [{ divide: [borderColor] }],
/**
* Outline Style
* @see https://tailwindcss.com/docs/outline-style
*/
'outline-style': [{ outline: ['', ...getLineStyles(), 'hidden'] }],
/**
* Outline Offset
* @see https://tailwindcss.com/docs/outline-offset
*/
'outline-offset': [{ 'outline-offset': [isLength] }],
/**
* Outline Width
* @see https://tailwindcss.com/docs/outline-width
*/
'outline-w': [{ outline: [isLength] }],
/**
* Outline Color
* @see https://tailwindcss.com/docs/outline-color
*/
'outline-color': [{ outline: [colors] }],
/**
* Ring Width
* @see https://tailwindcss.com/docs/ring-width
*/
'ring-w': [{ ring: getLengthWithEmpty() }],
/**
* Ring Width Inset
* @see https://tailwindcss.com/docs/ring-width
*/
'ring-w-inset': ['ring-inset'],
/**
* Ring Color
* @see https://tailwindcss.com/docs/ring-color
*/
'ring-color': [{ ring: [colors] }],
/**
* Ring Opacity
* @see https://tailwindcss.com/docs/ring-opacity
*/
'ring-opacity': [{ 'ring-opacity': [opacity] }],
/**
* Ring Offset Width
* @see https://tailwindcss.com/docs/ring-offset-width
*/
'ring-offset-w': [{ 'ring-offset': [isLength] }],
/**
* Ring Offset Color
* @see https://tailwindcss.com/docs/ring-offset-color
*/
'ring-offset-color': [{ 'ring-offset': [colors] }],
// Effects
/**
* Box Shadow
* @see https://tailwindcss.com/docs/box-shadow
*/
shadow: [{ shadow: ['', 'inner', 'none', isTshirtSize, isArbitraryShadow] }],
/**
* Box Shadow Color
* @see https://tailwindcss.com/docs/box-shadow-color
*/
'shadow-color': [{ shadow: [isAny] }],
/**
* Opacity
* @see https://tailwindcss.com/docs/opacity
*/
opacity: [{ opacity: [opacity] }],
/**
* Mix Beldn Mode
* @see https://tailwindcss.com/docs/mix-blend-mode
*/
'mix-blend': [{ 'mix-blend': getBlendModes() }],
/**
* Background Blend Mode
* @see https://tailwindcss.com/docs/background-blend-mode
*/
'bg-blend': [{ 'bg-blend': getBlendModes() }],
// Filters
/**
* Filter
* @deprecated since Tailwind CSS v3.0.0
* @see https://tailwindcss.com/docs/filter
*/
filter: [{ filter: ['', 'none'] }],
/**
* Blur
* @see https://tailwindcss.com/docs/blur
*/
blur: [{ blur: [blur] }],
/**
* Brightness
* @see https://tailwindcss.com/docs/brightness
*/
brightness: [{ brightness: [brightness] }],
/**
* Contrast
* @see https://tailwindcss.com/docs/contrast
*/
contrast: [{ contrast: [contrast] }],
/**
* Drop Shadow
* @see https://tailwindcss.com/docs/drop-shadow
*/
'drop-shadow': [{ 'drop-shadow': ['', 'none', isTshirtSize, isArbitraryValue] }],
/**
* Grayscale
* @see https://tailwindcss.com/docs/grayscale
*/
grayscale: [{ grayscale: [grayscale] }],
/**
* Hue Rotate
* @see https://tailwindcss.com/docs/hue-rotate
*/
'hue-rotate': [{ 'hue-rotate': [hueRotate] }],
/**
* Invert
* @see https://tailwindcss.com/docs/invert
*/
invert: [{ invert: [invert] }],
/**
* Saturate
* @see https://tailwindcss.com/docs/saturate
*/
saturate: [{ saturate: [saturate] }],
/**
* Sepia
* @see https://tailwindcss.com/docs/sepia
*/
sepia: [{ sepia: [sepia] }],
/**
* Backdrop Filter
* @deprecated since Tailwind CSS v3.0.0
* @see https://tailwindcss.com/docs/backdrop-filter
*/
'backdrop-filter': [{ 'backdrop-filter': ['', 'none'] }],
/**
* Backdrop Blur
* @see https://tailwindcss.com/docs/backdrop-blur
*/
'backdrop-blur': [{ 'backdrop-blur': [blur] }],
/**
* Backdrop Brightness
* @see https://tailwindcss.com/docs/backdrop-brightness
*/
'backdrop-brightness': [{ 'backdrop-brightness': [brightness] }],
/**
* Backdrop Contrast
* @see https://tailwindcss.com/docs/backdrop-contrast
*/
'backdrop-contrast': [{ 'backdrop-contrast': [contrast] }],
/**
* Backdrop Grayscale
* @see https://tailwindcss.com/docs/backdrop-grayscale
*/
'backdrop-grayscale': [{ 'backdrop-grayscale': [grayscale] }],
/**
* Backdrop Hue Rotate
* @see https://tailwindcss.com/docs/backdrop-hue-rotate
*/
'backdrop-hue-rotate': [{ 'backdrop-hue-rotate': [hueRotate] }],
/**
* Backdrop Invert
* @see https://tailwindcss.com/docs/backdrop-invert
*/
'backdrop-invert': [{ 'backdrop-invert': [invert] }],
/**
* Backdrop Opacity
* @see https://tailwindcss.com/docs/backdrop-opacity
*/
'backdrop-opacity': [{ 'backdrop-opacity': [opacity] }],
/**
* Backdrop Saturate
* @see https://tailwindcss.com/docs/backdrop-saturate
*/
'backdrop-saturate': [{ 'backdrop-saturate': [saturate] }],
/**
* Backdrop Sepia
* @see https://tailwindcss.com/docs/backdrop-sepia
*/
'backdrop-sepia': [{ 'backdrop-sepia': [sepia] }],
// Tables
/**
* Border Collapse
* @see https://tailwindcss.com/docs/border-collapse
*/
'border-collapse': [{ border: ['collapse', 'separate'] }],
/**
* Table Layout
* @see https://tailwindcss.com/docs/table-layout
*/
'table-layout': [{ table: ['auto', 'fixed'] }],
// Transitions and Animation
/**
* Tranisition Property
* @see https://tailwindcss.com/docs/transition-property
*/
transition: [
{
transition: [
'none',
'all',
'',
'colors',
'opacity',
'shadow',
'transform',
isArbitraryValue,
],
},
],
/**
* Transition Duration
* @see https://tailwindcss.com/docs/transition-duration
*/
duration: [{ duration: [isInteger] }],
/**
* Transition Timing Function
* @see https://tailwindcss.com/docs/transition-timing-function
*/
ease: [{ ease: ['linear', 'in', 'out', 'in-out', isArbitraryValue] }],
/**
* Transition Delay
* @see https://tailwindcss.com/docs/transition-delay
*/
delay: [{ delay: [isInteger] }],
/**
* Animation
* @see https://tailwindcss.com/docs/animation
*/
animate: [{ animate: ['none', 'spin', 'ping', 'pulse', 'bounce', isArbitraryValue] }],
// Transforms
/**
* Transform
* @see https://tailwindcss.com/docs/transform
*/
transform: [{ transform: ['', 'gpu', 'none'] }],
/**
* Scale
* @see https://tailwindcss.com/docs/scale
*/
scale: [{ scale: [scale] }],
/**
* Scale X
* @see https://tailwindcss.com/docs/scale
*/
'scale-x': [{ 'scale-x': [scale] }],
/**
* Scale Y
* @see https://tailwindcss.com/docs/scale
*/
'scale-y': [{ 'scale-y': [scale] }],
/**
* Rotate
* @see https://tailwindcss.com/docs/rotate
*/
rotate: [{ rotate: [isInteger, isArbitraryValue] }],
/**
* Translate X
* @see https://tailwindcss.com/docs/translate
*/
'translate-x': [{ 'translate-x': [translate] }],
/**
* Translate Y
* @see https://tailwindcss.com/docs/translate
*/
'translate-y': [{ 'translate-y': [translate] }],
/**
* Skew X
* @see https://tailwindcss.com/docs/skew
*/
'skew-x': [{ 'skew-x': [skew] }],
/**
* Skew Y
* @see https://tailwindcss.com/docs/skew
*/
'skew-y': [{ 'skew-y': [skew] }],
/**
* Transform Origin
* @see https://tailwindcss.com/docs/transform-origin
*/
'transform-origin': [
{
origin: [
'center',
'top',
'top-right',
'right',
'bottom-right',
'bottom',
'bottom-left',
'left',
'top-left',
isArbitraryValue,
],
},
],
// Interactivity
/**
* Accent Color
* @see https://tailwindcss.com/docs/accent-color
*/
accent: [{ accent: ['auto', colors] }],
/**
* Appearance
* @see https://tailwindcss.com/docs/appearance
*/
appearance: ['appearance-none'],
/**
* Cursor
* @see https://tailwindcss.com/docs/cursor
*/
cursor: [
{
cursor: [
'auto',
'default',
'pointer',
'wait',
'text',
'move',
'help',
'not-allowed',
'none',
'context-menu',
'progress',
'cell',
'crosshair',
'vertical-text',
'alias',
'copy',
'no-drop',
'grab',
'grabbing',
'all-scroll',
'col-resize',
'row-resize',
'n-resize',
'e-resize',
's-resize',
'w-resize',
'ne-resize',
'nw-resize',
'se-resize',
'sw-resize',
'ew-resize',
'ns-resize',
'nesw-resize',
'nwse-resize',
'zoom-in',
'zoom-out',
isArbitraryValue,
],
},
],
/**
* Caret Color
* @see https://tailwindcss.com/docs/just-in-time-mode#caret-color-utilities
*/
'caret-color': [{ caret: [colors] }],
/**
* Pointer Events
* @see https://tailwindcss.com/docs/pointer-events
*/
'pointer-events': [{ 'pointer-events': ['none', 'auto'] }],
/**
* Resize
* @see https://tailwindcss.com/docs/resize
*/
resize: [{ resize: ['none', 'y', 'x', ''] }],
/**
* Scroll Behavior
* @see https://tailwindcss.com/docs/scroll-behavior
*/
'scroll-behavior': [{ scroll: ['auto', 'smooth'] }],
/**
* Scroll Margin
* @see https://tailwindcss.com/docs/scroll-margin
*/
'scroll-m': [{ 'scroll-m': [spacing] }],
/**
* Scroll Margin X
* @see https://tailwindcss.com/docs/scroll-margin
*/
'scroll-mx': [{ 'scroll-mx': [spacing] }],
/**
* Scroll Margin Y
* @see https://tailwindcss.com/docs/scroll-margin
*/
'scroll-my': [{ 'scroll-my': [spacing] }],
/**
* Scroll Margin Top
* @see https://tailwindcss.com/docs/scroll-margin
*/
'scroll-mt': [{ 'scroll-mt': [spacing] }],
/**
* Scroll Margin Right
* @see https://tailwindcss.com/docs/scroll-margin
*/
'scroll-mr': [{ 'scroll-mr': [spacing] }],
/**
* Scroll Margin Bottom
* @see https://tailwindcss.com/docs/scroll-margin
*/
'scroll-mb': [{ 'scroll-mb': [spacing] }],
/**
* Scroll Margin Left
* @see https://tailwindcss.com/docs/scroll-margin
*/
'scroll-ml': [{ 'scroll-ml': [spacing] }],
/**
* Scroll Padding
* @see https://tailwindcss.com/docs/scroll-padding
*/
'scroll-p': [{ 'scroll-p': [spacing] }],
/**
* Scroll Padding X
* @see https://tailwindcss.com/docs/scroll-padding
*/
'scroll-px': [{ 'scroll-px': [spacing] }],
/**
* Scroll Padding Y
* @see https://tailwindcss.com/docs/scroll-padding
*/
'scroll-py': [{ 'scroll-py': [spacing] }],
/**
* Scroll Padding Top
* @see https://tailwindcss.com/docs/scroll-padding
*/
'scroll-pt': [{ 'scroll-pt': [spacing] }],
/**
* Scroll Padding Right
* @see https://tailwindcss.com/docs/scroll-padding
*/
'scroll-pr': [{ 'scroll-pr': [spacing] }],
/**
* Scroll Padding Bottom
* @see https://tailwindcss.com/docs/scroll-padding
*/
'scroll-pb': [{ 'scroll-pb': [spacing] }],
/**
* Scroll Padding Left
* @see https://tailwindcss.com/docs/scroll-padding
*/
'scroll-pl': [{ 'scroll-pl': [spacing] }],
/**
* Scroll Snap Align
* @see https://tailwindcss.com/docs/scroll-snap-align
*/
'snap-align': [{ snap: ['start', 'end', 'center', 'align-none'] }],
/**
* Scroll Snap Stop
* @see https://tailwindcss.com/docs/scroll-snap-stop
*/
'snap-stop': [{ snap: ['normal', 'always'] }],
/**
* Scroll Snap Type
* @see https://tailwindcss.com/docs/scroll-snap-type
*/
'snap-type': [{ snap: ['none', 'x', 'y', 'both'] }],
/**
* Scroll Snap Type Strictness
* @see https://tailwindcss.com/docs/scroll-snap-type
*/
'snap-strictness': [{ snap: ['mandatory', 'proximity'] }],
/**
* Touch Action
* @see https://tailwindcss.com/docs/touch-action
*/
touch: [
{
touch: [
'auto',
'none',
'pinch-zoom',
'manipulation',
{ pan: ['x', 'left', 'right', 'y', 'up', 'down'] },
],
},
],
/**
* User Select
* @see https://tailwindcss.com/docs/user-select
*/
select: [{ select: ['none', 'text', 'all', 'auto'] }],
/**
* Will Change
* @see https://tailwindcss.com/docs/will-change
*/
'will-change': [
{ 'will-change': ['auto', 'scroll', 'contents', 'transform', isArbitraryValue] },
],
// SVG
/**
* Fill
* @see https://tailwindcss.com/docs/fill
*/
fill: [{ fill: [colors] }],
/**
* Stroke Width
* @see https://tailwindcss.com/docs/stroke-width
*/
'stroke-w': [{ stroke: [isLength] }],
/**
* Stroke
* @see https://tailwindcss.com/docs/stroke
*/
stroke: [{ stroke: [colors] }],
// Accessibility
/**
* Screen Readers
* @see https://tailwindcss.com/docs/screen-readers
*/
sr: ['sr-only', 'not-sr-only'],
},
conflictingClassGroups: {
overflow: ['overflow-x', 'overflow-y'],
overscroll: ['overscroll-x', 'overscroll-y'],
inset: ['inset-x', 'inset-y', 'top', 'right', 'bottom', 'left'],
'inset-x': ['right', 'left'],
'inset-y': ['top', 'bottom'],
flex: ['basis', 'grow', 'shrink'],
'col-start-end': ['col-start', 'col-end'],
'row-start-end': ['row-start', 'row-end'],
gap: ['gap-x', 'gap-y'],
p: ['px', 'py', 'pt', 'pr', 'pb', 'pl'],
px: ['pr', 'pl'],
py: ['pt', 'pb'],
m: ['mx', 'my', 'mt', 'mr', 'mb', 'ml'],
mx: ['mr', 'ml'],
my: ['mt', 'mb'],
'font-size': ['leading'],
'fvn-normal': [
'fvn-ordinal',
'fvn-slashed-zero',
'fvn-figure',
'fvn-spacing',
'fvn-fraction',
],
'fvn-ordinal': ['fvn-normal'],
'fvn-slashed-zero': ['fvn-normal'],
'fvn-figure': ['fvn-normal'],
'fvn-spacing': ['fvn-normal'],
'fvn-fraction': ['fvn-normal'],
rounded: [
'rounded-t',
'rounded-r',
'rounded-b',
'rounded-l',
'rounded-tl',
'rounded-tr',
'rounded-br',
'rounded-bl',
],
'rounded-t': ['rounded-tl', 'rounded-tr'],
'rounded-r': ['rounded-tr', 'rounded-br'],
'rounded-b': ['rounded-br', 'rounded-bl'],
'rounded-l': ['rounded-tl', 'rounded-bl'],
'border-w': ['border-w-t', 'border-w-r', 'border-w-b', 'border-w-l'],
'border-w-x': ['border-w-r', 'border-w-l'],
'border-w-y': ['border-w-t', 'border-w-b'],
'border-color': [
'border-color-t',
'border-color-r',
'border-color-b',
'border-color-l',
],
'border-color-x': ['border-color-r', 'border-color-l'],
'border-color-y': ['border-color-t', 'border-color-b'],
'scroll-m': [
'scroll-mx',
'scroll-my',
'scroll-mt',
'scroll-mr',
'scroll-mb',
'scroll-ml',
],
'scroll-mx': ['scroll-mr', 'scroll-ml'],
'scroll-my': ['scroll-mt', 'scroll-mb'],
'scroll-p': [
'scroll-px',
'scroll-py',
'scroll-pt',
'scroll-pr',
'scroll-pb',
'scroll-pl',
],
'scroll-px': ['scroll-pr', 'scroll-pl'],
'scroll-py': ['scroll-pt', 'scroll-pb'],
},
} as const
} | the_stack |
import { getCoordinate } from '@antv/coord';
import { isNumberEqual } from '@antv/util';
import PolarLabel from '../../../../src/geometry/label/polar';
import Point from '../../../../src/geometry/point';
import { getTheme } from '../../../../src/theme/';
import { createCanvas, createDiv } from '../../../util/dom';
import { createScale } from '../../../util/scale';
const Theme = getTheme('default');
const PolarCoord = getCoordinate('polar');
describe('polar labels', () => {
const div = createDiv();
const canvas = createCanvas({
container: div,
width: 500,
height: 500,
});
const coord = new PolarCoord({
start: { x: 0, y: 100 },
end: { x: 100, y: 0 },
});
const data = [
{ x: 50, y: 10, z: '1' },
{ x: 100, y: 50, z: '2' },
{ x: 10, y: 50, z: '3' },
];
const points = [
{ x: 50, y: 10, z: 0, _origin: { x: 50, y: 10, z: '1' } },
{ x: 100, y: 50, z: 1, _origin: { x: 100, y: 50, z: '2' } },
{ x: 10, y: 50, z: 2, _origin: { x: 10, y: 50, z: '3' } },
];
const point = coord.convert({
x: 0.125,
y: 0.8,
});
// @ts-ignore
point.z = 3;
// @ts-ignore
point._origin = { x: point.z, y: point.y, z: '4' };
// @ts-ignore
points.push(point);
const points1 = [
{
x: 50,
y: [10, 20],
z: ['1', '2'],
_origin: { x: 50, y: [10, 20], z: ['1', '2'] },
},
{
x: [60, 80],
y: [50, 50],
z: ['3', '4'],
_origin: { x: [60, 80], y: [50, 50], z: ['3', '4'] },
},
];
const data1 = [
{ x: 50, y: [10, 20], z: ['1', '2'] },
{ x: [60, 80], y: [50, 50], z: ['3', '4'] },
];
describe('one point one label', () => {
const scales = {
x: createScale('x', data),
y: createScale('y', data),
z: createScale('z', data),
};
const pointGeom = new Point({
data,
scales,
container: canvas.addGroup(),
labelsContainer: canvas.addGroup(),
coordinate: coord,
});
pointGeom.position('x*y').label('z', { offset: 10 });
pointGeom.init({
theme: Theme,
});
const gLabels = new PolarLabel(pointGeom);
let items;
it('get items', () => {
items = gLabels.getLabelItems(points);
expect(items.length).toBe(points.length);
});
it('first point rotate 0', () => {
const first = items[0];
expect(first.x).toBe(points[0].x);
expect(first.y).toBe(points[0].y - 10);
expect(first.rotate).toBe(0);
});
it('second point rotate 90', () => {
const second = items[1];
expect(second.x).toBe(points[1].x + 10);
expect(second.y).toBe(points[1].y);
expect(second.rotate).toBe(Math.PI / 2);
});
it('third rotate 90', () => {
// tslint:disable-next-line: no-shadowed-variable
const point = items[2];
expect(point.x).toBe(points[2].x - 10);
expect(isNumberEqual(point.y, points[2].y)).toBe(true);
expect(point.rotate).toBe(Math.PI / 2);
});
it('point rotate 45', () => {
// tslint:disable-next-line: no-shadowed-variable
const point = items[3];
const tmp = coord.convert({
x: 0.125,
y: 1,
});
expect(point.x).toBe(tmp.x);
expect(point.y).toBe(tmp.y);
expect(point.rotate).toBe((45 / 180) * Math.PI);
});
});
describe('one point one label,inner text', () => {
const scales = {
x: createScale('x', data),
y: createScale('y', data),
z: createScale('z', data),
};
const pointGeom = new Point({
data,
scales,
container: canvas.addGroup(),
labelsContainer: canvas.addGroup(),
coordinate: coord,
});
pointGeom.position('x*y').label('z', { offset: -10 });
pointGeom.init({
theme: Theme,
});
const gLabels = new PolarLabel(pointGeom);
let items;
it('get items', () => {
items = gLabels.getLabelItems(points);
expect(items.length).toBe(points.length);
});
it('first point rotate 0', () => {
const first = items[0];
expect(first.x).toBe(points[0].x);
expect(first.y).toBe(points[0].y + 10);
expect(first.rotate).toBe(0);
});
it('second point rotate 90', () => {
const second = items[1];
expect(second.x).toBe(points[1].x - 10);
expect(second.y).toBe(points[1].y);
expect(second.rotate).toBe((90 / 180) * Math.PI);
});
it('third rotate 90', () => {
// tslint:disable-next-line: no-shadowed-variable
const point = items[2];
expect(point.x).toBe(points[2].x + 10);
expect(isNumberEqual(point.y, points[2].y)).toBe(true);
expect(point.rotate).toBe(Math.PI / 2);
});
it('point rotate 45', () => {
// tslint:disable-next-line: no-shadowed-variable
const point = items[3];
const tmp = coord.convert({
x: 0.125,
y: 0.6,
});
expect(point.x).toBe(tmp.x);
expect(point.y).toBe(tmp.y);
expect(point.rotate).toBe((45 / 180) * Math.PI);
});
});
describe('one point two labels,outer text', () => {
const scales = {
x: createScale('x', data1),
y: createScale('y', data1),
z: createScale('z', data1),
};
const pointGeom = new Point({
data: data1,
scales,
container: canvas.addGroup(),
labelsContainer: canvas.addGroup(),
coordinate: coord,
});
pointGeom.position('x*y').label('z', { offset: 10 });
pointGeom.init({
theme: Theme,
});
const gLabels = new PolarLabel(pointGeom);
let items;
it('get items', () => {
items = gLabels.getLabelItems(points1);
expect(items.length).toBe(points1.length * 2);
});
it('point rotate 0', () => {
const first = items[0];
expect(first.x).toBe(points1[0].x);
expect(first.y).toBe(points1[0].y[0] + 10);
expect(first.rotate).toBe(0);
const second = items[1];
expect(second.x).toBe(points1[0].x);
expect(second.y).toBe(points1[0].y[1] - 10);
expect(second.rotate).toBe(0);
});
it('point rotate 90', () => {
// tslint:disable-next-line: no-shadowed-variable
let point = items[2];
expect(point.x).toBe(points1[1].x[0] - 10);
expect(point.y).toBe(points1[1].y[0]);
point = items[3];
expect(point.x).toBe(points1[1].x[1] + 10);
expect(point.y).toBe(points1[1].y[1]);
});
});
describe('one point two label,inner text', () => {
const scales = {
x: createScale('x', data1),
y: createScale('y', data1),
z: createScale('z', data1),
};
const pointGeom = new Point({
data: data1,
scales,
container: canvas.addGroup(),
labelsContainer: canvas.addGroup(),
coordinate: coord,
});
pointGeom.position('x*y').label('z', { offset: -10 });
pointGeom.init({
theme: Theme,
});
const gLabels = new PolarLabel(pointGeom);
let items;
it('get items', () => {
items = gLabels.getLabelItems(points1);
expect(items.length).toBe(points1.length * 2);
});
it('point rotate 0', () => {
const first = items[0];
expect(first.x).toBe(points1[0].x);
expect(first.y).toBe(points1[0].y[0] - 10);
expect(first.rotate).toBe(0);
const second = items[1];
expect(second.x).toBe(points1[0].x);
expect(second.y).toBe(points1[0].y[1] + 10);
expect(second.rotate).toBe(0);
});
it('point rotate 90', () => {
// tslint:disable-next-line: no-shadowed-variable
let point = items[2];
expect(point.x).toBe(points1[1].x[0] + 10);
expect(point.y).toBe(points1[1].y[0]);
point = items[3];
expect(point.x).toBe(points1[1].x[1] - 10);
expect(point.y).toBe(points1[1].y[1]);
});
});
describe('transpose labels', () => {
const polarCoord = new PolarCoord({
start: {
x: 0,
y: 100,
},
end: {
x: 100,
y: 0,
},
});
polarCoord.transpose();
describe('offset < 0', () => {
const scales = {
x: createScale('x', data),
y: createScale('y', data),
z: createScale('z', data),
};
const pointGeom = new Point({
data,
scales,
container: canvas.addGroup(),
labelsContainer: canvas.addGroup(),
coordinate: polarCoord,
});
pointGeom.position('x*y').label('z', { offset: -10 });
pointGeom.init({
theme: Theme,
});
const gLabels = new PolarLabel(pointGeom);
let items;
it('get items', () => {
items = gLabels.getLabelItems(points);
expect(items.length).toBe(points.length);
});
it('first point rotate 0', () => {
const first = items[0];
expect(first.x).toBe(40.078432583507784);
expect(first.y).toBe(11.25);
expect(first.rotate).toBe(0);
});
it('second point rotate 90', () => {
const second = items[1];
expect(second.x).toBe(99);
expect(second.y).toBe(40.0501256289338);
expect(second.rotate).toBe(Math.PI / 2);
});
it('third rotate 90', () => {
// tslint:disable-next-line: no-shadowed-variable
const point = items[2];
expect(+point.x.toFixed(2)).toBe(11.25);
expect(point.y).toBe(59.92156741649222);
expect(point.rotate).toBe(Math.PI / 2);
});
});
describe('offset > 0', () => {
const scales = {
x: createScale('x', data),
y: createScale('y', data),
z: createScale('z', data),
};
const pointGeom = new Point({
data,
scales,
container: canvas.addGroup(),
labelsContainer: canvas.addGroup(),
coordinate: polarCoord,
});
pointGeom.position('x*y').label('z', { offset: 10 });
pointGeom.init({
theme: Theme,
});
const gLabels = new PolarLabel(pointGeom);
let items;
it('get items', () => {
items = gLabels.getLabelItems(points);
expect(items.length).toBe(points.length);
});
it('first point rotate 0', () => {
const first = items[0];
expect(first.x).toBe(59.92156741649222);
expect(first.y).toBe(11.25);
expect(first.rotate).toBe(0);
});
it('second point rotate 90', () => {
const second = items[1];
expect(second.x).toBe(99);
expect(second.y).toBe(59.9498743710662);
expect(second.rotate).toBe(Math.PI / 2);
});
it('third rotate 90', () => {
// tslint:disable-next-line: no-shadowed-variable
const point = items[2];
expect(point.x).toBe(11.25);
expect(point.y).toBe(40.078432583507784);
expect(point.rotate).toBe(Math.PI / 2);
});
});
});
}); | the_stack |
import { Callback } from "@siteimprove/alfa-callback";
import { Mapper } from "@siteimprove/alfa-mapper";
import { None, Option } from "@siteimprove/alfa-option";
import { Predicate } from "@siteimprove/alfa-predicate";
import { Result, Err } from "@siteimprove/alfa-result";
import { Refinement } from "@siteimprove/alfa-refinement";
const { not } = Predicate;
/**
* @public
*/
export type Parser<I, T, E = never, A extends Array<unknown> = []> = (
input: I,
...args: A
) => Result<[I, T], E>;
/**
* @public
*/
export namespace Parser {
export type Infallible<I, T, A extends Array<unknown> = []> = (
input: I,
...args: A
) => [I, T];
export function map<I, T, U, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>,
mapper: Mapper<T, U>
): Parser<I, U, E, A> {
return (input, ...args) =>
parser(input, ...args).map(([remainder, value]) => [
remainder,
mapper(value),
]);
}
export function mapResult<I, T, U, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>,
mapper: Mapper<T, Result<U, E>>
): Parser<I, U, E, A> {
return (input, ...args) =>
parser(input, ...args).flatMap(([remainder, value]) =>
mapper(value).map((result) => [remainder, result])
);
}
export function flatMap<I, T, U, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>,
mapper: Mapper<T, Parser<I, U, E, A>>
): Parser<I, U, E, A> {
return (input, ...args) =>
parser(input, ...args).flatMap(([remainder, value]) =>
mapper(value)(remainder, ...args)
);
}
export function filter<I, T, U extends T, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>,
refinement: Refinement<T, U>,
ifError: Mapper<T, E>
): Parser<I, U, E, A>;
export function filter<I, T, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>,
predicate: Predicate<T>,
ifError: Mapper<T, E>
): Parser<I, T, E, A>;
export function filter<I, T, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>,
predicate: Predicate<T>,
ifError: Mapper<T, E>
): Parser<I, T, E, A> {
return mapResult(parser, (value) =>
predicate(value) ? Result.of(value) : Err.of(ifError(value))
);
}
export function reject<I, T, U extends T, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>,
refinement: Refinement<T, U>,
ifError: Mapper<T, E>
): Parser<I, Exclude<T, U>, E, A>;
export function reject<I, T, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>,
predicate: Predicate<T>,
ifError: Mapper<T, E>
): Parser<I, T, E, A>;
export function reject<I, T, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>,
predicate: Predicate<T>,
ifError: Mapper<T, E>
): Parser<I, T, E, A> {
return filter(parser, not(predicate), ifError);
}
export function zeroOrMore<I, T, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>
): Parser<I, Array<T>, E, A> {
return takeAtLeast(parser, 0);
}
export function oneOrMore<I, T, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>
): Parser<I, Array<T>, E, A> {
return takeAtLeast(parser, 1);
}
export function take<I, T, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>,
count: number
): Parser<I, Array<T>, E, A> {
return takeBetween(parser, count, count);
}
export function takeBetween<I, T, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>,
lower: number,
upper: number
): Parser<I, Array<T>, E, A> {
return (input, ...args) => {
const values: Array<T> = [];
let value: T;
for (let i = 0; i < upper; i++) {
const result = parser(input, ...args);
if (result.isOk()) {
[input, value] = result.get();
values.push(value);
} else if (result.isErr()) {
if (values.length < lower) {
return result;
} else {
break;
}
}
}
return Result.of([input, values]);
};
}
export function takeAtLeast<I, T, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>,
lower: number
): Parser<I, Array<T>, E, A> {
return takeBetween(parser, lower, Infinity);
}
export function takeAtMost<I, T, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>,
upper: number
): Parser<I, Array<T>, E, A> {
return takeBetween(parser, 0, upper);
}
export function takeUntil<I, T, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>,
condition: Parser<I, unknown, E, A>
): Parser<I, Array<T>, E, A> {
return (input, ...args) => {
const values: Array<T> = [];
let value: T;
while (true) {
if (condition(input, ...args).isOk()) {
return Result.of([input, values]);
}
const result = parser(input, ...args);
if (result.isOk()) {
[input, value] = result.get();
values.push(value);
} else if (result.isErr()) {
return result;
}
}
};
}
export function peek<I, T, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>
): Parser<I, T, E, A> {
return (input, ...args) =>
parser(input, ...args).map(([, value]) => [input, value]);
}
export function tee<I, T, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>,
callback: Callback<T, void, [remainder: I, ...args: A]>
): Parser<I, T, E, A> {
return (input, ...args) =>
parser(input, ...args).tee(([remainder, result]) => {
callback(result, remainder, ...args);
});
}
export function teeErr<I, T, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>,
callback: Callback<E, void, A>
): Parser<I, T, E, A> {
return (input, ...args) =>
parser(input, ...args).teeErr((err) => {
callback(err, ...args);
});
}
export function option<I, T, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>
): Parser<I, Option<T>, E, A> {
return (input, ...args) => {
const result = parser(input, ...args);
if (result.isOk()) {
const [input, value] = result.get();
return Result.of([input, Option.of(value)]);
}
return Result.of([input, None]);
};
}
export function either<I, T, U, E, A extends Array<unknown> = []>(
left: Parser<I, T, E, A>,
right: Parser<I, U, E, A>
): Parser<I, T | U, E, A>;
export function either<I, T, E, A extends Array<unknown> = []>(
left: Parser<I, T, E, A>,
right: Parser<I, T, E, A>,
...rest: Array<Parser<I, T, E, A>>
): Parser<I, T, E, A>;
export function either<I, T, E, A extends Array<unknown> = []>(
...parsers: Array<Parser<I, T, E, A>>
): Parser<I, T, E, A> {
return (input, ...args) => {
let error: Err<E>;
for (const parser of parsers) {
const result = parser(input, ...args);
if (result.isErr()) {
error = result;
} else {
return result;
}
}
// Per the function overloads, there will always be at least one parser
// specified. It is therefore safe to assert that if we get this far, at
// least one parser will have produced an error.
return error!;
};
}
export function pair<I, T, U, E, A extends Array<unknown> = []>(
left: Parser<I, T, E, A>,
right: Parser<I, U, E, A>
): Parser<I, [T, U], E, A> {
return flatMap(left, (left) => map(right, (right) => [left, right]));
}
export function left<I, T, U, E, A extends Array<unknown> = []>(
left: Parser<I, T, E, A>,
right: Parser<I, U, E, A>
): Parser<I, T, E, A> {
return flatMap(left, (left) => map(right, () => left));
}
export function right<I, T, U, E, A extends Array<unknown> = []>(
left: Parser<I, T, E, A>,
right: Parser<I, U, E, A>
): Parser<I, U, E, A> {
return flatMap(left, () => map(right, (right) => right));
}
export function delimited<I, T, E, A extends Array<unknown> = []>(
parser: Parser<I, unknown, E, A>,
separator: Parser<I, T, E, A>
): Parser<I, T, E, A>;
export function delimited<I, T, E, A extends Array<unknown> = []>(
left: Parser<I, unknown, E, A>,
separator: Parser<I, T, E, A>,
right: Parser<I, unknown, E, A>
): Parser<I, T, E, A>;
export function delimited<I, T, E, A extends Array<unknown> = []>(
left: Parser<I, unknown, E, A>,
separator: Parser<I, T, E, A>,
right: Parser<I, unknown, E, A> = left
): Parser<I, T, E, A> {
return flatMap(left, () =>
flatMap(separator, (separator) => map(right, () => separator))
);
}
export function separated<I, T, U, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>,
separator: Parser<I, unknown, E, A>
): Parser<I, [T, T], E, A>;
export function separated<I, T, U, E, A extends Array<unknown> = []>(
left: Parser<I, T, E, A>,
separator: Parser<I, unknown, E, A>,
right: Parser<I, U, E, A>
): Parser<I, [T, U], E, A>;
export function separated<I, T, E, A extends Array<unknown> = []>(
left: Parser<I, T, E, A>,
separator: Parser<I, unknown, E, A>,
right: Parser<I, T, E, A> = left
): Parser<I, [T, T], E, A> {
return flatMap(left, (left) =>
flatMap(separator, () => map(right, (right) => [left, right]))
);
}
export function separatedList<I, T, E, A extends Array<unknown> = []>(
parser: Parser<I, T, E, A>,
separator: Parser<I, unknown, E, A>
): Parser<I, Array<T>, E, A> {
return map(
pair(parser, zeroOrMore(right(separator, parser))),
([first, rest]) => {
rest.unshift(first);
return rest;
}
);
}
export function end<I extends Iterable<unknown>, E>(
ifError: Mapper<I extends Iterable<infer T> ? T : unknown, E>
): Parser<I, void, E> {
return (input) => {
for (const value of input) {
return Err.of(ifError(value as any));
}
return Result.of([input, undefined]);
};
}
/**
* @deprecated Use `end()`
*/
export const eof = end;
} | the_stack |
import * as pb_1 from "google-protobuf";
export namespace common.asset_transfer {
export class AssetPledge extends pb_1.Message {
constructor(data?: any[] | {
assetDetails?: Uint8Array;
localNetworkID?: string;
remoteNetworkID?: string;
recipient?: string;
expiryTimeSecs?: number;
}) {
super();
pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], []);
if (!Array.isArray(data) && typeof data == "object") {
if ("assetDetails" in data && data.assetDetails != undefined) {
this.assetDetails = data.assetDetails;
}
if ("localNetworkID" in data && data.localNetworkID != undefined) {
this.localNetworkID = data.localNetworkID;
}
if ("remoteNetworkID" in data && data.remoteNetworkID != undefined) {
this.remoteNetworkID = data.remoteNetworkID;
}
if ("recipient" in data && data.recipient != undefined) {
this.recipient = data.recipient;
}
if ("expiryTimeSecs" in data && data.expiryTimeSecs != undefined) {
this.expiryTimeSecs = data.expiryTimeSecs;
}
}
}
get assetDetails() {
return pb_1.Message.getField(this, 1) as Uint8Array;
}
set assetDetails(value: Uint8Array) {
pb_1.Message.setField(this, 1, value);
}
get localNetworkID() {
return pb_1.Message.getField(this, 2) as string;
}
set localNetworkID(value: string) {
pb_1.Message.setField(this, 2, value);
}
get remoteNetworkID() {
return pb_1.Message.getField(this, 3) as string;
}
set remoteNetworkID(value: string) {
pb_1.Message.setField(this, 3, value);
}
get recipient() {
return pb_1.Message.getField(this, 4) as string;
}
set recipient(value: string) {
pb_1.Message.setField(this, 4, value);
}
get expiryTimeSecs() {
return pb_1.Message.getField(this, 5) as number;
}
set expiryTimeSecs(value: number) {
pb_1.Message.setField(this, 5, value);
}
static fromObject(data: {
assetDetails?: Uint8Array;
localNetworkID?: string;
remoteNetworkID?: string;
recipient?: string;
expiryTimeSecs?: number;
}) {
const message = new AssetPledge({});
if (data.assetDetails != null) {
message.assetDetails = data.assetDetails;
}
if (data.localNetworkID != null) {
message.localNetworkID = data.localNetworkID;
}
if (data.remoteNetworkID != null) {
message.remoteNetworkID = data.remoteNetworkID;
}
if (data.recipient != null) {
message.recipient = data.recipient;
}
if (data.expiryTimeSecs != null) {
message.expiryTimeSecs = data.expiryTimeSecs;
}
return message;
}
toObject() {
const data: {
assetDetails?: Uint8Array;
localNetworkID?: string;
remoteNetworkID?: string;
recipient?: string;
expiryTimeSecs?: number;
} = {};
if (this.assetDetails != null) {
data.assetDetails = this.assetDetails;
}
if (this.localNetworkID != null) {
data.localNetworkID = this.localNetworkID;
}
if (this.remoteNetworkID != null) {
data.remoteNetworkID = this.remoteNetworkID;
}
if (this.recipient != null) {
data.recipient = this.recipient;
}
if (this.expiryTimeSecs != null) {
data.expiryTimeSecs = this.expiryTimeSecs;
}
return data;
}
serialize(): Uint8Array;
serialize(w: pb_1.BinaryWriter): void;
serialize(w?: pb_1.BinaryWriter): Uint8Array | void {
const writer = w || new pb_1.BinaryWriter();
if (this.assetDetails !== undefined)
writer.writeBytes(1, this.assetDetails);
if (typeof this.localNetworkID === "string" && this.localNetworkID.length)
writer.writeString(2, this.localNetworkID);
if (typeof this.remoteNetworkID === "string" && this.remoteNetworkID.length)
writer.writeString(3, this.remoteNetworkID);
if (typeof this.recipient === "string" && this.recipient.length)
writer.writeString(4, this.recipient);
if (this.expiryTimeSecs !== undefined)
writer.writeUint64(5, this.expiryTimeSecs);
if (!w)
return writer.getResultBuffer();
}
static deserialize(bytes: Uint8Array | pb_1.BinaryReader): AssetPledge {
const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new AssetPledge();
while (reader.nextField()) {
if (reader.isEndGroup())
break;
switch (reader.getFieldNumber()) {
case 1:
message.assetDetails = reader.readBytes();
break;
case 2:
message.localNetworkID = reader.readString();
break;
case 3:
message.remoteNetworkID = reader.readString();
break;
case 4:
message.recipient = reader.readString();
break;
case 5:
message.expiryTimeSecs = reader.readUint64();
break;
default: reader.skipField();
}
}
return message;
}
serializeBinary(): Uint8Array {
return this.serialize();
}
static deserializeBinary(bytes: Uint8Array): AssetPledge {
return AssetPledge.deserialize(bytes);
}
}
export class AssetClaimStatus extends pb_1.Message {
constructor(data?: any[] | {
assetDetails?: Uint8Array;
localNetworkID?: string;
remoteNetworkID?: string;
recipient?: string;
claimStatus?: boolean;
expiryTimeSecs?: number;
expirationStatus?: boolean;
}) {
super();
pb_1.Message.initialize(this, Array.isArray(data) ? data : [], 0, -1, [], []);
if (!Array.isArray(data) && typeof data == "object") {
if ("assetDetails" in data && data.assetDetails != undefined) {
this.assetDetails = data.assetDetails;
}
if ("localNetworkID" in data && data.localNetworkID != undefined) {
this.localNetworkID = data.localNetworkID;
}
if ("remoteNetworkID" in data && data.remoteNetworkID != undefined) {
this.remoteNetworkID = data.remoteNetworkID;
}
if ("recipient" in data && data.recipient != undefined) {
this.recipient = data.recipient;
}
if ("claimStatus" in data && data.claimStatus != undefined) {
this.claimStatus = data.claimStatus;
}
if ("expiryTimeSecs" in data && data.expiryTimeSecs != undefined) {
this.expiryTimeSecs = data.expiryTimeSecs;
}
if ("expirationStatus" in data && data.expirationStatus != undefined) {
this.expirationStatus = data.expirationStatus;
}
}
}
get assetDetails() {
return pb_1.Message.getField(this, 1) as Uint8Array;
}
set assetDetails(value: Uint8Array) {
pb_1.Message.setField(this, 1, value);
}
get localNetworkID() {
return pb_1.Message.getField(this, 2) as string;
}
set localNetworkID(value: string) {
pb_1.Message.setField(this, 2, value);
}
get remoteNetworkID() {
return pb_1.Message.getField(this, 3) as string;
}
set remoteNetworkID(value: string) {
pb_1.Message.setField(this, 3, value);
}
get recipient() {
return pb_1.Message.getField(this, 4) as string;
}
set recipient(value: string) {
pb_1.Message.setField(this, 4, value);
}
get claimStatus() {
return pb_1.Message.getField(this, 5) as boolean;
}
set claimStatus(value: boolean) {
pb_1.Message.setField(this, 5, value);
}
get expiryTimeSecs() {
return pb_1.Message.getField(this, 6) as number;
}
set expiryTimeSecs(value: number) {
pb_1.Message.setField(this, 6, value);
}
get expirationStatus() {
return pb_1.Message.getField(this, 7) as boolean;
}
set expirationStatus(value: boolean) {
pb_1.Message.setField(this, 7, value);
}
static fromObject(data: {
assetDetails?: Uint8Array;
localNetworkID?: string;
remoteNetworkID?: string;
recipient?: string;
claimStatus?: boolean;
expiryTimeSecs?: number;
expirationStatus?: boolean;
}) {
const message = new AssetClaimStatus({});
if (data.assetDetails != null) {
message.assetDetails = data.assetDetails;
}
if (data.localNetworkID != null) {
message.localNetworkID = data.localNetworkID;
}
if (data.remoteNetworkID != null) {
message.remoteNetworkID = data.remoteNetworkID;
}
if (data.recipient != null) {
message.recipient = data.recipient;
}
if (data.claimStatus != null) {
message.claimStatus = data.claimStatus;
}
if (data.expiryTimeSecs != null) {
message.expiryTimeSecs = data.expiryTimeSecs;
}
if (data.expirationStatus != null) {
message.expirationStatus = data.expirationStatus;
}
return message;
}
toObject() {
const data: {
assetDetails?: Uint8Array;
localNetworkID?: string;
remoteNetworkID?: string;
recipient?: string;
claimStatus?: boolean;
expiryTimeSecs?: number;
expirationStatus?: boolean;
} = {};
if (this.assetDetails != null) {
data.assetDetails = this.assetDetails;
}
if (this.localNetworkID != null) {
data.localNetworkID = this.localNetworkID;
}
if (this.remoteNetworkID != null) {
data.remoteNetworkID = this.remoteNetworkID;
}
if (this.recipient != null) {
data.recipient = this.recipient;
}
if (this.claimStatus != null) {
data.claimStatus = this.claimStatus;
}
if (this.expiryTimeSecs != null) {
data.expiryTimeSecs = this.expiryTimeSecs;
}
if (this.expirationStatus != null) {
data.expirationStatus = this.expirationStatus;
}
return data;
}
serialize(): Uint8Array;
serialize(w: pb_1.BinaryWriter): void;
serialize(w?: pb_1.BinaryWriter): Uint8Array | void {
const writer = w || new pb_1.BinaryWriter();
if (this.assetDetails !== undefined)
writer.writeBytes(1, this.assetDetails);
if (typeof this.localNetworkID === "string" && this.localNetworkID.length)
writer.writeString(2, this.localNetworkID);
if (typeof this.remoteNetworkID === "string" && this.remoteNetworkID.length)
writer.writeString(3, this.remoteNetworkID);
if (typeof this.recipient === "string" && this.recipient.length)
writer.writeString(4, this.recipient);
if (this.claimStatus !== undefined)
writer.writeBool(5, this.claimStatus);
if (this.expiryTimeSecs !== undefined)
writer.writeUint64(6, this.expiryTimeSecs);
if (this.expirationStatus !== undefined)
writer.writeBool(7, this.expirationStatus);
if (!w)
return writer.getResultBuffer();
}
static deserialize(bytes: Uint8Array | pb_1.BinaryReader): AssetClaimStatus {
const reader = bytes instanceof pb_1.BinaryReader ? bytes : new pb_1.BinaryReader(bytes), message = new AssetClaimStatus();
while (reader.nextField()) {
if (reader.isEndGroup())
break;
switch (reader.getFieldNumber()) {
case 1:
message.assetDetails = reader.readBytes();
break;
case 2:
message.localNetworkID = reader.readString();
break;
case 3:
message.remoteNetworkID = reader.readString();
break;
case 4:
message.recipient = reader.readString();
break;
case 5:
message.claimStatus = reader.readBool();
break;
case 6:
message.expiryTimeSecs = reader.readUint64();
break;
case 7:
message.expirationStatus = reader.readBool();
break;
default: reader.skipField();
}
}
return message;
}
serializeBinary(): Uint8Array {
return this.serialize();
}
static deserializeBinary(bytes: Uint8Array): AssetClaimStatus {
return AssetClaimStatus.deserialize(bytes);
}
}
} | the_stack |
import { TypeRegistry } from '@kiltprotocol/chain-helpers'
import {
IDidKeyDetails,
IDidResolutionDocumentMetadata,
IDidServiceEndpoint,
IIdentity,
KeyringPair,
} from '@kiltprotocol/types'
import type { IDidResolvedDetails } from '@kiltprotocol/types'
import { Keyring } from '@kiltprotocol/utils'
import { hexToU8a, u8aToHex } from '@polkadot/util'
import { LightDidDetails } from '../DidDetails'
import type { INewPublicKey } from '../types'
import { IDidChainRecordJSON } from '../types'
import { DefaultResolver } from './DefaultResolver'
import {
getIdentifierFromKiltDid,
getKiltDidFromIdentifier,
parseDidUrl,
} from '../Did.utils'
const fullDidPresentWithAuthenticationKey =
'did:kilt:4r1WkS3t8rbCb11H8t3tJvGVCynwDXSUBiuGB6sLRHzCLCjs'
const fullDidPresentWithAllKeys =
'did:kilt:4sDxAgw86PFvC6TQbvZzo19WoYF6T4HcLd2i9wzvojkLXLvp'
const fullDidPresentWithServiceEndpoints =
'did:kilt:4q4DHavMdesaSMH3g32xH3fhxYPt5pmoP9oSwgTr73dQLrkN'
const deletedDid = 'did:kilt:4rrVTLAXgeoE8jo8si571HnqHtd5WmvLuzfH6e1xBsVXsRo7'
const migratedUndeletedLightDid = `did:kilt:light:00${getIdentifierFromKiltDid(
fullDidPresentWithAuthenticationKey
)}`
const migratedDeletedLightDid = `did:kilt:light:00${getIdentifierFromKiltDid(
deletedDid
)}`
function generateAuthenticationKeyDetails(
didIdentifier: IIdentity['address']
): [string, IDidKeyDetails] {
const didUri = getKiltDidFromIdentifier(didIdentifier, 'full')
return [
`${didUri}#auth`,
{
id: `${didUri}#auth`,
type: 'ed25519',
controller: didUri,
publicKeyHex:
'0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
includedAt: 200,
},
]
}
function generateEncryptionKeyDetails(
didIdentifier: IIdentity['address']
): [string, IDidKeyDetails] {
const didUri = getKiltDidFromIdentifier(didIdentifier, 'full')
return [
`${didUri}#enc`,
{
id: `${didUri}#enc`,
type: 'x25519',
controller: didUri,
publicKeyHex:
'0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
includedAt: 250,
},
]
}
function generateAttestationKeyDetails(
didIdentifier: IIdentity['address']
): [string, IDidKeyDetails] {
const didUri = getKiltDidFromIdentifier(didIdentifier, 'full')
return [
`${didUri}#att`,
{
id: `${didUri}#att`,
type: 'sr25519',
controller: didUri,
publicKeyHex:
'0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc',
includedAt: 300,
},
]
}
function generateDelegationKeyDetails(
didIdentifier: IIdentity['address']
): [string, IDidKeyDetails] {
const didUri = getKiltDidFromIdentifier(didIdentifier, 'full')
return [
`${didUri}#del`,
{
id: `${didUri}#del`,
type: 'ed25519',
controller: didUri,
publicKeyHex:
'0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd',
includedAt: 350,
},
]
}
function generateServiceEndpointDetails(
didIdentifier: IIdentity['address'],
serviceId: string
): IDidServiceEndpoint {
const didUri = getKiltDidFromIdentifier(didIdentifier, 'full')
return {
id: `${didUri}#${serviceId}`,
types: [`type-${serviceId}`],
urls: [`urls-${serviceId}`],
}
}
jest.mock('../Did.chain', () => {
const queryByDID = jest.fn(
async (did: string): Promise<IDidChainRecordJSON | null> => {
const [authKeyId, authKey] = generateAuthenticationKeyDetails(did)
const [encKeyId, encKey] = generateEncryptionKeyDetails(did)
const [attKeyId, attKey] = generateAttestationKeyDetails(did)
const [delKeyId, delKey] = generateDelegationKeyDetails(did)
switch (did) {
case fullDidPresentWithAuthenticationKey:
return {
did,
authenticationKey: authKeyId,
keyAgreementKeys: [],
publicKeys: [authKey],
lastTxCounter: TypeRegistry.createType('u64'),
}
case fullDidPresentWithAllKeys:
return {
did,
authenticationKey: authKeyId,
keyAgreementKeys: [encKeyId],
assertionMethodKey: attKeyId,
capabilityDelegationKey: delKeyId,
publicKeys: [authKey, encKey, attKey, delKey],
lastTxCounter: TypeRegistry.createType('u64'),
}
case fullDidPresentWithServiceEndpoints:
return {
did,
authenticationKey: authKeyId,
keyAgreementKeys: [],
publicKeys: [authKey],
lastTxCounter: TypeRegistry.createType('u64'),
}
default:
return null
}
}
)
const queryDidKey = jest.fn(
async (didUri: string): Promise<IDidKeyDetails | null> => {
const { identifier } = parseDidUrl(didUri)
const subjectDid = getKiltDidFromIdentifier(identifier, 'full')
const details = await queryByDID(subjectDid)
return details?.publicKeys.find((key) => key.id === didUri) || null
}
)
const queryServiceEndpoint = jest.fn(
async (didUri: string): Promise<IDidServiceEndpoint | null> => {
const { identifier, fragment } = parseDidUrl(didUri)
const subjectDid = getKiltDidFromIdentifier(identifier, 'full')
switch (subjectDid) {
case fullDidPresentWithServiceEndpoints:
return generateServiceEndpointDetails(identifier, fragment as string)
default:
return null
}
}
)
const queryServiceEndpoints = jest.fn(
async (didUri: string): Promise<IDidServiceEndpoint[]> => {
switch (didUri) {
case fullDidPresentWithServiceEndpoints:
return [
(await queryServiceEndpoint(
`${didUri}#id-1`
)) as IDidServiceEndpoint,
(await queryServiceEndpoint(
`${didUri}#id-2`
)) as IDidServiceEndpoint,
]
default:
return []
}
}
)
const queryDidDeletionStatus = jest.fn(
async (did: string): Promise<boolean> => {
switch (did) {
case deletedDid:
return true
default:
return false
}
}
)
return {
queryByDID,
queryById: jest.fn(
async (id: string): Promise<IDidChainRecordJSON | null> =>
queryByDID(getKiltDidFromIdentifier(id, 'full'))
),
queryDidKey,
queryServiceEndpoint,
queryServiceEndpoints,
queryDidDeletionStatus,
}
})
describe('Key resolution', () => {
it('Correctly resolves a key given its ID', async () => {
const key = (await DefaultResolver.resolveKey(
`${fullDidPresentWithAllKeys}#auth`
)) as IDidKeyDetails
expect(key).toMatchObject<Partial<IDidKeyDetails>>({
id: `${fullDidPresentWithAllKeys}#auth`,
type: 'ed25519',
controller: fullDidPresentWithAllKeys,
})
})
})
describe('Service endpoint resolution', () => {
it('Correctly resolves a service endpoint given its ID', async () => {
const serviceEndpoint = (await DefaultResolver.resolveServiceEndpoint(
`${fullDidPresentWithServiceEndpoints}#id-1`
)) as IDidServiceEndpoint
expect(serviceEndpoint).toMatchObject<IDidServiceEndpoint>({
id: `${fullDidPresentWithServiceEndpoints}#id-1`,
types: ['type-id-1'],
urls: ['urls-id-1'],
})
})
})
describe('Full DID resolution', () => {
it('Correctly resolves full DID details with authentication key', async () => {
const { details, metadata } = (await DefaultResolver.resolve(
fullDidPresentWithAuthenticationKey
)) as IDidResolvedDetails
expect(metadata).toStrictEqual<IDidResolutionDocumentMetadata>({
deactivated: false,
})
expect(details?.did).toStrictEqual(fullDidPresentWithAuthenticationKey)
expect(details?.getKeys()).toStrictEqual([
{
id: `${fullDidPresentWithAuthenticationKey}#auth`,
type: 'ed25519',
controller: fullDidPresentWithAuthenticationKey,
publicKeyHex:
'0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
includedAt: 200,
},
])
})
it('Correctly resolves full DID details with all keys', async () => {
const { details, metadata } = (await DefaultResolver.resolve(
fullDidPresentWithAllKeys
)) as IDidResolvedDetails
expect(metadata).toStrictEqual<IDidResolutionDocumentMetadata>({
deactivated: false,
})
expect(details?.did).toStrictEqual(fullDidPresentWithAllKeys)
expect(details?.getKeys()).toStrictEqual([
{
id: `${fullDidPresentWithAllKeys}#auth`,
type: 'ed25519',
controller: fullDidPresentWithAllKeys,
publicKeyHex:
'0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
includedAt: 200,
},
{
id: `${fullDidPresentWithAllKeys}#enc`,
type: 'x25519',
controller: fullDidPresentWithAllKeys,
publicKeyHex:
'0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
includedAt: 250,
},
{
id: `${fullDidPresentWithAllKeys}#att`,
type: 'sr25519',
controller: fullDidPresentWithAllKeys,
publicKeyHex:
'0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc',
includedAt: 300,
},
{
id: `${fullDidPresentWithAllKeys}#del`,
type: 'ed25519',
controller: fullDidPresentWithAllKeys,
publicKeyHex:
'0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd',
includedAt: 350,
},
])
})
it('Correctly resolves full DID details with service endpoints', async () => {
const { details, metadata } = (await DefaultResolver.resolve(
fullDidPresentWithServiceEndpoints
)) as IDidResolvedDetails
expect(metadata).toStrictEqual<IDidResolutionDocumentMetadata>({
deactivated: false,
})
expect(details?.did).toStrictEqual(fullDidPresentWithServiceEndpoints)
expect(details?.getKeys()).toStrictEqual([
{
id: `${fullDidPresentWithServiceEndpoints}#auth`,
type: 'ed25519',
controller: fullDidPresentWithServiceEndpoints,
publicKeyHex:
'0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
includedAt: 200,
},
])
expect(details?.getEndpoints()).toStrictEqual([
{
id: `${fullDidPresentWithServiceEndpoints}#id-1`,
types: ['type-id-1'],
urls: ['urls-id-1'],
},
{
id: `${fullDidPresentWithServiceEndpoints}#id-2`,
types: ['type-id-2'],
urls: ['urls-id-2'],
},
])
})
it('Correctly resolves a full DID that does not exist', async () => {
const { details, metadata } = (await DefaultResolver.resolve(
deletedDid
)) as IDidResolvedDetails
expect(details).toBeUndefined()
expect(metadata).toStrictEqual<IDidResolutionDocumentMetadata>({
deactivated: true,
})
})
it('Correctly resolves a full DID given a key ID', async () => {
const { details, metadata } = (await DefaultResolver.resolveDoc(
`${fullDidPresentWithAuthenticationKey}#auth`
)) as IDidResolvedDetails
expect(metadata).toStrictEqual<IDidResolutionDocumentMetadata>({
deactivated: false,
})
expect(details?.did).toStrictEqual(fullDidPresentWithAuthenticationKey)
expect(details?.getKeys()).toStrictEqual([
{
id: `${fullDidPresentWithAuthenticationKey}#auth`,
type: 'ed25519',
controller: fullDidPresentWithAuthenticationKey,
publicKeyHex:
'0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
includedAt: 200,
},
])
})
it('Correctly resolves a full DID given a service ID', async () => {
const { details, metadata } = (await DefaultResolver.resolveDoc(
`${fullDidPresentWithServiceEndpoints}#id-1`
)) as IDidResolvedDetails
expect(metadata).toStrictEqual<IDidResolutionDocumentMetadata>({
deactivated: false,
})
expect(details?.did).toStrictEqual(fullDidPresentWithServiceEndpoints)
expect(details?.getKeys()).toStrictEqual([
{
id: `${fullDidPresentWithServiceEndpoints}#auth`,
type: 'ed25519',
controller: fullDidPresentWithServiceEndpoints,
publicKeyHex:
'0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
includedAt: 200,
},
])
expect(details?.getEndpoints()).toStrictEqual([
{
id: `${fullDidPresentWithServiceEndpoints}#id-1`,
types: ['type-id-1'],
urls: ['urls-id-1'],
},
{
id: `${fullDidPresentWithServiceEndpoints}#id-2`,
types: ['type-id-2'],
urls: ['urls-id-2'],
},
])
})
})
describe('Light DID resolution', () => {
const mnemonic = 'testMnemonic'
const keyring: Keyring = new Keyring({ ss58Format: 38 })
let keypair: KeyringPair
let publicAuthKey: INewPublicKey
let encryptionKey: INewPublicKey
let serviceEndpoints: IDidServiceEndpoint[]
it('Correctly resolves a light DID created with only an ed25519 authentication key', async () => {
keypair = keyring.addFromMnemonic(mnemonic, undefined, 'ed25519')
publicAuthKey = {
publicKey: keypair.publicKey,
type: 'ed25519',
}
const lightDID = new LightDidDetails({
authenticationKey: publicAuthKey,
})
const { details, metadata } = (await DefaultResolver.resolve(
lightDID.did
)) as IDidResolvedDetails
expect(details?.getKey(`${lightDID.did}#authentication`)).toMatchObject<
Partial<IDidKeyDetails>
>({
id: `${lightDID.did}#authentication`,
controller: lightDID.did,
publicKeyHex: u8aToHex(publicAuthKey.publicKey),
})
expect(metadata).toStrictEqual<IDidResolutionDocumentMetadata>({
deactivated: false,
})
})
it('Correctly resolves a light DID created with only an sr25519 authentication key', async () => {
keypair = keyring.addFromMnemonic(mnemonic, undefined, 'sr25519')
publicAuthKey = {
publicKey: keypair.publicKey,
type: 'sr25519',
}
const lightDID = new LightDidDetails({
authenticationKey: publicAuthKey,
})
const { details, metadata } = (await DefaultResolver.resolve(
lightDID.did
)) as IDidResolvedDetails
expect(details?.getKey(`${lightDID.did}#authentication`)).toMatchObject<
Partial<IDidKeyDetails>
>({
id: `${lightDID.did}#authentication`,
controller: lightDID.did,
publicKeyHex: u8aToHex(publicAuthKey.publicKey),
})
expect(metadata).toStrictEqual<IDidResolutionDocumentMetadata>({
deactivated: false,
})
})
it('Correctly resolves a light DID created with an authentication, an encryption key, and three service endpoints', async () => {
keypair = keyring.addFromMnemonic(mnemonic, undefined, 'ed25519')
publicAuthKey = {
publicKey: keypair.publicKey,
type: 'sr25519',
}
encryptionKey = {
publicKey: hexToU8a(
'0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
),
type: 'x25519',
}
serviceEndpoints = [
{
id: 'id-1',
types: ['type-1'],
urls: ['url-1'],
},
{
id: 'id-2',
types: ['type-2'],
urls: ['url-2'],
},
{
id: 'id-3',
types: ['type-3'],
urls: ['url-3'],
},
]
const lightDID = new LightDidDetails({
authenticationKey: publicAuthKey,
encryptionKey,
serviceEndpoints,
})
const { details, metadata } = (await DefaultResolver.resolve(
lightDID.did
)) as IDidResolvedDetails
expect(details?.getKey(`${lightDID.did}#authentication`)).toMatchObject<
Partial<IDidKeyDetails>
>({
id: `${lightDID.did}#authentication`,
controller: lightDID.did,
publicKeyHex: u8aToHex(publicAuthKey.publicKey),
})
expect(details?.getKey(`${lightDID.did}#encryption`)).toMatchObject<
Partial<IDidKeyDetails>
>({
id: `${lightDID.did}#encryption`,
controller: lightDID.did,
publicKeyHex: u8aToHex(encryptionKey.publicKey),
})
expect(details?.getEndpoints()).toStrictEqual<IDidServiceEndpoint[]>([
{
id: `${lightDID.did}#id-1`,
types: ['type-1'],
urls: ['url-1'],
},
{
id: `${lightDID.did}#id-2`,
types: ['type-2'],
urls: ['url-2'],
},
{
id: `${lightDID.did}#id-3`,
types: ['type-3'],
urls: ['url-3'],
},
])
expect(metadata).toStrictEqual<IDidResolutionDocumentMetadata>({
deactivated: false,
})
})
it('Correctly resolves a light DID using a key ID', async () => {
keypair = keyring.addFromMnemonic(mnemonic, undefined, 'sr25519')
publicAuthKey = {
publicKey: keypair.publicKey,
type: 'sr25519',
}
const lightDID = new LightDidDetails({
authenticationKey: publicAuthKey,
})
const { details, metadata } = (await DefaultResolver.resolveDoc(
`${lightDID.did}#auth`
)) as IDidResolvedDetails
expect(details?.getKey(`${lightDID.did}#authentication`)).toMatchObject<
Partial<IDidKeyDetails>
>({
id: `${lightDID.did}#authentication`,
controller: lightDID.did,
publicKeyHex: u8aToHex(publicAuthKey.publicKey),
})
expect(metadata).toStrictEqual<IDidResolutionDocumentMetadata>({
deactivated: false,
})
})
it('Correctly resolves a light DID using a service ID', async () => {
keypair = keyring.addFromMnemonic(mnemonic, undefined, 'ed25519')
publicAuthKey = {
publicKey: keypair.publicKey,
type: 'sr25519',
}
encryptionKey = {
publicKey: hexToU8a(
'0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
),
type: 'x25519',
}
serviceEndpoints = [
{
id: 'id-1',
types: ['type-1'],
urls: ['url-1'],
},
{
id: 'id-2',
types: ['type-2'],
urls: ['url-2'],
},
{
id: 'id-3',
types: ['type-3'],
urls: ['url-3'],
},
]
const lightDID = new LightDidDetails({
authenticationKey: publicAuthKey,
encryptionKey,
serviceEndpoints,
})
const { details, metadata } = (await DefaultResolver.resolveDoc(
`${lightDID.did}#id-1`
)) as IDidResolvedDetails
expect(details?.getKey(`${lightDID.did}#authentication`)).toMatchObject<
Partial<IDidKeyDetails>
>({
id: `${lightDID.did}#authentication`,
controller: lightDID.did,
publicKeyHex: u8aToHex(publicAuthKey.publicKey),
})
expect(details?.getKey(`${lightDID.did}#encryption`)).toMatchObject<
Partial<IDidKeyDetails>
>({
id: `${lightDID.did}#encryption`,
controller: lightDID.did,
publicKeyHex: u8aToHex(encryptionKey.publicKey),
})
expect(details?.getEndpoints()).toStrictEqual<IDidServiceEndpoint[]>([
{
id: `${lightDID.did}#id-1`,
types: ['type-1'],
urls: ['url-1'],
},
{
id: `${lightDID.did}#id-2`,
types: ['type-2'],
urls: ['url-2'],
},
{
id: `${lightDID.did}#id-3`,
types: ['type-3'],
urls: ['url-3'],
},
])
expect(metadata).toStrictEqual<IDidResolutionDocumentMetadata>({
deactivated: false,
})
})
})
describe('Migrated DID resolution', () => {
it('Correctly resolves a migrated light DID that has not been deleted', async () => {
const { details, metadata } = (await DefaultResolver.resolve(
migratedUndeletedLightDid
)) as IDidResolvedDetails
expect(details).toBeDefined()
expect(metadata).toStrictEqual<IDidResolutionDocumentMetadata>({
deactivated: false,
canonicalId: fullDidPresentWithAuthenticationKey,
})
})
it('Correctly resolves a migrated light DID that has been deleted', async () => {
const { details, metadata } = (await DefaultResolver.resolve(
migratedDeletedLightDid
)) as IDidResolvedDetails
expect(details).toBeUndefined()
expect(metadata).toStrictEqual<IDidResolutionDocumentMetadata>({
deactivated: true,
})
})
}) | the_stack |
module android.widget {
import Spannable = android.text.Spannable;
import TextUtils = android.text.TextUtils;
import TextView = android.widget.TextView;
import View = android.view.View;
import Gravity = android.view.Gravity;
import Context = android.content.Context;
import Color = android.graphics.Color;
import Canvas = android.graphics.Canvas;
import Integer = java.lang.Integer;
import InputType = android.text.InputType;
import PasswordTransformationMethod = android.text.method.PasswordTransformationMethod;
import Platform = androidui.util.Platform;
import AttrBinder = androidui.attr.AttrBinder;
/**
* EditText is a thin veneer over TextView that configures itself
* to be editable.
*
* <p>See the <a href="{@docRoot}guide/topics/ui/controls/text.html">Text Fields</a>
* guide.</p>
* <p>
* <b>XML attributes</b>
* <p>
* See {@link android.R.styleable#EditText EditText Attributes},
* {@link android.R.styleable#TextView TextView Attributes},
* {@link android.R.styleable#View View Attributes}
*/
export class EditText extends TextView {
private inputElement:HTMLTextAreaElement|HTMLInputElement;
private mSingleLineInputElement:HTMLInputElement;
private mMultiLineInputElement:HTMLTextAreaElement;
private mInputType = InputType.TYPE_NULL;
private mForceDisableDraw = false;
private mMaxLength = Integer.MAX_VALUE;
constructor(context:Context, bindElement?:HTMLElement, defStyle:any=android.R.attr.editTextStyle) {
super(context, bindElement, defStyle);
const a = context.obtainStyledAttributes(bindElement, defStyle);
const inputTypeS = a.getAttrValue("inputType");
if (inputTypeS) {
this._setInputType(inputTypeS);
}
this.mMaxLength = a.getInteger('maxLength', this.mMaxLength);
}
protected createClassAttrBinder(): androidui.attr.AttrBinder.ClassBinderMap {
return super.createClassAttrBinder().set('inputType', {
setter(v:EditText, value:any, attrBinder:AttrBinder) {
if (Number.isInteger(Number.parseInt(value))) {
v.setInputType(Number.parseInt(value));
} else {
v._setInputType(value + '');
}
}, getter(v:EditText) {
return v.getInputType();
}
}).set('maxLength', {
setter(v:EditText, value:any, attrBinder:AttrBinder) {
v.mMaxLength = attrBinder.parseInt(value, v.mMaxLength);
}, getter(v:EditText) {
return v.mMaxLength;
}
});
}
protected initBindElement(bindElement:HTMLElement):void {
super.initBindElement(bindElement);
this.switchToMultiLineInputElement();//default
}
protected onInputValueChange(e){
let text = this.inputElement.value;//innerText;
let filterText = '';
for(let i = 0, length = text.length; i<length; i++){
let c = text.codePointAt(i);
if(!this.filterKeyCodeByInputType(c) && filterText.length < this.mMaxLength){
filterText += text[i];
}
}
if(text != filterText){
text = filterText;
this.inputElement.value = text;
}
if (!text || text.length === 0) {
this.setForceDisableDrawText(false);
} else {
this.setForceDisableDrawText(true);
}
this.setText(text);
}
private onDomTextInput(e) {
let text = e['data'];
for(let i = 0, length = text.length; i<length; i++){
let c = text.codePointAt(i);
if(!this.filterKeyCodeOnInput(c)){
return;
}
}
// prevent
e.preventDefault();
e.stopPropagation();
}
private switchToInputElement(inputElement: HTMLInputElement|HTMLTextAreaElement) {
if(this.inputElement === inputElement) return;
inputElement.onblur = ()=>{
inputElement.style.opacity = '0';
this.setForceDisableDrawText(false);
this.onInputElementFocusChanged(false);
};
inputElement.onfocus = ()=>{
inputElement.style.opacity = '1';
if(this.getText().length>0){
this.setForceDisableDrawText(true);
}
this.onInputElementFocusChanged(true);
};
inputElement.oninput = (e) => this.onInputValueChange(e);
inputElement.removeEventListener('textInput', (e) => this.onDomTextInput(e));
inputElement.addEventListener('textInput', (e) => this.onDomTextInput(e));
if(this.inputElement && this.inputElement.parentElement){
this.bindElement.removeChild(this.inputElement);
this.bindElement.appendChild(inputElement);
}
this.inputElement = inputElement;
}
private switchToSingleLineInputElement(){
if(!this.mSingleLineInputElement){
this.mSingleLineInputElement = document.createElement('input');
this.mSingleLineInputElement.style.position = 'absolute';
this.mSingleLineInputElement.style['webkitAppearance'] = 'none';
this.mSingleLineInputElement.style.borderRadius = '0';
this.mSingleLineInputElement.style.overflow = 'auto';
this.mSingleLineInputElement.style.background = 'transparent';
this.mSingleLineInputElement.style.fontFamily = Canvas.getMeasureTextFontFamily();
}
this.switchToInputElement(this.mSingleLineInputElement);
}
protected switchToMultiLineInputElement(){
if(!this.mMultiLineInputElement) {
this.mMultiLineInputElement = document.createElement('textarea');
this.mMultiLineInputElement.style.position = 'absolute';
this.mMultiLineInputElement.style['webkitAppearance'] = 'none';
this.mMultiLineInputElement.style['resize'] = 'none';
this.mMultiLineInputElement.style.borderRadius = '0';
this.mMultiLineInputElement.style.overflow = 'auto';
this.mMultiLineInputElement.style.background = 'transparent';
this.mMultiLineInputElement.style.boxSizing = 'border-box';
this.mMultiLineInputElement.style.fontFamily = Canvas.getMeasureTextFontFamily();
}
this.switchToInputElement(this.mMultiLineInputElement);
}
protected tryShowInputElement(){
if(!this.isInputElementShowed()){
this.inputElement.value = this.getText().toString();
this.bindElement.appendChild(this.inputElement);
this.inputElement.focus();
if(this.getText().length>0){
this.setForceDisableDrawText(true);
}
this.syncTextBoundInfoToInputElement();
//TODO make cursor position friendly : move to first / move to touch position
}
}
protected tryDismissInputElement(){
try {
if (this.inputElement.parentNode) this.bindElement.removeChild(this.inputElement);
} catch (e) {
}
this.setForceDisableDrawText(false);
}
protected onInputElementFocusChanged(focused:boolean) {
}
isInputElementShowed():boolean {
return this.inputElement.parentElement != null && this.inputElement.style.opacity != '0';
}
performClick(event:android.view.MotionEvent):boolean {
this.tryShowInputElement();
return super.performClick(event);
}
protected onFocusChanged(focused:boolean, direction:number, previouslyFocusedRect:android.graphics.Rect):void {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
if(focused){
this.tryShowInputElement();
}else{
this.tryDismissInputElement();
}
}
protected setForceDisableDrawText(disable:boolean){
if(this.mForceDisableDraw == disable) return;
this.mForceDisableDraw = disable;
if(disable){
this.mSkipDrawText = true;
}else{
this.mSkipDrawText = false;
}
this.invalidate();
}
protected updateTextColors():void {
super.updateTextColors();
if(this.isInputElementShowed()){
this.syncTextBoundInfoToInputElement();
}
}
onTouchEvent(event:android.view.MotionEvent):boolean {
const superResult:boolean = super.onTouchEvent(event);
if(this.isInputElementShowed()){
event[android.view.ViewRootImpl.ContinueEventToDom] = true;
// touch scroll in dom
//TODO check touch direction
if(this.inputElement.scrollHeight>this.inputElement.offsetHeight || this.inputElement.scrollWidth>this.inputElement.offsetWidth){
this.getParent().requestDisallowInterceptTouchEvent(true);
}
return true;
}
return superResult;
}
private filterKeyEvent(event:android.view.KeyEvent):boolean {
let keyCode = event.getKeyCode();
if(keyCode == android.view.KeyEvent.KEYCODE_Backspace || keyCode == android.view.KeyEvent.KEYCODE_Del
|| event.isCtrlPressed() || event.isAltPressed() || event.isMetaPressed()){
return false;
}
if(keyCode == android.view.KeyEvent.KEYCODE_ENTER && this.isSingleLine()){
return true;
}
if(event.mIsTypingKey) {
if(this.getText().length >= this.mMaxLength) {
return true;
}
return this.filterKeyCodeOnInput(keyCode);
}
return false;
}
protected filterKeyCodeByInputType(keyCode:number):boolean {
let filter = false;
const inputType = this.mInputType;
const typeClass = inputType & InputType.TYPE_MASK_CLASS;
if (typeClass === InputType.TYPE_CLASS_NUMBER) {
filter = InputType.LimitCode.TYPE_CLASS_NUMBER.indexOf(keyCode) === -1;
if ((inputType & InputType.TYPE_NUMBER_FLAG_SIGNED) === InputType.TYPE_NUMBER_FLAG_SIGNED) {
filter = filter && keyCode !== android.view.KeyEvent.KEYCODE_Minus;
}
if ((inputType & InputType.TYPE_NUMBER_FLAG_DECIMAL) === InputType.TYPE_NUMBER_FLAG_DECIMAL) {
filter = filter && keyCode !== android.view.KeyEvent.KEYCODE_Period;
}
} else if (typeClass === InputType.TYPE_CLASS_PHONE) {
filter = InputType.LimitCode.TYPE_CLASS_PHONE.indexOf(keyCode) === -1;
}
return filter;
}
protected filterKeyCodeOnInput(keyCode:number):boolean {
let filter = false;
const inputType = this.mInputType;
const typeClass = inputType & InputType.TYPE_MASK_CLASS;
if (typeClass === InputType.TYPE_CLASS_NUMBER) {
if ((inputType & InputType.TYPE_NUMBER_FLAG_SIGNED) === InputType.TYPE_NUMBER_FLAG_SIGNED) {
if(keyCode === android.view.KeyEvent.KEYCODE_Minus && this.getText().length > 0) {
filter = true;
}
}
if ((inputType & InputType.TYPE_NUMBER_FLAG_DECIMAL) === InputType.TYPE_NUMBER_FLAG_DECIMAL) {
if (keyCode === android.view.KeyEvent.KEYCODE_Period && (this.getText().includes('.') || this.getText().length === 0)) {
filter = true;
}
}
}
return filter || this.filterKeyCodeByInputType(keyCode);
}
private checkFilterKeyEventToDom(event:android.view.KeyEvent):boolean {
if(this.isInputElementShowed()){
if(this.filterKeyEvent(event)){
event[android.view.ViewRootImpl.ContinueEventToDom] = false;
}else{
event[android.view.ViewRootImpl.ContinueEventToDom] = true;
}
return true;
}
return false;
}
onKeyDown(keyCode:number, event:android.view.KeyEvent):boolean {
const filter = this.checkFilterKeyEventToDom(event);
return super.onKeyDown(keyCode, event) || filter;
}
onKeyUp(keyCode:number, event:android.view.KeyEvent):boolean {
const filter = this.checkFilterKeyEventToDom(event);
return super.onKeyUp(keyCode, event) || filter;
}
requestSyncBoundToElement(immediately = false):void {
if(this.isInputElementShowed()){
immediately = true;
}
super.requestSyncBoundToElement(immediately);
}
protected setRawTextSize(size:number):void {
super.setRawTextSize(size);
if(this.isInputElementShowed()){
this.syncTextBoundInfoToInputElement();
}
}
protected onTextChanged(text:String, start:number, lengthBefore:number, lengthAfter:number):void {
if(this.isInputElementShowed()){
this.syncTextBoundInfoToInputElement();
}
}
protected onLayout(changed:boolean, left:number, top:number, right:number, bottom:number):void {
super.onLayout(changed, left, top, right, bottom);
if(this.isInputElementShowed()){
this.syncTextBoundInfoToInputElement();
}
}
setGravity(gravity:number):void {
super.setGravity(gravity);
if(this.isInputElementShowed()){
this.syncTextBoundInfoToInputElement();
}
}
setSingleLine(singleLine = true):void {
if (singleLine) {
this.switchToSingleLineInputElement();
} else {
this.switchToMultiLineInputElement();
}
super.setSingleLine(singleLine);
}
_setInputType(value:string):void {
switch (value + ''){
case 'none':
this.setInputType(InputType.TYPE_NULL);
break;
case 'text':
this.setInputType(InputType.TYPE_CLASS_TEXT);
break;
case 'textUri':
this.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI);
break;
case 'textEmailAddress':
this.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
break;
case 'textPassword':
this.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
break;
case 'textVisiblePassword':
this.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
break;
case 'number':
this.setInputType(InputType.TYPE_CLASS_NUMBER);
break;
case 'numberSigned':
this.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_SIGNED);
break;
case 'numberDecimal':
this.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
break;
case 'numberPassword':
this.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
break;
case 'phone':
this.setInputType(InputType.TYPE_CLASS_PHONE);
break;
case 'datetime':
this.setInputType(InputType.TYPE_CLASS_DATETIME);
break;
case 'date':
this.setInputType(InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_DATE);
break;
case 'time':
this.setInputType(InputType.TYPE_CLASS_DATETIME | InputType.TYPE_DATETIME_VARIATION_TIME);
break;
}
}
/**
* Set the type of the content with a constant as defined for {@link EditorInfo#inputType}. This
* will take care of changing the key listener, by calling {@link #setKeyListener(KeyListener)},
* to match the given content type. If the given content type is {@link EditorInfo#TYPE_NULL}
* then a soft keyboard will not be displayed for this text view.
*
* Note that the maximum number of displayed lines (see {@link #setMaxLines(int)}) will be
* modified if you change the {@link EditorInfo#TYPE_TEXT_FLAG_MULTI_LINE} flag of the input
* type.
*
* @see #getInputType()
* @see #setRawInputType(int)
* @see android.text.InputType
* @attr ref android.R.styleable#TextView_inputType
*/
setInputType(type:number):void {
this.mInputType = type;
const typeClass = type & InputType.TYPE_MASK_CLASS;
this.inputElement.style['webkitTextSecurity'] = '';
this.setTransformationMethod(null);
switch (typeClass){
case InputType.TYPE_NULL:
this.setSingleLine(false);
this.inputElement.removeAttribute('type');
break;
case InputType.TYPE_CLASS_TEXT:
if ((type & InputType.TYPE_TEXT_VARIATION_URI) === InputType.TYPE_TEXT_VARIATION_URI) {
this.setSingleLine(true);
this.inputElement.setAttribute('type', 'url');
} else if ((type & InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS) === InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS) {
this.setSingleLine(true);
this.inputElement.setAttribute('type', 'email');
} else if ((type & InputType.TYPE_TEXT_VARIATION_PASSWORD) === InputType.TYPE_TEXT_VARIATION_PASSWORD) {
this.setSingleLine(true);
this.inputElement.setAttribute('type', 'password');
this.setTransformationMethod(PasswordTransformationMethod.getInstance());
} else if ((type & InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) === InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {
this.setSingleLine(true);
this.inputElement.setAttribute('type', 'email');//use email type as visible password
} else {
this.setSingleLine(false);
this.inputElement.removeAttribute('type');
}
break;
case InputType.TYPE_CLASS_NUMBER:
this.setSingleLine(true);
this.inputElement.setAttribute('type', 'number');
if ((type & InputType.TYPE_NUMBER_VARIATION_PASSWORD) === InputType.TYPE_NUMBER_VARIATION_PASSWORD) {
this.inputElement.style['webkitTextSecurity'] = 'disc';
this.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
break;
case InputType.TYPE_CLASS_PHONE:
this.setSingleLine(true);
this.inputElement.setAttribute('type', 'tel');
break;
case InputType.TYPE_CLASS_DATETIME:
this.setSingleLine(true);
if ((type & InputType.TYPE_DATETIME_VARIATION_DATE) === InputType.TYPE_DATETIME_VARIATION_DATE) {
this.inputElement.setAttribute('type', 'date');
} else if ((type & InputType.TYPE_DATETIME_VARIATION_TIME) === InputType.TYPE_DATETIME_VARIATION_TIME) {
this.inputElement.setAttribute('type', 'time');
} else {
this.inputElement.setAttribute('type', 'datetime');
}
break;
}
}
/**
* Get the type of the editable content.
*
* @see #setInputType(int)
* @see android.text.InputType
*/
getInputType():number {
return this.mInputType;
}
private syncTextBoundInfoToInputElement(){
let left = this.getLeft();
let top = this.getTop();
let right = this.getRight();
let bottom = this.getBottom();
const density = this.getResources().getDisplayMetrics().density;
let maxHeight = this.getMaxHeight();
if(maxHeight<=0 || maxHeight>=Integer.MAX_VALUE){
let maxLine = this.getMaxLines();
if(maxLine>0 && maxLine<Integer.MAX_VALUE){
maxHeight = maxLine * this.getLineHeight();
}
}
let textHeight = bottom - top - this.getCompoundPaddingTop() - this.getCompoundPaddingBottom();
if(maxHeight<=0 || maxHeight>textHeight){
maxHeight = textHeight;
}
let layout:android.text.Layout = this.mLayout;
if (this.mHint != null && this.mText.length == 0) {
layout = this.mHintLayout;
}
let height = layout ? Math.min(layout.getLineTop(layout.getLineCount()), maxHeight) : maxHeight;
this.inputElement.style.height = height / density + 1 + 'px';
this.inputElement.style.top = '';
this.inputElement.style.bottom = '';
this.inputElement.style.transform = this.inputElement.style.webkitTransform = '';
let gravity = this.getGravity();
switch (gravity & Gravity.VERTICAL_GRAVITY_MASK) {
case Gravity.TOP:
this.inputElement.style.top = this.getCompoundPaddingTop() / density + 'px';
break;
case Gravity.BOTTOM:
this.inputElement.style.bottom = this.getCompoundPaddingBottom() / density + 'px';
break;
default:
this.inputElement.style.top = '50%';
this.inputElement.style.transform = this.inputElement.style.webkitTransform = 'translate(0, -50%)';
break;
}
switch (gravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.LEFT:
this.inputElement.style.textAlign = 'left';
break;
case Gravity.RIGHT:
this.inputElement.style.textAlign = 'right';
break;
default:
this.inputElement.style.textAlign = 'center';
break;
}
const isIOS = Platform.isIOS;
this.inputElement.style.left = this.getCompoundPaddingLeft() / density - (isIOS?3:0) + 'px';
//this.inputElement.style.right = this.getCompoundPaddingRight() / density + 'px';
this.inputElement.style.width = (right - left - this.getCompoundPaddingRight() - this.getCompoundPaddingLeft()) / density + (isIOS?6:1) + 'px';
this.inputElement.style.lineHeight = this.getLineHeight()/density + 'px';
if(this.getLineCount() == 1){
this.inputElement.style.whiteSpace = 'nowrap';
}else{
this.inputElement.style.whiteSpace = '';
}
let text = this.getText().toString();
if(text!=this.inputElement.value) this.inputElement.value = text;
this.inputElement.style.fontSize = this.getTextSize() / density + 'px';
this.inputElement.style.color = Color.toRGBAFunc(this.getCurrentTextColor());
if(this.inputElement == this.mMultiLineInputElement){
this.inputElement.style.padding = (this.getTextSize()/density/5).toFixed(1) + 'px 0px 0px 0px';//textarea baseline adjust
}else{
this.inputElement.style.padding = '0px';
}
}
protected dependOnDebugLayout():boolean {
return true;
}
//protected getDefaultEditable():boolean {
// return true;
//}
//
//protected getDefaultMovementMethod():MovementMethod {
// return ArrowKeyMovementMethod.getInstance();
//}
//
//getText():Editable {
// return <Editable> super.getText();
//}
//
//setText(text:CharSequence, type:BufferType):void {
// super.setText(text, BufferType.EDITABLE);
//}
//
///**
// * Convenience for {@link Selection#setSelection(Spannable, int, int)}.
// */
//setSelection(start:number, stop:number):void {
// Selection.setSelection(this.getText(), start, stop);
//}
//
///**
// * Convenience for {@link Selection#setSelection(Spannable, int)}.
// */
//setSelection(index:number):void {
// Selection.setSelection(this.getText(), index);
//}
//
///**
// * Convenience for {@link Selection#selectAll}.
// */
//selectAll():void {
// Selection.selectAll(this.getText());
//}
//
///**
// * Convenience for {@link Selection#extendSelection}.
// */
//extendSelection(index:number):void {
// Selection.extendSelection(this.getText(), index);
//}
setEllipsize(ellipsis:TextUtils.TruncateAt):void {
if (ellipsis == TextUtils.TruncateAt.MARQUEE) {
throw Error(`new IllegalArgumentException("EditText cannot use the ellipsize mode " + "TextUtils.TruncateAt.MARQUEE")`);
}
super.setEllipsize(ellipsis);
}
}
} | the_stack |
import Global, { globalInstance } from './global'
import type { ScoreNote } from '../../main/on-score'
// eslint-disable-next-line import/no-duplicates
import type Note from './note'
// eslint-disable-next-line import/no-duplicates
import type { ScoreNoteWithNoteInstance } from './note'
import TapNote from './tap-note'
import FlipNote from './flip-note'
import LongNote from './long-note'
import LongMoveNote from './long-move-note'
import { showSaveDialog } from '../ipc'
import getPath from '../../common/get-path'
import { MishiroAudio } from '../audio'
import { error } from '../log'
const { /* relative, */parse } = window.node.path
const fs = window.node.fs
const { ipcRenderer } = window.node.electron
interface Song<ScoreType> {
src: string
bpm: number
score: ScoreType[]
fullCombo: number
difficulty: string
}
interface Option {
speed: number
}
class ScoreViewer {
public static main (): void {
window.addEventListener('beforeunload', () => {
ipcRenderer.sendTo(ipcRenderer.sendSync('mainWindowId'), 'liveEnd', null, false)
})
const song = ipcRenderer.sendSync('getSong')
if (!song) return
// console.log(song)
const name = parse(song.src).name.substr(parse(song.src).name.indexOf('-') + 1)
document.getElementsByTagName('title')[0].innerHTML = name
const sv = ScoreViewer.init(song, document.body)
sv.start()
// if (process.env.NODE_ENV !== 'production') {
// (document.getElementById('debug') as HTMLButtonElement).addEventListener('click', () => {
// const base64str = sv.frontCanvas.toDataURL('image/png').substr(22)
// writeFile(getPath.scoreDir(name + '.png'), Buffer.from(base64str, 'base64'))
// // console.log(sv.frontCanvas.toDataURL('image/png').substr(22))
// }, false)
// }
}
private static _instance: ScoreViewer | null = null
public static init (song: Song<ScoreNote>, el: HTMLElement, options?: Option): ScoreViewer {
return new ScoreViewer(song, el, options)
}
public static calY (speed: number, sec: number, currentTime: number): number {
return ScoreViewer.TOP_TO_TARGET_POSITION - (~~(speed * 60 * (sec - currentTime)))
}
public static saveCalY (sv: ScoreViewer, sec: number): number {
return sv.saveCanvas.height - ((~~(globalInstance.saveSpeed * 60 * (sec)))) / globalInstance.scale
}
private static readonly CANVAS_WIDTH = 867
private static readonly CANVAS_HEIGHT = 720
public static X: number[] = [238 - 206, 414 - 206, 589 - 206, 764 - 206, 937 - 206]
private static readonly BOTTOM = 20
public static TOP_TO_TARGET_POSITION = ScoreViewer.CANVAS_HEIGHT - ScoreViewer.BOTTOM - 114 + 6
public frontCanvas: HTMLCanvasElement
public backCanvas: HTMLCanvasElement
public saveCanvas: HTMLCanvasElement
public frontCtx: CanvasRenderingContext2D
public backCtx: CanvasRenderingContext2D
public saveCtx: CanvasRenderingContext2D
public song: Song<ScoreNoteWithNoteInstance>
public audio: MishiroAudio
public pauseButton: HTMLButtonElement
public saveButton: HTMLButtonElement
public rangeInput: HTMLInputElement
public speedInput: HTMLInputElement
public progressTime: HTMLSpanElement
public options: Option = {
speed: 12 // * 60 px / s
}
private _isReady: boolean = false
private _isReadyToSave: boolean = false
private _isPaused: boolean = false
private _t: number
private _isClean = true
private _comboDom: HTMLDivElement
// private _preCalculation: { timeRange: number }
constructor (song: Song<ScoreNote>, el: HTMLElement, options?: Option) {
if (ScoreViewer._instance) return ScoreViewer._instance
if (options) this.options = Object.assign({}, this.options, options)
// this.audio = process.env.NODE_ENV === 'production' ? Global.createAudio(song.src) : Global.createAudio(relative(getPath('public'), song.src))
this.audio = new MishiroAudio()
this.audio.loop = false
this.song = song
// this._preCalculation = {
// timeRange: 24 * (60 / song.bpm)
// }
this._resolveNoteList()
this._resolveDOM(el)
// console.log(this.song.score)
ScoreViewer._instance = this
console.log('score hca: ' + song.src)
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.audio.playHca(song.src)
return ScoreViewer._instance
}
private _setNoteInstance (index: number, note: Note): void {
if (!this.song.score[index]._instance) this.song.score[index]._instance = note
}
private _resolveNoteList (): void {
for (let i = 0; i < this.song.score.length; i++) {
if (this.song.score[i]._instance) continue
const note = this.song.score[i]
switch (note.type) {
case 1:
if (note.status === 0) {
this._setNoteInstance(i, new TapNote(note, this._getSyncNote(i)))
} else {
let group = this._findSameGroup(i, note.groupId)
if (group.length) {
for (let x = 0; x < group.length - 1; x++) {
if (this.song.score[group[x]].finishPos === this.song.score[group[x + 1]].finishPos) {
group = group.slice(0, x + 1)
break
}
}
for (let j = group.length - 1; j > 0; j--) {
this._setNoteInstance(group[j], new FlipNote(this.song.score[group[j]], this.song.score[group[j - 1]], this._getSyncNote(group[j])))
}
this._setNoteInstance(group[0], new FlipNote(this.song.score[group[0]], note, this._getSyncNote(group[0])))
}
this._setNoteInstance(i, new FlipNote(note, undefined, this._getSyncNote(i)))
}
break
case 2: {
const endIndex = this._findLongNote(i, note.finishPos)
if (endIndex !== -1) {
const group = this._findSameGroup(endIndex, this.song.score[endIndex].groupId)
if (group.length) {
for (let j = group.length - 1; j > 0; j--) {
if (this.song.score[group[j]].type === 2 && this.song.score[group[j]].status === 0) {
this._setNoteInstance(group[j], new LongNote(this.song.score[group[j]], this.song.score[group[j - 1]], this._getSyncNote(group[j])))
} else {
this._setNoteInstance(group[j], new FlipNote(this.song.score[group[j]], this.song.score[group[j - 1]], this._getSyncNote(group[j])))
}
}
if (this.song.score[group[0]].type === 2 && this.song.score[group[0]].status === 0) {
this._setNoteInstance(group[0], new LongNote(this.song.score[group[0]], this.song.score[endIndex], this._getSyncNote(group[0])))
} else {
this._setNoteInstance(group[0], new FlipNote(this.song.score[group[0]], this.song.score[endIndex], this._getSyncNote(group[0])))
}
}
if (this.song.score[endIndex].type === 2 && this.song.score[endIndex].status === 0) {
this._setNoteInstance(endIndex, new LongNote(this.song.score[endIndex], note, this._getSyncNote(endIndex)))
} else {
this._setNoteInstance(endIndex, new FlipNote(this.song.score[endIndex], note, this._getSyncNote(endIndex)))
}
}
this._setNoteInstance(i, new LongNote(note, undefined, this._getSyncNote(i)))
break
}
case 3: {
const group = this._findSameGroup(i, note.groupId)
if (group.length) {
for (let j = group.length - 1; j > 0; j--) {
if (this.song.score[group[j]].type === 3 && this.song.score[group[j]].status === 0) {
this._setNoteInstance(group[j], new LongMoveNote(this.song.score[group[j]], this.song.score[group[j - 1]], this._getSyncNote(group[j])))
} else {
this._setNoteInstance(group[j], new FlipNote(this.song.score[group[j]], this.song.score[group[j - 1]], this._getSyncNote(group[j])))
}
}
if (this.song.score[group[0]].type === 3 && this.song.score[group[0]].status === 0) {
this._setNoteInstance(group[0], new LongMoveNote(this.song.score[group[0]], note, this._getSyncNote(group[0])))
} else {
this._setNoteInstance(group[0], new FlipNote(this.song.score[group[0]], note, this._getSyncNote(group[0])))
}
}
this._setNoteInstance(i, new LongMoveNote(note, undefined, this._getSyncNote(i)))
break
}
default:
break
}
}
}
public start (): void {
if (!this._isReady) {
setTimeout(() => {
this.start()
}, 100)
return
}
this.audio.play().catch(err => {
console.error(err)
error(`SCOREVIEWER start: ${err.stack}`)
})
const self = this
_frame()
function _frame (): void {
self._cal()
self._renderNote()
self._t = window.requestAnimationFrame(_frame)
}
}
public stop (): void {
this.audio.pause()
window.cancelAnimationFrame(this._t)
}
private _clear (): void {
if (!this._isClean) {
this.frontCtx.clearRect(0, 0, ScoreViewer.CANVAS_WIDTH, ScoreViewer.CANVAS_HEIGHT - 15)
this._isClean = true
}
}
private _cal (): void {
let combo = -1
for (let i = 0; i < this.song.score.length; i++) {
if (this.song.score[i].sec > this.audio.currentTime) {
combo = i
break
}
(this.song.score[i]._instance as Note).setY(ScoreViewer.calY(this.options.speed, this.song.score[i].sec, this.audio.currentTime))
}
if (combo === -1) combo = this.song.score.length
if (this._comboDom.innerHTML !== combo.toString()) this._comboDom.innerHTML = combo.toString()
for (let i = combo; i < this.song.score.length; i++) {
(this.song.score[i]._instance as Note).setY(ScoreViewer.calY(this.options.speed, this.song.score[i].sec, this.audio.currentTime))
}
}
private _findLongNote (begin: number, finishPos: number): number {
for (let i = begin + 1; i < this.song.score.length; i++) {
if (this.song.score[i].finishPos === finishPos) {
return i
}
}
return -1
}
private _findSameGroup (begin: number, groupId: number): number[] {
if (groupId === 0) return []
const index = []
for (let i = begin + 1; i < this.song.score.length; i++) {
if (this.song.score[i].groupId === groupId) {
index.push(i)
}
}
return index
}
private _renderNote (): void {
this._clear()
for (let i = this.song.score.length - 1; i >= 0; i--) {
if ((this.song.score[i]._instance as Note).isNeedDraw()) (this.song.score[i]._instance as Note).drawConnection(this)
}
this.frontCtx.save()
this.frontCtx.fillStyle = '#fff'
for (let i = this.song.score.length - 1; i >= 0; i--) {
if ((this.song.score[i]._instance as Note).isNeedDraw()) (this.song.score[i]._instance as Note).drawSync(this)
}
this.frontCtx.restore()
for (let i = this.song.score.length - 1; i >= 0; i--) {
if ((this.song.score[i]._instance as Note).isNeedDraw()) (this.song.score[i]._instance as Note).drawNote(this)
}
this._isClean = false
}
private _getSyncNote (index: number): ScoreNote | undefined {
if (index !== this.song.score.length - 1 && this.song.score[index].sync === 1 && this.song.score[index].sec === this.song.score[index + 1].sec) {
return this.song.score[index + 1]
}
return undefined
}
private _saveScore (): void {
if (!this._isReady) {
setTimeout(() => {
this._saveScore()
}, 100)
return
}
const name = parse(this.song.src).name.substr(parse(this.song.src).name.indexOf('-') + 1)
const _drawAndSave = (filename: string): void => {
if (!this._isReadyToSave) {
this.stop()
this.saveCanvas.height = globalInstance.saveSpeed * 60 * this.audio.duration / globalInstance.scale
this.saveCtx = this.saveCanvas.getContext('2d') as CanvasRenderingContext2D
this.saveCtx.fillStyle = 'rgba(255, 255, 255, 0.66)'
this.saveCtx.save()
this.saveCtx.fillStyle = 'rgb(39, 40, 34)'
this.saveCtx.font = '12px Consolas'
this.saveCtx.fillRect(0, 0, this.saveCanvas.width, this.saveCanvas.height)
this.saveCtx.strokeStyle = '#e070d0'
this.saveCtx.fillStyle = '#e070d0'
const b = Math.round(this.audio.duration * this.song.bpm / 60)
for (let i = 0; i < b; i += 4) {
const y = this.saveCanvas.height - (i * 60 / this.song.bpm * globalInstance.saveSpeed * 60) / globalInstance.scale + globalInstance.noteHeight / 2 / globalInstance.scale
this.saveCtx.fillText(i.toString(), 1, y - 2)
this.saveCtx.beginPath()
this.saveCtx.moveTo(0, y)
this.saveCtx.lineTo(this.saveCanvas.width, y)
this.saveCtx.stroke()
this.saveCtx.closePath()
}
const firstY = this.saveCanvas.height - (60 / this.song.bpm * globalInstance.saveSpeed * 60) / globalInstance.scale + globalInstance.noteHeight / 2 / globalInstance.scale
this.saveCtx.font = '14px -apple-system, BlinkMacSystemFont, Segoe WPC,Segoe UI, HelveticaNeue-Light, Noto Sans, Microsoft YaHei, PingFang SC, Hiragino Sans GB, Source Han Sans SC, Source Han Sans CN, Source Han Sans, sans-serif'
this.saveCtx.fillStyle = '#fff'
this.saveCtx.textAlign = 'center'
this.saveCtx.fillText('https://github.com/toyobayashi/mishiro', this.saveCanvas.width / 2, firstY - 7)
this.saveCtx.fillText(name, this.saveCanvas.width / 2, firstY - 7 - 16 * 3)
this.saveCtx.fillText(this.song.difficulty, this.saveCanvas.width / 2, firstY - 7 - 16 * 4)
this.saveCtx.restore()
globalInstance.noteWidth /= globalInstance.scale
globalInstance.noteHeight /= globalInstance.scale
globalInstance.noteWidthFlip /= globalInstance.scale
const OLD_TOP_TO_TARGET_POSITION = ScoreViewer.TOP_TO_TARGET_POSITION
const oldX = ScoreViewer.X
ScoreViewer.X = [238 - 206, 414 - 206, 589 - 206, 764 - 206, 937 - 206].map(v => v / globalInstance.scale)
ScoreViewer.TOP_TO_TARGET_POSITION = this.saveCanvas.height
for (let i = 0; i < this.song.score.length; i++) {
(this.song.score[i]._instance as Note).setX((this.song.score[i]._instance as Note).getX() / globalInstance.scale);
(this.song.score[i]._instance as Note).setY(ScoreViewer.saveCalY(this, this.song.score[i].sec))
}
for (let i = this.song.score.length - 1; i >= 0; i--) {
(this.song.score[i]._instance as Note).saveDrawConnection(this)
}
this.saveCtx.save()
this.saveCtx.fillStyle = '#fff'
for (let i = this.song.score.length - 1; i >= 0; i--) {
(this.song.score[i]._instance as Note).saveDrawSync(this)
}
this.saveCtx.restore()
for (let i = this.song.score.length - 1; i >= 0; i--) {
(this.song.score[i]._instance as Note).saveDrawNote(this)
}
for (let i = 0; i < this.song.score.length; i++) {
(this.song.score[i]._instance as Note).setX((this.song.score[i]._instance as Note).getX() * globalInstance.scale)
}
globalInstance.noteWidth *= globalInstance.scale
globalInstance.noteHeight *= globalInstance.scale
globalInstance.noteWidthFlip *= globalInstance.scale
ScoreViewer.TOP_TO_TARGET_POSITION = OLD_TOP_TO_TARGET_POSITION
ScoreViewer.X = oldX
}
const base64str = this.saveCanvas.toDataURL('image/png')
if (base64str === 'data:,') {
const OLD_SAVE_SPEED = globalInstance.saveSpeed
globalInstance.saveSpeed--
_drawAndSave(filename)
globalInstance.saveSpeed = OLD_SAVE_SPEED
return
}
this._isReadyToSave = true
this.start()
fs.writeFile(filename, Buffer.from(base64str.substr(22), 'base64'), (err) => {
if (err) alert(err.message)
})
}
showSaveDialog({
title: 'Save Score - ' + name + '-' + this.song.difficulty,
defaultPath: getPath.scoreDir(name + '-' + this.song.difficulty + '.png')
}).then((res) => {
res.filePath && _drawAndSave(res.filePath)
}).catch((err) => {
console.error(err)
error(`SCOREVIEWER _saveScore: ${err.stack}`)
})
}
private _formatTime (second: number): string {
let min: string | number = Math.floor(second / 60)
let sec: string | number = Math.floor(second % 60)
if (min < 10) {
min = `0${min}`
}
if (sec < 10) {
sec = `0${sec}`
}
return `${min}:${sec}`
}
private _resolveDOM (el: HTMLElement): void {
const background = document.getElementById('bg') as HTMLImageElement
this.frontCanvas = document.createElement('canvas')
this.backCanvas = document.createElement('canvas')
this.saveCanvas = document.createElement('canvas')
this.frontCanvas.width = this.backCanvas.width = ScoreViewer.CANVAS_WIDTH
this.frontCanvas.height = this.backCanvas.height = ScoreViewer.CANVAS_HEIGHT
this.saveCanvas.width = ScoreViewer.CANVAS_WIDTH / globalInstance.scale
this.frontCanvas.className = this.backCanvas.className = 'canvas canvas-center'
this.pauseButton = document.createElement('button')
this.pauseButton.innerHTML = 'pause'
this.pauseButton.addEventListener('click', () => {
globalInstance.playSe()
if (this._isPaused) {
this.start()
} else {
this.stop()
}
})
this.pauseButton.className = 'cgss-btn cgss-btn-star'
this.pauseButton.style.position = 'absolute'
this.pauseButton.style.zIndex = '2000'
this.pauseButton.style.top = '2%'
this.pauseButton.style.left = '1%'
this.saveButton = document.createElement('button')
this.saveButton.innerHTML = 'save'
this.saveButton.addEventListener('click', () => {
globalInstance.playSeOk()
this._saveScore()
})
this.saveButton.className = 'cgss-btn cgss-btn-ok'
this.saveButton.style.position = 'absolute'
this.saveButton.style.zIndex = '2000'
this.saveButton.style.top = 'calc(2% + 84px)'
this.saveButton.style.left = '1%'
this.rangeInput = document.createElement('input')
this.rangeInput.type = 'range'
this.rangeInput.min = '0'
this.rangeInput.max = '100'
this.rangeInput.value = '0'
this.rangeInput.style.position = 'absolute'
this.rangeInput.style.zIndex = '2000'
this.rangeInput.style.width = '50%'
this.rangeInput.style.left = '25%'
this.rangeInput.style.bottom = '10px'
this.rangeInput.addEventListener('input', (ev) => {
this.audio.currentTime = Number((ev.target as HTMLInputElement).value)
this.progressTime.innerHTML = `${this._formatTime(Number((ev.target as HTMLInputElement).value))} / ${this._formatTime(this.audio.duration)}`
})
this.speedInput = document.createElement('input')
this.speedInput.type = 'range'
this.speedInput.min = '5'
this.speedInput.max = '20'
this.speedInput.value = '12'
this.speedInput.style.position = 'absolute'
this.speedInput.style.zIndex = '2000'
this.speedInput.style.width = '15%'
this.speedInput.style.left = '2%'
this.speedInput.style.bottom = '10px'
this.speedInput.addEventListener('input', (ev) => {
this.options.speed = Number((ev.target as HTMLInputElement).value)
})
this.progressTime = document.createElement('span')
this.progressTime.innerHTML = '00:00 / 00:00'
this.progressTime.style.position = 'absolute'
this.progressTime.style.zIndex = '2000'
this.progressTime.style.width = '15%'
this.progressTime.style.right = '2%'
this.progressTime.style.bottom = '2px'
this.progressTime.style.color = '#fff'
this.progressTime.style.fontFamily = 'CGSS-B'
el.appendChild(this.backCanvas)
el.appendChild(this.frontCanvas)
el.appendChild(this.pauseButton)
el.appendChild(this.saveButton)
el.appendChild(this.rangeInput)
el.appendChild(this.speedInput)
el.appendChild(this.progressTime)
this._comboDom = document.getElementById('combo') as HTMLDivElement
this.frontCtx = this.frontCanvas.getContext('2d') as CanvasRenderingContext2D
this.backCtx = this.backCanvas.getContext('2d') as CanvasRenderingContext2D
this.frontCtx.fillStyle = 'rgba(255, 255, 255, 0.66)'
const liveIcon = Global.newImage('../../asset/img.asar/live_icon_857x114.png')
liveIcon.addEventListener('load', () => {
this.backCtx.drawImage(liveIcon, 5, ScoreViewer.CANVAS_HEIGHT - ScoreViewer.BOTTOM - 114)
}, false)
this.audio.on('canplay', () => {
this._isReady = true
this.rangeInput.max = this.audio.duration.toString()
})
this.audio.on('play', () => {
this._isPaused = false
this.pauseButton.innerHTML = 'pause'
this.pauseButton.className = 'cgss-btn cgss-btn-star'
})
this.audio.on('pause', () => {
this._isPaused = true
this.pauseButton.innerHTML = 'play'
this.pauseButton.className = 'cgss-btn cgss-btn-ok'
})
this.audio.on('ended', () => {
window.close()
})
this.audio.on('timeupdate', () => {
this.rangeInput.value = this.audio.currentTime.toString()
this.progressTime.innerHTML = `${this._formatTime(this.audio.currentTime)} / ${this._formatTime(this.audio.duration)}`
this.rangeInput.style.backgroundSize = `${100 * (this.audio.currentTime / this.audio.duration)}% 100%`
})
window.addEventListener('resize', () => {
if (window.innerWidth / window.innerHeight >= 1280 / 824) {
background.className = 'img-middle'
} else {
background.className = 'img-center'
}
if (window.innerWidth / window.innerHeight >= ScoreViewer.CANVAS_WIDTH / ScoreViewer.CANVAS_HEIGHT) {
this.frontCanvas.className = 'canvas canvas-center'
if (this.backCanvas) this.backCanvas.className = 'canvas canvas-center'
} else {
this.frontCanvas.className = 'canvas canvas-middle'
if (this.backCanvas) this.backCanvas.className = 'canvas canvas-middle'
}
}, false)
}
}
export default ScoreViewer | the_stack |
import * as stream from 'stream';
import {Service} from './service';
import {Response} from './response';
import {HttpRequest} from './http_request';
import {AWSError} from './error';
export class Request<D, E> {
/**
* Creates a request for an operation on a given service with a set of input parameters.
*
* @param {AWS.Service} service - The service to perform the operation on.
* @param {string} operation - The operation to perform on the service.
* @param {object} params - Parameters to send to the operation.
*/
constructor(service: Service, operation: string, params?: any);
/**
* Aborts a request, emitting the error and complete events.
* This feature is not supported in the browser environment of the SDK.
*/
abort(): void;
/**
* Converts the request object into a readable stream that can be read from or piped into a writable stream.
* The data read from a readable stream contains only the raw HTTP body contents.
* This feature is not supported in the browser environment of the SDK.
*/
createReadStream(): stream.Readable;
/**
* Iterates over each page of results given a pageable request, calling the provided callback with each page of data.
* After all pages have been retrieved, the callback is called with null data.
*
* @param {eachPage} callback - The callback that handles the response.
*/
eachPage(callback: (err: E, data: D, doneCallback?: () => void) => boolean): void;
/**
* Returns whether the operation can return multiple pages of response data.
*/
isPageable(): boolean;
/**
* Sends the request object.
* If a callback is supplied, it is called when a response is returned from the service.
*/
send(callback?: (err: E, data: D) => void): void;
/**
* Adds a listener that is triggered when a request emits the specified event.
*
* @param {string} event - 'Name of a request event.'
* @param {function} listener - Callback to run when the event is triggered on the request.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
on(event: string, listener: () => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when a request is being validated.
*
* @param {string} event - validate: triggered when a request is being validated.
* @param {function} listener - Callback to run when the request is being validated.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
on(event: "validate", listener: (request: Request<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when the request payload is being built.
*
* @param {string} event - build: triggered when the request payload is being built.
* @param {function} listener - Callback to run when the request's payload is being built.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
on(event: "build", listener: (request: Request<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when a request is being signed.
*
* @param {string} event - sign: triggered when a request is being signed.
* @param {function} listener - Callback to run when the request is being signed.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
on(event: "sign", listener: (request: Request<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when a request is ready to be sent.
*
* @param {string} event - send: triggered when a request is ready to be sent.
* @param {function} listener - Callback to run when the request is ready to be sent.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
on(event: "send", listener: (response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when a request failed and might need to be retried or redirected.
*
* @param {string} event - retry: triggered when a request failed and might need to be retried or redirected.
* @param {function} listener - Callback to run when the request failed and may be retried.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
on(event: "retry", listener: (response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered on all non-2xx requests so that listeners can extract error details from the response body.
*
* @param {string} event - extractError: triggered on all non-2xx requests so that listeners can extract error details from the response body.
* @param {function} listener - Callback to run when the request failed.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
on(event: "extractError", listener: (response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered in successful requests to allow listeners to de-serialize the response body into response.data.
*
* @param {string} event - extractData: triggered in successful requests to allow listeners to de-serialize the response body into response.data.
* @param {function} listener - Callback to run when the request succeeded.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
on(event: "extractData", listener: (response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when the request completed successfully.
*
* @param {string} event - success: triggered when the request completed successfully.
* @param {function} listener - Callback to run when the request completed successfully.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
on(event: "success", listener: (response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when an error occurs at any point during the request.
*
* @param {string} event - error: triggered when an error occurs at any point during the request.
* @param {function} listener - Callback to run when the request errors at any point.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
on(event: "error", listener: (err: AWSError, response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered whenever a request cycle completes.
*
* @param {string} event - complete: triggered whenever a request cycle completes.
* @param {function} listener - Callback to run when the request cycle completes.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
on(event: "complete", listener: (response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when headers are sent by the remote server.
*
* @param {string} event - httpHeaders: triggered when headers are sent by the remote server.
* @param {function} listener - Callback to run when the headers are sent by the remote server.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
on(event: "httpHeaders", listener: (statusCode: number, headers: {[key: string]: string}, response: Response<D, E>, statusMessage: string) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when data is sent by the remote server.
*
* @param {string} event - httpData: triggered when data is sent by the remote server.
* @param {function} listener - Callback to run when data is sent by the remote server.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
on(event: "httpData", listener: (chunk: Buffer|Uint8Array, response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when the HTTP request has uploaded more data.
*
* @param {string} event - httpUploadProgress: triggered when the HTTP request has uploaded more data.
* @param {function} listener - Callback to run when the HTTP request has uploaded more data.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
on(event: "httpUploadProgress", listener: (progress: Progress, response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when the HTTP request has downloaded more data.
*
* @param {string} event - httpDownloadProgress: triggered when the HTTP request has downloaded more data.
* @param {function} listener - Callback to run when the HTTP request has downloaded more data.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
on(event: "httpDownloadProgress", listener: (progress: Progress, response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when the HTTP request failed.
*
* @param {string} event - httpError: triggered when the HTTP request failed.
* @param {function} listener - Callback to run when the HTTP request failed.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
on(event: "httpError", listener: (err: Error, response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when the server is finished sending data.
*
* @param {string} event - httpDone: triggered when the server is finished sending data.
* @param {function} listener - Callback to run when the server is finished sending data.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
on(event: "httpDone", listener: (response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when a request emits the specified event.
*
* @param {string} event - 'Name of a request event.'
* @param {function} listener - Callback to run when the event is triggered on the request.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
onAsync(event: string, listener: () => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when a request is being validated.
*
* @param {string} event - validate: triggered when a request is being validated.
* @param {function} listener - Callback to run when the request is being validated.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
onAsync(event: "validate", listener: (request: Request<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when the request payload is being built.
*
* @param {string} event - build: triggered when the request payload is being built.
* @param {function} listener - Callback to run when the request's payload is being built.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
onAsync(event: "build", listener: (request: Request<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when a request is being signed.
*
* @param {string} event - sign: triggered when a request is being signed.
* @param {function} listener - Callback to run when the request is being signed.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
onAsync(event: "sign", listener: (request: Request<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when a request is ready to be sent.
*
* @param {string} event - send: triggered when a request is ready to be sent.
* @param {function} listener - Callback to run when the request is ready to be sent.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
onAsync(event: "send", listener: (response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when a request failed and might need to be retried or redirected.
*
* @param {string} event - retry: triggered when a request failed and might need to be retried or redirected.
* @param {function} listener - Callback to run when the request failed and may be retried.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
onAsync(event: "retry", listener: (response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered on all non-2xx requests so that listeners can extract error details from the response body.
*
* @param {string} event - extractError: triggered on all non-2xx requests so that listeners can extract error details from the response body.
* @param {function} listener - Callback to run when the request failed.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
onAsync(event: "extractError", listener: (response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered in successful requests to allow listeners to de-serialize the response body into response.data.
*
* @param {string} event - extractData: triggered in successful requests to allow listeners to de-serialize the response body into response.data.
* @param {function} listener - Callback to run when the request succeeded.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
onAsync(event: "extractData", listener: (response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when the request completed successfully.
*
* @param {string} event - success: triggered when the request completed successfully.
* @param {function} listener - Callback to run when the request completed successfully.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
onAsync(event: "success", listener: (response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when an error occurs at any point during the request.
*
* @param {string} event - error: triggered when an error occurs at any point during the request.
* @param {function} listener - Callback to run when the request errors at any point.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
onAsync(event: "error", listener: (err: AWSError, response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered whenever a request cycle completes.
*
* @param {string} event - complete: triggered whenever a request cycle completes.
* @param {function} listener - Callback to run when the request cycle completes.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
onAsync(event: "complete", listener: (response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when headers are sent by the remote server.
*
* @param {string} event - httpHeaders: triggered when headers are sent by the remote server.
* @param {function} listener - Callback to run when the headers are sent by the remote server.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
onAsync(event: "httpHeaders", listener: (statusCode: number, headers: {[key: string]: string}, response: Response<D, E>, statusMessage: string) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when data is sent by the remote server.
*
* @param {string} event - httpData: triggered when data is sent by the remote server.
* @param {function} listener - Callback to run when data is sent by the remote server.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
onAsync(event: "httpData", listener: (chunk: Buffer|Uint8Array, response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when the HTTP request has uploaded more data.
*
* @param {string} event - httpUploadProgress: triggered when the HTTP request has uploaded more data.
* @param {function} listener - Callback to run when the HTTP request has uploaded more data.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
onAsync(event: "httpUploadProgress", listener: (progress: Progress, response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when the HTTP request has downloaded more data.
*
* @param {string} event - httpDownloadProgress: triggered when the HTTP request has downloaded more data.
* @param {function} listener - Callback to run when the HTTP request has downloaded more data.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
onAsync(event: "httpDownloadProgress", listener: (progress: Progress, response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when the HTTP request failed.
*
* @param {string} event - httpError: triggered when the HTTP request failed.
* @param {function} listener - Callback to run when the HTTP request failed.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
onAsync(event: "httpError", listener: (err: Error, response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Adds a listener that is triggered when the server is finished sending data.
*
* @param {string} event - httpDone: triggered when the server is finished sending data.
* @param {function} listener - Callback to run when the server is finished sending data.
* @param {boolean} prepend - If set, prepends listener instead of appending.
*/
onAsync(event: "httpDone", listener: (response: Response<D, E>) => void, prepend?: boolean): Request<D, E>;
/**
* Returns a 'thenable' promise.
*/
promise(): Promise<PromiseResult<D, E>>
/**
* The time that the request started.
*/
startTime: Date;
/**
* The raw HTTP request object containing request headers and body information sent by the service.
*/
httpRequest: HttpRequest;
}
export type PromiseResult<D, E> = D & {$response: Response<D, E>};
export interface Progress {
loaded: number;
total: number;
} | the_stack |
import * as path from "path";
import * as util from "util";
import * as _ from "lodash";
import { APP_FOLDER_NAME } from "../../constants";
import { getHash } from "../../common/helpers";
import { performanceLog } from "../../common/decorators";
import { IPlatformsDataService } from "../../definitions/platform";
import { IProjectData } from "../../definitions/project";
import {
IFileSystem,
IDictionary,
IProjectFilesManager,
} from "../../common/declarations";
export abstract class PlatformLiveSyncServiceBase {
private _deviceLiveSyncServicesCache: IDictionary<
INativeScriptDeviceLiveSyncService
> = {};
constructor(
protected $fs: IFileSystem,
protected $logger: ILogger,
protected $platformsDataService: IPlatformsDataService,
protected $projectFilesManager: IProjectFilesManager,
private $devicePathProvider: IDevicePathProvider
) {}
public getDeviceLiveSyncService(
device: Mobile.IDevice,
projectData: IProjectData
): INativeScriptDeviceLiveSyncService {
const platform = device.deviceInfo.platform.toLowerCase();
const platformData = this.$platformsDataService.getPlatformData(
device.deviceInfo.platform,
projectData
);
const frameworkVersion = platformData.platformProjectService.getFrameworkVersion(
projectData
);
const key = getHash(
`${device.deviceInfo.identifier}${projectData.projectIdentifiers[platform]}${projectData.projectDir}${frameworkVersion}`
);
if (!this._deviceLiveSyncServicesCache[key]) {
this._deviceLiveSyncServicesCache[key] = this._getDeviceLiveSyncService(
device,
projectData,
frameworkVersion
);
}
return this._deviceLiveSyncServicesCache[key];
}
protected abstract _getDeviceLiveSyncService(
device: Mobile.IDevice,
data: IProjectData,
frameworkVersion: string
): INativeScriptDeviceLiveSyncService;
public async shouldRestart(
projectData: IProjectData,
liveSyncInfo: ILiveSyncResultInfo
): Promise<boolean> {
const deviceLiveSyncService = this.getDeviceLiveSyncService(
liveSyncInfo.deviceAppData.device,
projectData
);
const shouldRestart = await deviceLiveSyncService.shouldRestart(
projectData,
liveSyncInfo
);
return shouldRestart;
}
public async syncAfterInstall(
device: Mobile.IDevice,
liveSyncInfo: ILiveSyncWatchInfo
): Promise<void> {
/* intentionally left blank */
}
public async restartApplication(
projectData: IProjectData,
liveSyncInfo: ILiveSyncResultInfo
): Promise<void> {
const deviceLiveSyncService = this.getDeviceLiveSyncService(
liveSyncInfo.deviceAppData.device,
projectData
);
this.$logger.info(
`Restarting application on device ${liveSyncInfo.deviceAppData.device.deviceInfo.identifier}...`
);
await deviceLiveSyncService.restartApplication(projectData, liveSyncInfo);
}
public async tryRefreshApplication(
projectData: IProjectData,
liveSyncInfo: ILiveSyncResultInfo
): Promise<boolean> {
let didRefresh = true;
if (liveSyncInfo.isFullSync || liveSyncInfo.modifiedFilesData.length) {
const deviceLiveSyncService = this.getDeviceLiveSyncService(
liveSyncInfo.deviceAppData.device,
projectData
);
this.$logger.info(
`Refreshing application on device ${liveSyncInfo.deviceAppData.device.deviceInfo.identifier}...`
);
didRefresh = await deviceLiveSyncService.tryRefreshApplication(
projectData,
liveSyncInfo
);
}
return didRefresh;
}
public async fullSync(syncInfo: IFullSyncInfo): Promise<ILiveSyncResultInfo> {
const projectData = syncInfo.projectData;
const device = syncInfo.device;
const deviceLiveSyncService = this.getDeviceLiveSyncService(
device,
syncInfo.projectData
);
const platformData = this.$platformsDataService.getPlatformData(
device.deviceInfo.platform,
projectData
);
const deviceAppData = await this.getAppData(syncInfo);
if (deviceLiveSyncService.beforeLiveSyncAction) {
await deviceLiveSyncService.beforeLiveSyncAction(deviceAppData);
}
const projectFilesPath = path.join(
platformData.appDestinationDirectoryPath,
APP_FOLDER_NAME
);
const localToDevicePaths = await this.$projectFilesManager.createLocalToDevicePaths(
deviceAppData,
projectFilesPath,
null,
[]
);
const modifiedFilesData = await this.transferFiles(
deviceAppData,
localToDevicePaths,
projectFilesPath,
projectData,
syncInfo.liveSyncDeviceData,
{ isFullSync: true, force: syncInfo.force }
);
return {
modifiedFilesData,
isFullSync: true,
deviceAppData,
useHotModuleReload: syncInfo.useHotModuleReload,
};
}
@performanceLog()
public async liveSyncWatchAction(
device: Mobile.IDevice,
liveSyncInfo: ILiveSyncWatchInfo
): Promise<ILiveSyncResultInfo> {
const projectData = liveSyncInfo.projectData;
const deviceLiveSyncService = this.getDeviceLiveSyncService(
device,
projectData
);
const syncInfo = _.merge({ device, watch: true }, liveSyncInfo);
const deviceAppData = await this.getAppData(syncInfo);
if (deviceLiveSyncService.beforeLiveSyncAction) {
await deviceLiveSyncService.beforeLiveSyncAction(deviceAppData);
}
let modifiedLocalToDevicePaths: Mobile.ILocalToDevicePathData[] = [];
if (liveSyncInfo.filesToSync.length) {
const filesToSync = liveSyncInfo.filesToSync;
// const mappedFiles = _.map(filesToSync, filePath => this.$projectFilesProvider.mapFilePath(filePath, device.deviceInfo.platform, projectData));
// Some plugins modify platforms dir on afterPrepare (check nativescript-dev-sass) - we want to sync only existing file.
const existingFiles = filesToSync.filter((m) => m && this.$fs.exists(m));
this.$logger.trace("Will execute livesync for files: ", existingFiles);
const skippedFiles = _.difference(filesToSync, existingFiles);
if (skippedFiles.length) {
this.$logger.trace(
"The following files will not be synced as they do not exist:",
skippedFiles
);
}
if (existingFiles.length) {
const platformData = this.$platformsDataService.getPlatformData(
device.deviceInfo.platform,
projectData
);
const projectFilesPath = path.join(
platformData.appDestinationDirectoryPath,
APP_FOLDER_NAME
);
const localToDevicePaths = await this.$projectFilesManager.createLocalToDevicePaths(
deviceAppData,
projectFilesPath,
existingFiles,
[]
);
modifiedLocalToDevicePaths.push(...localToDevicePaths);
modifiedLocalToDevicePaths = await this.transferFiles(
deviceAppData,
localToDevicePaths,
projectFilesPath,
projectData,
liveSyncInfo.liveSyncDeviceData,
{ isFullSync: false, force: liveSyncInfo.force }
);
}
}
if (liveSyncInfo.filesToRemove.length) {
const filePaths = liveSyncInfo.filesToRemove;
const platformData = this.$platformsDataService.getPlatformData(
device.deviceInfo.platform,
projectData
);
const mappedFiles = _(filePaths)
// .map(filePath => this.$projectFilesProvider.mapFilePath(filePath, device.deviceInfo.platform, projectData))
.filter((filePath) => !!filePath)
.value();
const projectFilesPath = path.join(
platformData.appDestinationDirectoryPath,
APP_FOLDER_NAME
);
const localToDevicePaths = await this.$projectFilesManager.createLocalToDevicePaths(
deviceAppData,
projectFilesPath,
mappedFiles,
[]
);
modifiedLocalToDevicePaths.push(...localToDevicePaths);
await deviceLiveSyncService.removeFiles(
deviceAppData,
localToDevicePaths,
projectFilesPath
);
}
return {
modifiedFilesData: modifiedLocalToDevicePaths,
isFullSync: false,
deviceAppData,
useHotModuleReload: liveSyncInfo.useHotModuleReload,
};
}
private async transferFiles(
deviceAppData: Mobile.IDeviceAppData,
localToDevicePaths: Mobile.ILocalToDevicePathData[],
projectFilesPath: string,
projectData: IProjectData,
liveSyncDeviceData: ILiveSyncDeviceDescriptor,
options: ITransferFilesOptions
): Promise<Mobile.ILocalToDevicePathData[]> {
let transferredFiles: Mobile.ILocalToDevicePathData[] = [];
const deviceLiveSyncService = this.getDeviceLiveSyncService(
deviceAppData.device,
projectData
);
transferredFiles = await deviceLiveSyncService.transferFiles(
deviceAppData,
localToDevicePaths,
projectFilesPath,
projectData,
liveSyncDeviceData,
options
);
await deviceAppData.device.applicationManager.setTransferredAppFiles(
localToDevicePaths.map((l) => l.getLocalPath())
);
this.logFilesSyncInformation(
transferredFiles,
"Successfully transferred %s on device %s.",
this.$logger.info,
deviceAppData.device.deviceInfo.identifier
);
return transferredFiles;
}
public async getAppData(
syncInfo: IFullSyncInfo
): Promise<Mobile.IDeviceAppData> {
const platform = syncInfo.device.deviceInfo.platform.toLowerCase();
const appIdentifier = syncInfo.projectData.projectIdentifiers[platform];
const deviceProjectRootOptions: IDeviceProjectRootOptions = _.assign(
{ appIdentifier },
syncInfo
);
return {
appIdentifier,
device: syncInfo.device,
platform: syncInfo.device.deviceInfo.platform,
getDeviceProjectRootPath: () =>
this.$devicePathProvider.getDeviceProjectRootPath(
syncInfo.device,
deviceProjectRootOptions
),
deviceSyncZipPath: this.$devicePathProvider.getDeviceSyncZipPath(
syncInfo.device
),
connectTimeout: syncInfo.connectTimeout,
projectDir: syncInfo.projectData.projectDir,
};
}
private logFilesSyncInformation(
localToDevicePaths: Mobile.ILocalToDevicePathData[],
message: string,
action: Function,
deviceIdentifier: string
): void {
if (localToDevicePaths && localToDevicePaths.length < 10) {
_.each(localToDevicePaths, (file: Mobile.ILocalToDevicePathData) => {
action.call(
this.$logger,
util.format(message, path.basename(file.getLocalPath()).yellow),
deviceIdentifier
);
});
} else {
action.call(
this.$logger,
util.format(message, "all files", deviceIdentifier)
);
}
}
} | the_stack |
import { Router } from 'express';
import asyncHandler from 'express-async-handler';
const router: Router = Router();
import { ReposAppRequest, IAppSession, SupportedLinkType, ICorporateLink, LinkOperationSource } from '../interfaces';
import { getProviders, splitSemiColonCommas } from '../transitional';
import { IndividualContext } from '../user';
import { storeOriginalUrlAsReferrer, wrapError } from '../utils';
import validator from 'validator';
import unlinkRoute from './unlink';
import { jsonError } from '../middleware';
interface IRequestWithSession extends ReposAppRequest {
session: IAppSession;
}
interface IRequestHacked extends ReposAppRequest {
overrideLinkUserPrincipalName?: any;
}
router.use((req: IRequestHacked, res, next) => {
const config = getProviders(req).config;;
if (config && config.github && config.github.links && config.github.links.provider && config.github.links.provider.linkingOfflineMessage) {
return next(new Error(`Linking is temporarily offline: ${config.github.links.provider.linkingOfflineMessage}`));
} else {
return next();
}
});
router.use('/', asyncHandler(async function (req: ReposAppRequest, res, next) {
// Make sure both account types are authenticated before showing the link pg [wi 12690]
const individualContext = req.individualContext;
if (!individualContext.corporateIdentity || !individualContext.getGitHubIdentity()) {
req.insights.trackEvent({ name: 'PortalSessionNeedsBothGitHubAndAadUsernames' });
return res.redirect('/?signin');
}
return next();
}));
// TODO: graph provider non-guest check should be middleware and in the link business process
router.use(asyncHandler(async (req: IRequestHacked, res, next) => {
const individualContext = req.individualContext as IndividualContext;
const providers = getProviders(req);
const insights = providers.insights;
const config = providers.config;
let validateAndBlockGuests = false;
if (config && config.activeDirectory && config.activeDirectory.blockGuestUserTypes) {
validateAndBlockGuests = true;
}
// If the app has not been configured to check whether a user is a guest before linking, continue:
if (!validateAndBlockGuests) {
return next();
}
const aadId = individualContext.corporateIdentity.id;
// If the app is configured to check guest status, do this now, before linking:
const graphProvider = providers.graphProvider;
// REFACTOR: delegate the decision to the auth provider
if (!graphProvider || !graphProvider.getUserById) {
return next(new Error('User type validation cannot be performed because there is no graphProvider configured for this type of account'));
}
insights.trackEvent({
name: 'LinkValidateNotGuestStart',
properties: {
aadId: aadId,
},
});
try {
const details = await graphProvider.getUserById(aadId);
const userType = details.userType;
const displayName = details.displayName;
const userPrincipalName = details.userPrincipalName;
let block = userType as string === 'Guest';
let blockedRecord = block ? 'BLOCKED' : 'not blocked';
// If the app is configured to check for guests, but this is a specifically permitted guest user, continue:
if (config?.activeDirectoryGuests) {
const authorizedGuests = Array.isArray(config.activeDirectoryGuests) ? config.activeDirectoryGuests as string[] : splitSemiColonCommas(config.activeDirectoryGuests);
if (!authorizedGuests.includes(aadId)) {
block = false;
blockedRecord = 'specifically authorized user ' + aadId + ' ' + userPrincipalName;
req.overrideLinkUserPrincipalName = userPrincipalName;
return next(new Error('This feature is not currently available. Please reach out to support to re-enable this feature.'));
}
}
insights.trackEvent({
name: 'LinkValidateNotGuestGraphSuccess',
properties: {
aadId: aadId,
userType: userType,
displayName: displayName,
userPrincipalName: userPrincipalName,
blocked: blockedRecord,
},
});
if (block) {
insights.trackMetric({ name: 'LinksBlockedForGuests', value: 1 });
return next(new Error(`This system is not available to guests. You are currently signed in as ${displayName} ${userPrincipalName}. Please sign out or try a private browser window.`));
}
const manager = await providers.graphProvider.getManagerById(aadId);
if (!manager || !manager.userPrincipalName) {
throw new Error(`You do not have an active manager entry in the directory and so cannot yet link.`);
}
return next();
} catch (graphError) {
insights.trackException({
exception: graphError,
properties: {
aadId: aadId,
name: 'LinkValidateNotGuestGraphFailure',
},
});
return next(graphError);
}
}));
router.get('/', asyncHandler(async function (req: ReposAppRequest, res, next) {
const individualContext = req.individualContext;
const link = individualContext.link;
if (!individualContext.corporateIdentity && !individualContext.getGitHubIdentity()) {
req.insights.trackEvent({ name: 'PortalSessionNeedsBothGitHubAndAadUsernames' });
return res.redirect('/?signin');
}
if (!individualContext.getGitHubIdentity()) {
req.insights.trackEvent({ name: 'PortalSessionNeedsGitHubUsername' });
return res.redirect('/signin/github/');
}
if (!link) {
return await showLinkPage(req, res);
} else {
req.insights.trackEvent({ name: 'LinkRouteLinkLocated' });
let organizations = null;
try {
organizations = await individualContext.aggregations.organizations();
} catch (ignoredError) {
/* ignore */
}
return individualContext.webContext.render({
view: 'linkConfirmed',
title: 'You\'re already linked',
state: {
organizations,
}
});
}
}));
async function showLinkPage(req: ReposAppRequest, res) {
const individualContext = req.individualContext as IndividualContext;
function render(options) {
individualContext.webContext.render({
view: 'link',
title: 'Link GitHub with corporate identity',
optionalObject: options || {},
});
}
const { config, graphProvider } = getProviders(req);
if (config.authentication.scheme !== 'aad' || !graphProvider) {
return render(null);
}
const aadId = individualContext.corporateIdentity.id;
const { operations } = getProviders(req);
// By design, we want to log the errors but do not want any individual
// lookup problem to break the underlying experience of letting a user
// link. This is important if someone is new in the company, they may
// not be in the graph fully yet.
const userLinkData = await operations.validateCorporateAccountCanLink(aadId);
render({
graphUser: userLinkData.graphEntry,
isServiceAccountCandidate: userLinkData.type === SupportedLinkType.ServiceAccount,
});
}
router.get('/enableMultipleAccounts', function (req: IRequestWithSession, res) {
// LEGACY
// TODO: is this code still ever really used?
if (req.user.github) {
req.session.enableMultipleAccounts = true;
return res.redirect('/link/cleanup');
}
req.insights.trackEvent({ name: 'PortalUserEnabledMultipleAccounts' });
storeOriginalUrlAsReferrer(req, res, '/auth/github', 'multiple accounts enabled need to auth with GitHub again now');
});
router.post('/', asyncHandler(async (req: ReposAppRequest, res, next) => {
const individualContext = req.individualContext as IndividualContext;
try {
await interactiveLinkUser(false, individualContext, req, res, next);
} catch (error) {
return next(error);
}
}));
export async function interactiveLinkUser(isJson: boolean, individualContext: IndividualContext, req, res, next) {
const isServiceAccount = req.body.sa === '1';
const serviceAccountMail = req.body.serviceAccountMail;
const { operations } = getProviders(req);
if (isServiceAccount && !validator.isEmail(serviceAccountMail)) {
const errorMessage = 'Please enter a valid e-mail address for the Service Account maintainer.';
return next(isJson ? jsonError(errorMessage, 400) : wrapError(null, errorMessage, true));
}
let newLinkObject: ICorporateLink = null;
try {
newLinkObject = individualContext.createGitHubLinkObject();
} catch (missingInformationError) {
return next(missingInformationError);
}
if (isServiceAccount) {
newLinkObject.isServiceAccount = true;
newLinkObject.serviceAccountMail = serviceAccountMail;
const address = operations.getOperationsMailAddress();
const errorMessage = `Service Account linking is not available. Please reach out to ${address} for more information.`;
return next(isJson ? jsonError(errorMessage, 400) : new Error(errorMessage));
}
try {
await operations.linkAccounts({
link: newLinkObject,
operationSource: LinkOperationSource.Portal,
correlationId: individualContext.webContext?.correlationId || 'N/A',
skipGitHubValidation: true, // already has been verified in the recent session
});
if (isJson) {
res.status(201);
return res.end();
} else {
return res.redirect('/?onboarding=yes');
}
} catch (createError) {
const errorMessage = `We had trouble linking your corporate and GitHub accounts: ${createError.message}`;
return next(isJson ? jsonError(errorMessage, 500) : wrapError(createError, errorMessage));
}
}
router.use('/remove', unlinkRoute);
router.get('/reconnect', function (req: ReposAppRequest, res, next) {
const config = getProviders(req).config;;
if (config.authentication.scheme !== 'aad') {
return next(wrapError(null, 'Account reconnection is only needed for Active Directory authentication applications.', true));
}
// If the request comes back to the reconnect page, the authenticated app will
// actually update the link the next time around.
const ghi = req.individualContext.getGitHubIdentity();
const hasToken = !!req.individualContext.webContext.tokens.gitHubReadToken;
if (ghi && ghi.id && ghi.username && hasToken) {
req.insights.trackEvent({ name: 'PortalUserReconnected' });
return res.redirect('/');
}
req.insights.trackEvent({ name: 'PortalUserReconnectNeeded' });
req.individualContext.webContext.render({
view: 'reconnectGitHub',
title: 'Please sign in with GitHub',
state: {
expectedUsername: ghi.username,
},
});
});
export default router; | the_stack |
import React from 'react'
import classNames from 'classnames'
import { hasEnoughSpace, calculatePosition, RelativePosition } from './positioning-utils'
import './popover.less'
/**
* Position of the popover. Defaults to `auto`.
* `auto` tries to position the tooltip to the top,
* if there's not enough space it tries to position the tooltip clockwise (right, bottom, left).
* Setting a distinct value like `right` will always position the popover right, regardless of available space.
* Specifying `horizontal` will only try to position the tooltip left and right in that order.
* Specifying `vertical` will only try to position the tooltip top and bottom in that order.
*/
type Position = 'left' | 'right' | 'top' | 'bottom' | 'vertical' | 'horizontal' | 'auto'
type Props = {
visible?: boolean
/** ref of the popover in case you need to manipulate it. */
popoverRef?: React.Ref<HTMLElement>
/** ref of the wrapper in case you need to manipulate it. */
wrapperRef?: React.Ref<HTMLElement>
/** Function to be called when the mouse enters the trigger. */
onMouseEnter?: React.MouseEventHandler
/** Function to be called when the mouse leaves the trigger. */
onMouseLeave?: React.MouseEventHandler
onClick?: React.MouseEventHandler
/** Additional css class that is applied to the wrapper element. */
wrapperClassName?: string
/** Additional css class that is applied to the popover element. */
popoverClassName?: string
/** Additional css class that is applied to style the arrow. Not applied when `withArrow` is false. */
arrowClassName?: string
/** Content prop of the popover. */
content?: (() => React.ReactNode) | React.ReactNode
trigger?: React.ReactNode
position: Position
withArrow?: boolean
/**
* Whether vague positioning is allowed. When set to true the popover prefers to be fully visible over being correctly centered.
*/
allowVaguePositioning?: boolean
/** Gap between the popover wrapper and the arrow. */
gapSize: number
}
class Popover extends React.Component<Props> {
public static displayName: string
public static defaultProps: Props
componentDidMount() {
if (this.props.visible) {
this._updatePopoverPosition()
}
}
componentDidUpdate(prevProps: Props) {
if (this.wrapper && this.props.visible) {
const positionChanged = prevProps.position !== this.props.position
const vaguePositioningChanged =
prevProps.allowVaguePositioning !== this.props.allowVaguePositioning
const visibilityChanged = prevProps.visible !== this.props.visible
const arrowChanged = prevProps.withArrow !== this.props.withArrow
const gapSizeChanged = prevProps.gapSize !== this.props.gapSize
const contentChanged = prevProps.content !== this.props.content
if (
positionChanged ||
vaguePositioningChanged ||
visibilityChanged ||
arrowChanged ||
gapSizeChanged ||
contentChanged
) {
this._updatePopoverPosition()
}
}
}
popover!: HTMLElement
wrapper!: HTMLElement
_updatePopoverPosition = () => {
const { position, allowVaguePositioning, gapSize } = this.props
const wrapperRect = this.wrapper.getBoundingClientRect()
const popoverRect = this.popover.getBoundingClientRect()
// Instead of using the documentElement find the nearest absolutely positioned element
const documentEl = document.documentElement
let node = this.wrapper
let foundParent = false
while (!foundParent) {
const styles = getComputedStyle(node)
const position = styles.getPropertyValue('position')
if (position === 'absolute' || node === documentEl || !node.parentElement) {
foundParent = true
} else {
node = node.parentElement
}
}
const nodeRect = node.getBoundingClientRect()
const windowDimensions = {
height: nodeRect.height,
width: nodeRect.width,
}
const popoverDimensions = {
height: popoverRect.height,
width: popoverRect.width,
}
const wrapperDimensions = {
height: wrapperRect.height,
width: wrapperRect.width,
}
const wrapperPositionRelative = {
x: wrapperRect.left - nodeRect.left,
y: wrapperRect.top - nodeRect.top,
}
const wrapperPositionAbsolute = {
x: wrapperRect.left,
y: wrapperRect.top,
}
const positionsToTry: RelativePosition[] =
position === 'auto'
? ['top', 'right', 'bottom', 'left', 'top']
: position === 'vertical'
? ['top', 'bottom']
: position === 'horizontal'
? ['left', 'right']
: [position]
for (let index = 0; index < positionsToTry.length; index++) {
const currentPosition = positionsToTry[index]
const enoughSpaceAtPosition = hasEnoughSpace(
windowDimensions,
popoverDimensions,
wrapperDimensions,
wrapperPositionRelative,
currentPosition,
gapSize,
)
if (enoughSpaceAtPosition || index === positionsToTry.length - 1) {
const popoverPosition = calculatePosition(
currentPosition,
wrapperDimensions,
wrapperPositionAbsolute,
popoverDimensions,
gapSize,
)
this.popover.style.top = `${popoverPosition.y}px`
this.popover.style.left = `${popoverPosition.x}px`
/**
* Correct placement if vague positioning is allowed.
* When it's not allowed we "cut off" popovers and display them
* out of the viewport to maintain their centered position.
*/
if (allowVaguePositioning) {
// correct horizontally
if (popoverPosition.x < 0) {
this.popover.style.left = `${2 * gapSize}px`
}
// correct vertically
if (popoverPosition.y + popoverDimensions.height > windowDimensions.height) {
this.popover.style.top = `${
windowDimensions.height - popoverDimensions.height - 2 * gapSize
}px`
}
}
if (currentPosition !== position) {
this.popover.className = this._getClassNameForPosition(currentPosition)
}
break
}
}
}
_getClassNameForPosition = (position: Position) => {
const { visible, withArrow, arrowClassName } = this.props
const className = classNames('reactist_popover', { visible })
if (visible && withArrow) {
return classNames(className, arrowClassName, {
arrow_top: position === 'bottom',
arrow_right: position === 'left',
arrow_bottom: position === 'auto' || position === 'top',
arrow_left: position === 'right',
})
}
return className
}
_updatePopoverRef = (popover: HTMLElement) => {
this.popover = popover
if (typeof this.props.popoverRef === 'function') {
this.props.popoverRef(popover)
}
}
_updateWrapperRef = (wrapper: HTMLElement) => {
this.wrapper = wrapper
if (typeof this.props.wrapperRef === 'function') {
this.props.wrapperRef(wrapper)
}
}
render() {
const {
position,
wrapperClassName,
popoverClassName,
onMouseEnter,
onMouseLeave,
onClick,
trigger,
content,
} = this.props
const popoverClass = position ? this._getClassNameForPosition(position) : ''
const popoverContentClass = classNames('reactist_popover__content', popoverClassName)
const wrapperClass = classNames('reactist_popover__wrapper', wrapperClassName)
const triggerElement = React.Children.only<React.ReactElement>(
trigger as React.ReactElement,
)
function handleTriggerClick(event: React.SyntheticEvent) {
// @ts-expect-error This is temporary while we revisit the Popover interface
if (onClick) onClick(event)
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
if (typeof triggerElement.props.onClick === 'function') {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access,@typescript-eslint/no-unsafe-call
triggerElement.props.onClick(event)
}
}
return (
<span
className={wrapperClass}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
ref={this._updateWrapperRef}
>
{React.cloneElement(triggerElement, { onClick: handleTriggerClick })}
<span className={popoverClass} ref={this._updatePopoverRef}>
{this.props.visible ? (
<span className={popoverContentClass}>
{typeof content === 'function' ? content() : content}
</span>
) : null}
</span>
</span>
)
}
}
Popover.displayName = 'Popover'
Popover.defaultProps = {
position: 'auto',
gapSize: 5, // default size of the arrow (see `tooltip.less`)
}
export { Popover } | the_stack |
import { Percent, Price, Scalar, scalar, Shares, Tokens } from "./dimension-quantity";
// This library is intended to be a home for all augur financial formulas.
// The emphasis is on safety and education with mechanisms like more specific
// types (eg. Shares instead of BigNumber), named parameters/return values
// (eg. returning a TradeQuantityOpened instead of Shares), and highly
// structured nouns (eg. passing around a RealizedProfit instead of Tokens).
// The documentation is centered around the types, the idea
// being that financial formuals are mostly self-documenting
// given time spent understanding the input and output types.
// The docs below describe many values as being in the context of one market
// outcome. Usually this is highest resolution / most specific data available-- eg.
// we have a user's TotalCost computed for a categorical outcome A, and a different
// TotalCost for outcome B. But, TotalCost and other values can also be expressed as
// rollups/aggregations, for example TotalCost of a user's entire Augur portfolio.
// PositionType is the type of a user's investment position in an Augur market.
// A position is scoped to one market outcome. For example in a categorical
// market if a user bought shares of A and later bought shares of B, these
// are two distinct positions. A position is said to be "closed" if the user
// has no shares in that outcome. A position is said to be "long" ("short") if
// the user earns money when the price of an outcome's shares goes up (down).
export interface PositionType {
positionType: "closed" | "long" | "short";
}
// NetPosition is the number of shares a user currently owns in a market
// outcome. If NetPosition is positive (negative), the user has a "long"
// ("short") position and earns money if the price goes up (down). If NetPosition
// is zero the position is said to be "closed". In the context of a trade,
// NetPosition is prior to the trade being processed, see NextNetPosition.
export interface NetPosition {
netPosition: Shares;
}
// NextNetPosition is, in the context of a trade, a user's NetPosition after
// processing that trade. NetPosition is prior to the trade being processed.
export interface NextNetPosition {
nextNetPosition: Shares;
}
// AverageTradePriceMinusMinPriceForOpenPosition is the average
// per-share trade price at which the user opened their position. For
// technical reasons this average includes subtraction of MarketMinPrice
// (ie. an average of TradePriceMinusMinPrice, not TradePrice). This
// is a _trade price_ average, not to be confused with SharePrice.
export interface AverageTradePriceMinusMinPriceForOpenPosition {
averageTradePriceMinusMinPriceForOpenPosition: Price;
}
// NextAverageTradePriceMinusMinPriceForOpenPosition is, in the context of
// a trade, a user's AverageTradePriceMinusMinPriceForOpenPosition after
// processing that trade. AverageTradePriceMinusMinPriceForOpenPosition
// is prior to the trade being processed.
export interface NextAverageTradePriceMinusMinPriceForOpenPosition {
nextAverageTradePriceMinusMinPriceForOpenPosition: Price;
}
// UnrealizedCost is the amount of tokens a user paid to open their current
// NetPosition in that market outcome. NB UnrealizedCost is a cashflow amount that
// the user remitted based on SharePrice not TradePrice. For example if you open
// a short position for one share in a binary market at a trade price of 0.2, then
// your UnrealizedCost is `MarketMaxPrice=1.0 - TradePrice=0.2 --> SharePrice=0.8
// * 1 share --> UnrealizedCost=0.8``. NB also that in categorical markets the
// user may pay shares of other outcomes in lieu of tokens, which doesn't change
// the calculation for UnrealizedCost, but it does mean that (in a categorical
// market) UnrealizedCost may be greater than the actual tokens a user remitted.
export interface UnrealizedCost {
unrealizedCost: Tokens;
}
// UnrealizedRevenue is the amount of tokens a user would receive for
// their current NetPosition if they were to close that position at the
// last price for that market outcome. The last price is the most recent
// price paid by anyone trading on that outcome. For example if a user has
// a long position of 10 shares in a binary market, and the last price is
// 0.75, then `NetPosition=10 * LastPrice=0.75 --> UnrealizedRevenue=7.5`.
export interface UnrealizedRevenue {
unrealizedRevenue: Tokens;
}
// UnrealizedProfit is the profit a user would make on just their current
// NetPosition if they were to close it at the last price for that market
// outcome. The last price is the most recent price paid by anyone trading on
// that outcome. UnrealizedProfit is UnrealizedRevenue minus UnrealizedCost.
export interface UnrealizedProfit {
unrealizedProfit: Tokens;
}
// UnrealizedProfitPercent is the percent profit a user would have on just their
// current NetPosition if they were to close it at the last price for that market
// outcome. The last price is the most recent price paid by anyone trading on that
// outcome. UnrealizedProfitPercent is UnrealizedProfit divided by UnrealizedCost.
export interface UnrealizedProfitPercent {
unrealizedProfitPercent: Percent;
}
// RealizedCost is the amount of tokens a user paid for the total historical cost
// to open all positions which have _since been closed_ for that market outcome. Ie.
// RealizedCost is accrued cost for shares a user previously owned. NB RealizedCost
// is a cashflow amount that the user remitted based on SharePrice not TradePrice.
// For example if you open a short position for one share in a binary market at
// a trade price of 0.2, and then close that position so the cost is realized,
// your RealizedCost is `MarketMaxPrice=1.0 - TradePrice=0.2 --> SharePrice=0.8
// * 1 share --> RealizedCost=0.8`. NB also that in categorical markets the
// user may pay shares of other outcomes in lieu of tokens, which doesn't change
// the calculation for RealizedCost, but it does mean that (in a categorical
// market) RealizedCost may be greater than the actual tokens a user remitted.
export interface RealizedCost {
realizedCost: Tokens;
}
// NextRealizedCost is, in the context of a trade, a user's RealizedCost after
// processing that trade. RealizedCost is prior to the trade being processed.
export interface NextRealizedCost {
nextRealizedCost: Tokens;
}
// RealizedProfit is the profit a user made for total historical
// positions which have _since been closed_ in a market outcome. Ie.
// RealizedProfit is accrued profit for shares a user previously owned.
export interface RealizedProfit {
realizedProfit: Tokens;
}
// NextRealizedProfit is, in the context of a trade, a user's RealizedProfit after
// processing that trade. RealizedProfit is prior to the trade being processed.
export interface NextRealizedProfit {
nextRealizedProfit: Tokens;
}
// RealizedProfitPercent is the percent profit a user made for total
// historical positions which have _since been closed_ in a market outcome. Ie.
// RealizedProfitPercent is accrued profit percent for shares a user previously
// owned. RealizedProfitPercent is RealizedProfit divided by RealizedCost.
export interface RealizedProfitPercent {
realizedProfitPercent: Percent;
}
// TotalCost is UnrealizedCost plus RealizedCost. Ie. TotalCost is
// the cashflow amount the user remitted, based on SharePrice not
// TradePrice, for all shares they ever bought in this market outcome.
export interface TotalCost {
totalCost: Tokens;
}
// TotalProfit is UnrealizedProfit plus RealizedProfit. Ie. TotalProfit is the
// profit a user made on previously owned shares in a market outcome, plus what
// they could make if they closed their current NetPosition in that outcome.
export interface TotalProfit {
totalProfit: Tokens;
}
// TotalProfitPercent is TotalProfit divided by TotalCost. Ie.
// TotalProfitPercent is the total/final percent profit a user
// would make if they closed their NetPosition at the LastPrice.
// In other words, TotalProfitPercent is what RealizedProfitPercent
// _would become_ if the user closed their NetPosition at LastPrice.
export interface TotalProfitPercent {
totalProfitPercent: Percent;
}
// TradePositionDelta is the increase or decrease to a user's NetPosition
// as the result of processing a trade. For example if a user's
// NetPosition=5 and TradePositionDelta=-2, then this trade is partially
// closing their long position with a trade quantity of 2. A positive
// (negative) tradePositionDelta corresponds to a buy (sell) trade.
export interface TradePositionDelta {
tradePositionDelta: Shares;
}
// TradeCost is the cost basis for one trade, ie. the amount of tokens a
// user paid to execute that trade on a market outcome, excluding fees (see
// TradeCostIncludingFees). TradeCost is a cashflow amount the user remitted
// based on SharePrice not TradePrice. For example if you execute a sell
// trade for one share in a binary market at a trade price of 0.2, then your
// TradeCost is `MarketMaxPrice=1.0 - TradePrice=0.2 --> SharePrice=0.8 * 1
// share --> TradeCost=0.8``. NB also that in categorical markets the user
// may pay shares of other outcomes in lieu of tokens, which doesn't change
// the calculation for TradeCost, but it does mean that (in a categorical
// market) TradeCost may be greater than the actual tokens a user remitted.
export interface TradeCost {
tradeCost: Tokens;
}
// TradeCostIncludingFees is TradeCost plus TotalFees for that trade.
export interface TradeCostIncludingFees {
tradeCostIncludingFees: Tokens;
}
// TradeBuyOrSell represents the type of a trade being either a "buy" trade
// or a "sell" trade, from the perspective of this user. Each trade has
// a counterparty that sees this trade as the opposite type, ie. if you
// and I do a trade, and my trade is a "buy", then your trade is a "sell".
export interface TradeBuyOrSell {
tradeBuyOrSell: "buy" | "sell";
}
// TradeQuantity is the number of shares bought or sold in one trade.
// TradeQuantity is context-free: it doesn't know if this trade was a
// buy/sell trade, or if this trade opened/closed/reversed a user's position.
export interface TradeQuantity {
tradeQuantity: Shares;
}
// TradeQuantityClosed is portion of a user's NetPosition which was
// closed as the result of processing a trade. For example if a user's
// NetPosition=5 and TradePositionDelta=2, then TradeQuantityClosed=0
// because the user is further opening, not closing their position in
// this trade. If a user's NetPosition=-10 and TradePositionDelta=7, then
// TradeQuantityClosed=7 ie. the user is closing 7 shares this trade.
export interface TradeQuantityClosed {
tradeQuantityClosed: Shares;
}
// TradeQuantityOpened is portion of a user's NetPosition which was
// opened as the result of processing a trade. For example if a user's
// NetPosition=5 and TradePositionDelta=2, then TradeQuantityOpened=2 because
// the user is further opening their position in this trade. If a user's
// NetPosition=-10 and TradePositionDelta=7, then TradeQuantityOpened=0 ie.
// the user is partially closing, not opening, their position in this trade.
export interface TradeQuantityOpened {
tradeQuantityOpened: Shares;
}
// TradeRealizedCostDelta is the change in RealizedCost as a result of processing
// a trade. Ie. NextRealizedCost = TradeRealizedCostDelta + RealizedCost.
export interface TradeRealizedCostDelta {
tradeRealizedCostDelta: Tokens;
}
// TradeRealizedRevenueDelta is the change in RealizedRevenue as a
// result of processing a trade. (At this time RealizedRevenue doesn't
// have its own type, it's built directly into NextRealizedProfit.)
export interface TradeRealizedRevenueDelta {
tradeRealizedRevenueDelta: Tokens;
}
// TradeRealizedProfitDelta is the change in RealizedProfit as a result of processing
// a trade. Ie. NextRealizedProfit = TradeRealizedProfitDelta + RealizedProfit.
export interface TradeRealizedProfitDelta {
tradeRealizedProfitDelta: Tokens;
}
// TradePrice is the price at which a trade executed. A trade is always
// on a single market outcome. TradePrice is the price shown in the UI,
// looking at the order book or historical price chart. NB TradePrice
// is not the cashflow price a user paid/received, that's SharePrice.
export interface TradePrice {
tradePrice: Price;
}
// TradePriceMinusMinPrice equal to TradePrice minus the MarketMinPrice.
// For technical/historical reasons we often pass around and store
// TradePriceMinusMinPrice instead of TradePrice. Eg. in the DB
// wcl_profit_loss_timeseries.price is a TradePriceMinusMinPrice.
export interface TradePriceMinusMinPrice {
tradePriceMinusMinPrice: Price;
}
// SharePrice is the cashflow price a user paid to get or received to
// give shares in a market outcome. SharePrice represents money exchanging
// hands, whereas TradePrice is the price at which the trade executed
// as shown in the UI order book. For example in a scalar market with
// MarketMinPrice=50, maxPrice=250, if a user opened a long position for
// one share at TradePrice=125, we have `TradePrice=125 - MarketMinPrice=50
// --> SharePrice=75`. NB in categorical markets the user may pay shares of
// other outcomes in lieu of tokens, which doesn't change the calculation for
// SharePrice, but it does mean that (in a categorical market) the user may
// pay shares of other outcomes instead of tokens when satisfying SharePrice.
export interface SharePrice {
sharePrice: Price;
}
// LastTradePriceMinusMinPrice is the TradePriceMinusMinPrice for the most recent
// trade (made by anyone) on that market outcome. LastTradePriceMinusMinPrice--
// also known as the "last price"-- is used to calculate UnrealizedRevenue.
export interface LastTradePriceMinusMinPrice {
lastTradePriceMinusMinPrice: Price;
}
// MarketMinPrice is a market's minimum TradePrice. In
// DB markets.minPrice. MarketMinPrice is necessary in
// general to convert between TradePrice and SharePrice.
export interface MarketMinPrice {
marketMinPrice: Price;
}
// MarketMaxPrice is a market's maximum TradePrice. In
// DB markets.maxPrice. MarketMaxPrice is necessary in
// general to convert between TradePrice and SharePrice.
export interface MarketMaxPrice {
marketMaxPrice: Price;
}
// ReporterFees are fees paid by a user to Augur Reporters based on the
// universe-wide variable reporter fee rate. ReporterFees is within some context,
// eg. reporter fees for one trade or all reporter fees ever paid by a user.
export interface ReporterFees {
reporterFees: Tokens;
}
// MarketCreatorFees are fees paid by a user to the creator of a
// market based on the market creator fee rate set by that creator.
// MarketCreatorFees is within some context, eg. market creator fees
// for one trade or all market creator fees ever paid by a user.
export interface MarketCreatorFees {
marketCreatorFees: Tokens;
}
// TotalFees is ReporterFees plus MarketCreatorFees.
export interface TotalFees {
totalFees: Tokens;
}
// ReporterFeeRate is the universe-wide variable reporter fee rate
// that yields ReporterFees. ReporterFeeRate is expressed as percent
// of Tokens released from escrow when complete sets are destroyed.
export interface ReporterFeeRate {
reporterFeeRate: Percent;
}
// MarketCreatorFeeRate is the market-specific fee rate set by the market
// creator that yields MarketCreatorFees. MarketCreatorFeeRate is expressed as
// a percent of Tokens released from escrow when complete sets are destroyed.
export interface MarketCreatorFeeRate {
marketCreatorFeeRate: Percent;
}
// TotalFeeRate is ReporterFeeRate plus MarketCreatorFeeRate.
export interface TotalFeeRate {
totalFeeRate: Percent;
}
// DisplayRange is the range in which a market's shares may be
// priced. DisplayRange is MarketMaxPrice minus MarketMinPrice.
// DisplayRange is also the number of Tokens for which a complete
// set of shares may be redeemed or purchased from the Augur system.
export interface DisplayRange {
displayRange: Price;
}
export function getPositionType(params: NetPosition): PositionType {
if (params.netPosition.isZero()) {
return {
positionType: "closed",
};
}
if (params.netPosition.sign === -1) {
return {
positionType: "short",
};
}
return {
positionType: "long",
};
}
export function getTradePrice(params: MarketMinPrice & TradePriceMinusMinPrice): TradePrice {
return {
tradePrice: params.marketMinPrice.plus(params.tradePriceMinusMinPrice),
};
}
export function getTradePriceMinusMinPrice(params: MarketMinPrice & TradePrice): TradePriceMinusMinPrice {
return {
tradePriceMinusMinPrice: params.tradePrice.minus(params.marketMinPrice),
};
}
export function getSharePrice(params: MarketMinPrice & MarketMaxPrice & PositionType & (TradePriceMinusMinPrice | TradePrice)): SharePrice {
// For example, in a scalar market with marketMinPrice=20, marketMaxPrice=25,
// and tradePrice=22, the sharePrice for a long position is 2 Tokens/Share
// (ie. tradePrice-marketMinPrice = 22-20 = 2), and for a short position
// is 3 Tokens/Share (ie. marketMaxPrice-tradePrice = 25-22 = 3)
switch (params.positionType) {
case "closed":
return { sharePrice: Price.ZERO };
case "short":
return {
sharePrice: params.marketMaxPrice.minus("tradePrice" in params ?
params.tradePrice :
getTradePrice(params).tradePrice),
};
case "long":
return {
sharePrice: "tradePriceMinusMinPrice" in params ?
params.tradePriceMinusMinPrice :
getTradePriceMinusMinPrice(params).tradePriceMinusMinPrice,
};
}
}
export function getSharePriceForPosition(params: MarketMinPrice & MarketMaxPrice & NetPosition & TradePriceMinusMinPrice): SharePrice {
return getSharePrice({
...params,
...getPositionType(params),
});
}
export function getNextNetPosition(params: NetPosition & TradePositionDelta): NextNetPosition {
return {
nextNetPosition: params.netPosition.plus(params.tradePositionDelta),
};
}
export function getNextAverageTradePriceMinusMinPriceForOpenPosition(params: NetPosition & AverageTradePriceMinusMinPriceForOpenPosition & TradePositionDelta & TradePriceMinusMinPrice): NextAverageTradePriceMinusMinPriceForOpenPosition {
const { nextNetPosition } = getNextNetPosition(params);
if (nextNetPosition.isZero()) {
// this trade closed the user's position
return { nextAverageTradePriceMinusMinPriceForOpenPosition: Price.ZERO };
} else if (nextNetPosition.sign !== params.netPosition.sign) {
// this trade reversed the user's position (from a short to long or vice versa)
return { nextAverageTradePriceMinusMinPriceForOpenPosition: params.tradePriceMinusMinPrice };
}
const { tradeQuantityOpened } = getTradeQuantityOpened(params);
if (tradeQuantityOpened.isZero()) {
return { nextAverageTradePriceMinusMinPriceForOpenPosition: params.averageTradePriceMinusMinPriceForOpenPosition };
}
// invariant: tradeQuantityOpened == tradePositionDelta, ie. position opened further.
// this is a weighted average:
return {
nextAverageTradePriceMinusMinPriceForOpenPosition: (
(params.netPosition.abs()
.multipliedBy(params.averageTradePriceMinusMinPriceForOpenPosition))
.plus(params.tradePositionDelta.abs().multipliedBy(params.tradePriceMinusMinPrice))
).dividedBy(nextNetPosition.abs()).expect(Price),
};
}
export function getTradeQuantityClosed(params: NetPosition & TradePositionDelta): TradeQuantityClosed {
if (params.tradePositionDelta.isZero() ||
params.tradePositionDelta.sign === params.netPosition.sign) {
return { tradeQuantityClosed: Shares.ZERO };
}
return { tradeQuantityClosed: params.netPosition.abs().min(params.tradePositionDelta.abs()) };
}
export function getTradeQuantityOpened(params: NetPosition & TradePositionDelta): TradeQuantityOpened {
if (params.tradePositionDelta.isZero()) {
return { tradeQuantityOpened: Shares.ZERO };
} else if (params.tradePositionDelta.sign === params.netPosition.sign) {
return { tradeQuantityOpened: params.tradePositionDelta.abs() }; // position opened further
} else if (params.tradePositionDelta.abs().gt(params.netPosition.abs())) {
return { tradeQuantityOpened: params.tradePositionDelta.plus(params.netPosition).abs() }; // position reversed
}
return { tradeQuantityOpened: Shares.ZERO }; // position partially or fully closed
}
export function getTradeRealizedCostDelta(params: MarketMinPrice & MarketMaxPrice & NetPosition & TradePositionDelta & AverageTradePriceMinusMinPriceForOpenPosition): TradeRealizedCostDelta {
const { sharePrice } = getSharePriceForPosition({
...params,
// the user has closed `tradeQuantityClosed` number of shares at some
// price X; this function doesn't care about price X; we are computing
// _cost_, which is what the user previously paid to open this position,
// that's why we use averageTradePriceMinusMinPriceForOpenPosition.
tradePriceMinusMinPrice: params.averageTradePriceMinusMinPriceForOpenPosition,
});
const { tradeQuantityClosed } = getTradeQuantityClosed(params);
return {
tradeRealizedCostDelta: sharePrice.multipliedBy(tradeQuantityClosed).expect(Tokens),
};
}
export function getNextRealizedCost(params: MarketMinPrice & MarketMaxPrice & RealizedCost & NetPosition & TradePositionDelta & AverageTradePriceMinusMinPriceForOpenPosition): NextRealizedCost {
const { tradeRealizedCostDelta } = getTradeRealizedCostDelta(params);
return {
nextRealizedCost: params.realizedCost.plus(tradeRealizedCostDelta),
};
}
export function getTradeRealizedRevenueDelta(params: MarketMinPrice & MarketMaxPrice & NetPosition & TradePositionDelta & TradePriceMinusMinPrice): TradeRealizedRevenueDelta {
const { sharePrice } = getSharePriceForPosition(params);
const { tradeQuantityClosed } = getTradeQuantityClosed(params);
return {
tradeRealizedRevenueDelta: sharePrice.multipliedBy(tradeQuantityClosed).expect(Tokens),
};
}
export function getTradeRealizedProfitDelta(params: MarketMinPrice & MarketMaxPrice & NetPosition & TradePositionDelta & AverageTradePriceMinusMinPriceForOpenPosition & TradePriceMinusMinPrice): TradeRealizedProfitDelta {
const { tradeRealizedRevenueDelta } = getTradeRealizedRevenueDelta(params);
const { tradeRealizedCostDelta } = getTradeRealizedCostDelta(params);
return {
tradeRealizedProfitDelta: tradeRealizedRevenueDelta.minus(tradeRealizedCostDelta),
};
}
export function getNextRealizedProfit(params: RealizedProfit & MarketMinPrice & MarketMaxPrice & NetPosition & TradePositionDelta & AverageTradePriceMinusMinPriceForOpenPosition & TradePriceMinusMinPrice): NextRealizedProfit {
const { tradeRealizedProfitDelta } = getTradeRealizedProfitDelta(params);
return {
nextRealizedProfit: params.realizedProfit.plus(tradeRealizedProfitDelta),
};
}
export function getRealizedProfitPercent(params: RealizedCost & RealizedProfit): RealizedProfitPercent {
if (params.realizedCost.isZero()) {
// user spent nothing and so can't have a percent profit on
// nothing; we might consider realizedProfitPercent to be
// undefined, but instead we return zero for convenience.
return { realizedProfitPercent: Percent.ZERO };
}
return {
realizedProfitPercent: params.realizedProfit.dividedBy(params.realizedCost).expect(Percent),
};
}
export function getTradePositionDelta(params: TradeBuyOrSell & TradeQuantity): TradePositionDelta {
return {
tradePositionDelta: params.tradeBuyOrSell === "buy" ? params.tradeQuantity
: params.tradeQuantity.negated(),
};
}
export function getTradeCost(params: MarketMinPrice & MarketMaxPrice & TradePrice & (TradePositionDelta | (TradeBuyOrSell & TradeQuantity))): TradeCost {
// Compute TradeCost by constructing a position comprised of only this trade
const { tradePositionDelta } = "tradePositionDelta" in params ? params : getTradePositionDelta(params);
const { unrealizedCost } = getUnrealizedCost({
...params,
netPosition: tradePositionDelta,
averageTradePriceMinusMinPriceForOpenPosition: getTradePriceMinusMinPrice(params).tradePriceMinusMinPrice,
});
return {
tradeCost: unrealizedCost,
};
}
export function getTradeCostIncludingFees(params: MarketMinPrice & MarketMaxPrice & TradePrice & TradePositionDelta & ReporterFees & MarketCreatorFees): TradeCostIncludingFees {
return {
tradeCostIncludingFees: getTradeCost(params).tradeCost
.plus(getTotalFees(params).totalFees),
};
}
export function getUnrealizedCost(params: MarketMinPrice & MarketMaxPrice & NetPosition & AverageTradePriceMinusMinPriceForOpenPosition): UnrealizedCost {
const { sharePrice } = getSharePriceForPosition({
...params,
// user has an open position; we are computing _cost_, which is
// what the user previously paid to open this position, that's
// why we use averageTradePriceMinusMinPriceForOpenPosition.
tradePriceMinusMinPrice: params.averageTradePriceMinusMinPriceForOpenPosition,
});
return {
unrealizedCost: sharePrice.multipliedBy(params.netPosition.abs()).expect(Tokens),
};
}
export function getUnrealizedRevenue(params: MarketMinPrice & MarketMaxPrice & NetPosition & LastTradePriceMinusMinPrice): UnrealizedRevenue {
const { sharePrice } = getSharePriceForPosition({
...params,
// user has an open position; we are computing potential revenue user would get
// if they fully closed the position at LastPrice, that's why we use LastPrice.
tradePriceMinusMinPrice: params.lastTradePriceMinusMinPrice,
});
return {
unrealizedRevenue: sharePrice.multipliedBy(params.netPosition.abs()).expect(Tokens),
};
}
export function getUnrealizedProfit(params: MarketMinPrice & MarketMaxPrice & NetPosition & AverageTradePriceMinusMinPriceForOpenPosition & LastTradePriceMinusMinPrice): UnrealizedProfit {
const { unrealizedRevenue } = getUnrealizedRevenue(params);
const { unrealizedCost } = getUnrealizedCost(params);
return {
unrealizedProfit: unrealizedRevenue.minus(unrealizedCost),
};
}
// We support passing UnrealizedCost/UnrealizedProfit because some clients
// have these but don't have other parameters like LastTradePriceMinusMinPrice.
export function getUnrealizedProfitPercent(params:
(MarketMinPrice & MarketMaxPrice & NetPosition & AverageTradePriceMinusMinPriceForOpenPosition & LastTradePriceMinusMinPrice)
| (UnrealizedCost & UnrealizedProfit)): UnrealizedProfitPercent {
const { unrealizedCost } = "unrealizedCost" in params ? params : getUnrealizedCost(params);
if (unrealizedCost.isZero()) {
// user spent nothing and so can't have a percent profit on
// nothing; we might consider unrealizedProfitPercent to be
// undefined, but instead we return zero for convenience.
return { unrealizedProfitPercent: Percent.ZERO };
}
const { unrealizedProfit } = "unrealizedProfit" in params ? params : getUnrealizedProfit(params);
return {
unrealizedProfitPercent: unrealizedProfit.dividedBy(unrealizedCost).expect(Percent),
};
}
export function getTotalCost(params: MarketMinPrice & MarketMaxPrice & NetPosition & AverageTradePriceMinusMinPriceForOpenPosition & RealizedCost): TotalCost {
const { unrealizedCost } = getUnrealizedCost(params);
return {
totalCost: unrealizedCost.plus(params.realizedCost),
};
}
export function getTotalProfit(params: MarketMinPrice & MarketMaxPrice & NetPosition & AverageTradePriceMinusMinPriceForOpenPosition & LastTradePriceMinusMinPrice & RealizedProfit): TotalProfit {
const { unrealizedProfit } = getUnrealizedProfit(params);
return {
totalProfit: unrealizedProfit.plus(params.realizedProfit),
};
}
// We support passing TotalCost/TotalProfit because some clients have
// these but don't have other parameters like LastTradePriceMinusMinPrice.
export function getTotalProfitPercent(params:
(MarketMinPrice & MarketMaxPrice & NetPosition & AverageTradePriceMinusMinPriceForOpenPosition & LastTradePriceMinusMinPrice & RealizedCost & RealizedProfit)
| (TotalCost & TotalProfit)): TotalProfitPercent {
const { totalCost } = "totalCost" in params ? params : getTotalCost(params);
if (totalCost.isZero()) {
// user spent nothing and so can't have a percent profit on
// nothing; we might consider totalProfitPercent to be
// undefined, but instead we return zero for convenience.
return { totalProfitPercent: Percent.ZERO };
}
const { totalProfit } = "totalProfit" in params ? params : getTotalProfit(params);
return { totalProfitPercent: totalProfit.dividedBy(totalCost).expect(Percent) };
}
export function getTotalFees(params: ReporterFees & MarketCreatorFees): TotalFees {
return {
totalFees: params.reporterFees.plus(params.marketCreatorFees),
};
}
export function getTotalFeeRate(params: ReporterFeeRate & MarketCreatorFeeRate): TotalFeeRate {
return {
totalFeeRate: params.reporterFeeRate.plus(params.marketCreatorFeeRate),
};
}
export function getDisplayRange(params: MarketMinPrice & MarketMaxPrice): DisplayRange {
return {
displayRange: params.marketMaxPrice.minus(params.marketMinPrice),
};
}
// continuousCompound applies continuously compounding interest to
// the passed amount. The passed interestRate and compoundingDuration
// must use same time unit, eg. annual rate and duration in years.
export function continuousCompound(params: {
amount: Tokens,
interestRate: Percent,
compoundingDuration: Scalar,
}): Tokens {
return params.amount.multipliedBy(scalar(Math.exp(
params.interestRate.multipliedBy(params.compoundingDuration).toNumber())));
} | the_stack |
import {Request} from '../lib/request';
import {Response} from '../lib/response';
import {AWSError} from '../lib/error';
import {PollyCustomizations} from '../lib/services/polly';
import {ServiceConfigurationOptions} from '../lib/service';
import {ConfigBase as Config} from '../lib/config-base';
import {Presigner as presigner} from '../lib/polly/presigner';
import {Readable} from 'stream';
interface Blob {}
declare class Polly extends PollyCustomizations {
/**
* Constructs a service object. This object has one method for each API operation.
*/
constructor(options?: Polly.Types.ClientConfiguration)
config: Config & Polly.Types.ClientConfiguration;
/**
* Deletes the specified pronunciation lexicon stored in an Amazon Web Services Region. A lexicon which has been deleted is not available for speech synthesis, nor is it possible to retrieve it using either the GetLexicon or ListLexicon APIs. For more information, see Managing Lexicons.
*/
deleteLexicon(params: Polly.Types.DeleteLexiconInput, callback?: (err: AWSError, data: Polly.Types.DeleteLexiconOutput) => void): Request<Polly.Types.DeleteLexiconOutput, AWSError>;
/**
* Deletes the specified pronunciation lexicon stored in an Amazon Web Services Region. A lexicon which has been deleted is not available for speech synthesis, nor is it possible to retrieve it using either the GetLexicon or ListLexicon APIs. For more information, see Managing Lexicons.
*/
deleteLexicon(callback?: (err: AWSError, data: Polly.Types.DeleteLexiconOutput) => void): Request<Polly.Types.DeleteLexiconOutput, AWSError>;
/**
* Returns the list of voices that are available for use when requesting speech synthesis. Each voice speaks a specified language, is either male or female, and is identified by an ID, which is the ASCII version of the voice name. When synthesizing speech ( SynthesizeSpeech ), you provide the voice ID for the voice you want from the list of voices returned by DescribeVoices. For example, you want your news reader application to read news in a specific language, but giving a user the option to choose the voice. Using the DescribeVoices operation you can provide the user with a list of available voices to select from. You can optionally specify a language code to filter the available voices. For example, if you specify en-US, the operation returns a list of all available US English voices. This operation requires permissions to perform the polly:DescribeVoices action.
*/
describeVoices(params: Polly.Types.DescribeVoicesInput, callback?: (err: AWSError, data: Polly.Types.DescribeVoicesOutput) => void): Request<Polly.Types.DescribeVoicesOutput, AWSError>;
/**
* Returns the list of voices that are available for use when requesting speech synthesis. Each voice speaks a specified language, is either male or female, and is identified by an ID, which is the ASCII version of the voice name. When synthesizing speech ( SynthesizeSpeech ), you provide the voice ID for the voice you want from the list of voices returned by DescribeVoices. For example, you want your news reader application to read news in a specific language, but giving a user the option to choose the voice. Using the DescribeVoices operation you can provide the user with a list of available voices to select from. You can optionally specify a language code to filter the available voices. For example, if you specify en-US, the operation returns a list of all available US English voices. This operation requires permissions to perform the polly:DescribeVoices action.
*/
describeVoices(callback?: (err: AWSError, data: Polly.Types.DescribeVoicesOutput) => void): Request<Polly.Types.DescribeVoicesOutput, AWSError>;
/**
* Returns the content of the specified pronunciation lexicon stored in an Amazon Web Services Region. For more information, see Managing Lexicons.
*/
getLexicon(params: Polly.Types.GetLexiconInput, callback?: (err: AWSError, data: Polly.Types.GetLexiconOutput) => void): Request<Polly.Types.GetLexiconOutput, AWSError>;
/**
* Returns the content of the specified pronunciation lexicon stored in an Amazon Web Services Region. For more information, see Managing Lexicons.
*/
getLexicon(callback?: (err: AWSError, data: Polly.Types.GetLexiconOutput) => void): Request<Polly.Types.GetLexiconOutput, AWSError>;
/**
* Retrieves a specific SpeechSynthesisTask object based on its TaskID. This object contains information about the given speech synthesis task, including the status of the task, and a link to the S3 bucket containing the output of the task.
*/
getSpeechSynthesisTask(params: Polly.Types.GetSpeechSynthesisTaskInput, callback?: (err: AWSError, data: Polly.Types.GetSpeechSynthesisTaskOutput) => void): Request<Polly.Types.GetSpeechSynthesisTaskOutput, AWSError>;
/**
* Retrieves a specific SpeechSynthesisTask object based on its TaskID. This object contains information about the given speech synthesis task, including the status of the task, and a link to the S3 bucket containing the output of the task.
*/
getSpeechSynthesisTask(callback?: (err: AWSError, data: Polly.Types.GetSpeechSynthesisTaskOutput) => void): Request<Polly.Types.GetSpeechSynthesisTaskOutput, AWSError>;
/**
* Returns a list of pronunciation lexicons stored in an Amazon Web Services Region. For more information, see Managing Lexicons.
*/
listLexicons(params: Polly.Types.ListLexiconsInput, callback?: (err: AWSError, data: Polly.Types.ListLexiconsOutput) => void): Request<Polly.Types.ListLexiconsOutput, AWSError>;
/**
* Returns a list of pronunciation lexicons stored in an Amazon Web Services Region. For more information, see Managing Lexicons.
*/
listLexicons(callback?: (err: AWSError, data: Polly.Types.ListLexiconsOutput) => void): Request<Polly.Types.ListLexiconsOutput, AWSError>;
/**
* Returns a list of SpeechSynthesisTask objects ordered by their creation date. This operation can filter the tasks by their status, for example, allowing users to list only tasks that are completed.
*/
listSpeechSynthesisTasks(params: Polly.Types.ListSpeechSynthesisTasksInput, callback?: (err: AWSError, data: Polly.Types.ListSpeechSynthesisTasksOutput) => void): Request<Polly.Types.ListSpeechSynthesisTasksOutput, AWSError>;
/**
* Returns a list of SpeechSynthesisTask objects ordered by their creation date. This operation can filter the tasks by their status, for example, allowing users to list only tasks that are completed.
*/
listSpeechSynthesisTasks(callback?: (err: AWSError, data: Polly.Types.ListSpeechSynthesisTasksOutput) => void): Request<Polly.Types.ListSpeechSynthesisTasksOutput, AWSError>;
/**
* Stores a pronunciation lexicon in an Amazon Web Services Region. If a lexicon with the same name already exists in the region, it is overwritten by the new lexicon. Lexicon operations have eventual consistency, therefore, it might take some time before the lexicon is available to the SynthesizeSpeech operation. For more information, see Managing Lexicons.
*/
putLexicon(params: Polly.Types.PutLexiconInput, callback?: (err: AWSError, data: Polly.Types.PutLexiconOutput) => void): Request<Polly.Types.PutLexiconOutput, AWSError>;
/**
* Stores a pronunciation lexicon in an Amazon Web Services Region. If a lexicon with the same name already exists in the region, it is overwritten by the new lexicon. Lexicon operations have eventual consistency, therefore, it might take some time before the lexicon is available to the SynthesizeSpeech operation. For more information, see Managing Lexicons.
*/
putLexicon(callback?: (err: AWSError, data: Polly.Types.PutLexiconOutput) => void): Request<Polly.Types.PutLexiconOutput, AWSError>;
/**
* Allows the creation of an asynchronous synthesis task, by starting a new SpeechSynthesisTask. This operation requires all the standard information needed for speech synthesis, plus the name of an Amazon S3 bucket for the service to store the output of the synthesis task and two optional parameters (OutputS3KeyPrefix and SnsTopicArn). Once the synthesis task is created, this operation will return a SpeechSynthesisTask object, which will include an identifier of this task as well as the current status. The SpeechSynthesisTask object is available for 72 hours after starting the asynchronous synthesis task.
*/
startSpeechSynthesisTask(params: Polly.Types.StartSpeechSynthesisTaskInput, callback?: (err: AWSError, data: Polly.Types.StartSpeechSynthesisTaskOutput) => void): Request<Polly.Types.StartSpeechSynthesisTaskOutput, AWSError>;
/**
* Allows the creation of an asynchronous synthesis task, by starting a new SpeechSynthesisTask. This operation requires all the standard information needed for speech synthesis, plus the name of an Amazon S3 bucket for the service to store the output of the synthesis task and two optional parameters (OutputS3KeyPrefix and SnsTopicArn). Once the synthesis task is created, this operation will return a SpeechSynthesisTask object, which will include an identifier of this task as well as the current status. The SpeechSynthesisTask object is available for 72 hours after starting the asynchronous synthesis task.
*/
startSpeechSynthesisTask(callback?: (err: AWSError, data: Polly.Types.StartSpeechSynthesisTaskOutput) => void): Request<Polly.Types.StartSpeechSynthesisTaskOutput, AWSError>;
/**
* Synthesizes UTF-8 input, plain text or SSML, to a stream of bytes. SSML input must be valid, well-formed SSML. Some alphabets might not be available with all the voices (for example, Cyrillic might not be read at all by English voices) unless phoneme mapping is used. For more information, see How it Works.
*/
synthesizeSpeech(params: Polly.Types.SynthesizeSpeechInput, callback?: (err: AWSError, data: Polly.Types.SynthesizeSpeechOutput) => void): Request<Polly.Types.SynthesizeSpeechOutput, AWSError>;
/**
* Synthesizes UTF-8 input, plain text or SSML, to a stream of bytes. SSML input must be valid, well-formed SSML. Some alphabets might not be available with all the voices (for example, Cyrillic might not be read at all by English voices) unless phoneme mapping is used. For more information, see How it Works.
*/
synthesizeSpeech(callback?: (err: AWSError, data: Polly.Types.SynthesizeSpeechOutput) => void): Request<Polly.Types.SynthesizeSpeechOutput, AWSError>;
}
declare namespace Polly {
export import Presigner = presigner;
}
declare namespace Polly {
export type Alphabet = string;
export type AudioStream = Buffer|Uint8Array|Blob|string|Readable;
export type ContentType = string;
export type DateTime = Date;
export interface DeleteLexiconInput {
/**
* The name of the lexicon to delete. Must be an existing lexicon in the region.
*/
Name: LexiconName;
}
export interface DeleteLexiconOutput {
}
export interface DescribeVoicesInput {
/**
* Specifies the engine (standard or neural) used by Amazon Polly when processing input text for speech synthesis.
*/
Engine?: Engine;
/**
* The language identification tag (ISO 639 code for the language name-ISO 3166 country code) for filtering the list of voices returned. If you don't specify this optional parameter, all available voices are returned.
*/
LanguageCode?: LanguageCode;
/**
* Boolean value indicating whether to return any bilingual voices that use the specified language as an additional language. For instance, if you request all languages that use US English (es-US), and there is an Italian voice that speaks both Italian (it-IT) and US English, that voice will be included if you specify yes but not if you specify no.
*/
IncludeAdditionalLanguageCodes?: IncludeAdditionalLanguageCodes;
/**
* An opaque pagination token returned from the previous DescribeVoices operation. If present, this indicates where to continue the listing.
*/
NextToken?: NextToken;
}
export interface DescribeVoicesOutput {
/**
* A list of voices with their properties.
*/
Voices?: VoiceList;
/**
* The pagination token to use in the next request to continue the listing of voices. NextToken is returned only if the response is truncated.
*/
NextToken?: NextToken;
}
export type Engine = "standard"|"neural"|string;
export type EngineList = Engine[];
export type Gender = "Female"|"Male"|string;
export interface GetLexiconInput {
/**
* Name of the lexicon.
*/
Name: LexiconName;
}
export interface GetLexiconOutput {
/**
* Lexicon object that provides name and the string content of the lexicon.
*/
Lexicon?: Lexicon;
/**
* Metadata of the lexicon, including phonetic alphabetic used, language code, lexicon ARN, number of lexemes defined in the lexicon, and size of lexicon in bytes.
*/
LexiconAttributes?: LexiconAttributes;
}
export interface GetSpeechSynthesisTaskInput {
/**
* The Amazon Polly generated identifier for a speech synthesis task.
*/
TaskId: TaskId;
}
export interface GetSpeechSynthesisTaskOutput {
/**
* SynthesisTask object that provides information from the requested task, including output format, creation time, task status, and so on.
*/
SynthesisTask?: SynthesisTask;
}
export type IncludeAdditionalLanguageCodes = boolean;
export type LanguageCode = "arb"|"cmn-CN"|"cy-GB"|"da-DK"|"de-DE"|"en-AU"|"en-GB"|"en-GB-WLS"|"en-IN"|"en-US"|"es-ES"|"es-MX"|"es-US"|"fr-CA"|"fr-FR"|"is-IS"|"it-IT"|"ja-JP"|"hi-IN"|"ko-KR"|"nb-NO"|"nl-NL"|"pl-PL"|"pt-BR"|"pt-PT"|"ro-RO"|"ru-RU"|"sv-SE"|"tr-TR"|"en-NZ"|"en-ZA"|string;
export type LanguageCodeList = LanguageCode[];
export type LanguageName = string;
export type LastModified = Date;
export type LexemesCount = number;
export interface Lexicon {
/**
* Lexicon content in string format. The content of a lexicon must be in PLS format.
*/
Content?: LexiconContent;
/**
* Name of the lexicon.
*/
Name?: LexiconName;
}
export type LexiconArn = string;
export interface LexiconAttributes {
/**
* Phonetic alphabet used in the lexicon. Valid values are ipa and x-sampa.
*/
Alphabet?: Alphabet;
/**
* Language code that the lexicon applies to. A lexicon with a language code such as "en" would be applied to all English languages (en-GB, en-US, en-AUS, en-WLS, and so on.
*/
LanguageCode?: LanguageCode;
/**
* Date lexicon was last modified (a timestamp value).
*/
LastModified?: LastModified;
/**
* Amazon Resource Name (ARN) of the lexicon.
*/
LexiconArn?: LexiconArn;
/**
* Number of lexemes in the lexicon.
*/
LexemesCount?: LexemesCount;
/**
* Total size of the lexicon, in characters.
*/
Size?: Size;
}
export type LexiconContent = string;
export interface LexiconDescription {
/**
* Name of the lexicon.
*/
Name?: LexiconName;
/**
* Provides lexicon metadata.
*/
Attributes?: LexiconAttributes;
}
export type LexiconDescriptionList = LexiconDescription[];
export type LexiconName = string;
export type LexiconNameList = LexiconName[];
export interface ListLexiconsInput {
/**
* An opaque pagination token returned from previous ListLexicons operation. If present, indicates where to continue the list of lexicons.
*/
NextToken?: NextToken;
}
export interface ListLexiconsOutput {
/**
* A list of lexicon names and attributes.
*/
Lexicons?: LexiconDescriptionList;
/**
* The pagination token to use in the next request to continue the listing of lexicons. NextToken is returned only if the response is truncated.
*/
NextToken?: NextToken;
}
export interface ListSpeechSynthesisTasksInput {
/**
* Maximum number of speech synthesis tasks returned in a List operation.
*/
MaxResults?: MaxResults;
/**
* The pagination token to use in the next request to continue the listing of speech synthesis tasks.
*/
NextToken?: NextToken;
/**
* Status of the speech synthesis tasks returned in a List operation
*/
Status?: TaskStatus;
}
export interface ListSpeechSynthesisTasksOutput {
/**
* An opaque pagination token returned from the previous List operation in this request. If present, this indicates where to continue the listing.
*/
NextToken?: NextToken;
/**
* List of SynthesisTask objects that provides information from the specified task in the list request, including output format, creation time, task status, and so on.
*/
SynthesisTasks?: SynthesisTasks;
}
export type MaxResults = number;
export type NextToken = string;
export type OutputFormat = "json"|"mp3"|"ogg_vorbis"|"pcm"|string;
export type OutputS3BucketName = string;
export type OutputS3KeyPrefix = string;
export type OutputUri = string;
export interface PutLexiconInput {
/**
* Name of the lexicon. The name must follow the regular express format [0-9A-Za-z]{1,20}. That is, the name is a case-sensitive alphanumeric string up to 20 characters long.
*/
Name: LexiconName;
/**
* Content of the PLS lexicon as string data.
*/
Content: LexiconContent;
}
export interface PutLexiconOutput {
}
export type RequestCharacters = number;
export type SampleRate = string;
export type Size = number;
export type SnsTopicArn = string;
export type SpeechMarkType = "sentence"|"ssml"|"viseme"|"word"|string;
export type SpeechMarkTypeList = SpeechMarkType[];
export interface StartSpeechSynthesisTaskInput {
/**
* Specifies the engine (standard or neural) for Amazon Polly to use when processing input text for speech synthesis. Using a voice that is not supported for the engine selected will result in an error.
*/
Engine?: Engine;
/**
* Optional language code for the Speech Synthesis request. This is only necessary if using a bilingual voice, such as Aditi, which can be used for either Indian English (en-IN) or Hindi (hi-IN). If a bilingual voice is used and no language code is specified, Amazon Polly uses the default language of the bilingual voice. The default language for any voice is the one returned by the DescribeVoices operation for the LanguageCode parameter. For example, if no language code is specified, Aditi will use Indian English rather than Hindi.
*/
LanguageCode?: LanguageCode;
/**
* List of one or more pronunciation lexicon names you want the service to apply during synthesis. Lexicons are applied only if the language of the lexicon is the same as the language of the voice.
*/
LexiconNames?: LexiconNameList;
/**
* The format in which the returned output will be encoded. For audio stream, this will be mp3, ogg_vorbis, or pcm. For speech marks, this will be json.
*/
OutputFormat: OutputFormat;
/**
* Amazon S3 bucket name to which the output file will be saved.
*/
OutputS3BucketName: OutputS3BucketName;
/**
* The Amazon S3 key prefix for the output speech file.
*/
OutputS3KeyPrefix?: OutputS3KeyPrefix;
/**
* The audio frequency specified in Hz. The valid values for mp3 and ogg_vorbis are "8000", "16000", "22050", and "24000". The default value for standard voices is "22050". The default value for neural voices is "24000". Valid values for pcm are "8000" and "16000" The default value is "16000".
*/
SampleRate?: SampleRate;
/**
* ARN for the SNS topic optionally used for providing status notification for a speech synthesis task.
*/
SnsTopicArn?: SnsTopicArn;
/**
* The type of speech marks returned for the input text.
*/
SpeechMarkTypes?: SpeechMarkTypeList;
/**
* The input text to synthesize. If you specify ssml as the TextType, follow the SSML format for the input text.
*/
Text: Text;
/**
* Specifies whether the input text is plain text or SSML. The default value is plain text.
*/
TextType?: TextType;
/**
* Voice ID to use for the synthesis.
*/
VoiceId: VoiceId;
}
export interface StartSpeechSynthesisTaskOutput {
/**
* SynthesisTask object that provides information and attributes about a newly submitted speech synthesis task.
*/
SynthesisTask?: SynthesisTask;
}
export interface SynthesisTask {
/**
* Specifies the engine (standard or neural) for Amazon Polly to use when processing input text for speech synthesis. Using a voice that is not supported for the engine selected will result in an error.
*/
Engine?: Engine;
/**
* The Amazon Polly generated identifier for a speech synthesis task.
*/
TaskId?: TaskId;
/**
* Current status of the individual speech synthesis task.
*/
TaskStatus?: TaskStatus;
/**
* Reason for the current status of a specific speech synthesis task, including errors if the task has failed.
*/
TaskStatusReason?: TaskStatusReason;
/**
* Pathway for the output speech file.
*/
OutputUri?: OutputUri;
/**
* Timestamp for the time the synthesis task was started.
*/
CreationTime?: DateTime;
/**
* Number of billable characters synthesized.
*/
RequestCharacters?: RequestCharacters;
/**
* ARN for the SNS topic optionally used for providing status notification for a speech synthesis task.
*/
SnsTopicArn?: SnsTopicArn;
/**
* List of one or more pronunciation lexicon names you want the service to apply during synthesis. Lexicons are applied only if the language of the lexicon is the same as the language of the voice.
*/
LexiconNames?: LexiconNameList;
/**
* The format in which the returned output will be encoded. For audio stream, this will be mp3, ogg_vorbis, or pcm. For speech marks, this will be json.
*/
OutputFormat?: OutputFormat;
/**
* The audio frequency specified in Hz. The valid values for mp3 and ogg_vorbis are "8000", "16000", "22050", and "24000". The default value for standard voices is "22050". The default value for neural voices is "24000". Valid values for pcm are "8000" and "16000" The default value is "16000".
*/
SampleRate?: SampleRate;
/**
* The type of speech marks returned for the input text.
*/
SpeechMarkTypes?: SpeechMarkTypeList;
/**
* Specifies whether the input text is plain text or SSML. The default value is plain text.
*/
TextType?: TextType;
/**
* Voice ID to use for the synthesis.
*/
VoiceId?: VoiceId;
/**
* Optional language code for a synthesis task. This is only necessary if using a bilingual voice, such as Aditi, which can be used for either Indian English (en-IN) or Hindi (hi-IN). If a bilingual voice is used and no language code is specified, Amazon Polly uses the default language of the bilingual voice. The default language for any voice is the one returned by the DescribeVoices operation for the LanguageCode parameter. For example, if no language code is specified, Aditi will use Indian English rather than Hindi.
*/
LanguageCode?: LanguageCode;
}
export type SynthesisTasks = SynthesisTask[];
export interface SynthesizeSpeechInput {
/**
* Specifies the engine (standard or neural) for Amazon Polly to use when processing input text for speech synthesis. For information on Amazon Polly voices and which voices are available in standard-only, NTTS-only, and both standard and NTTS formats, see Available Voices. NTTS-only voices When using NTTS-only voices such as Kevin (en-US), this parameter is required and must be set to neural. If the engine is not specified, or is set to standard, this will result in an error. Type: String Valid Values: standard | neural Required: Yes Standard voices For standard voices, this is not required; the engine parameter defaults to standard. If the engine is not specified, or is set to standard and an NTTS-only voice is selected, this will result in an error.
*/
Engine?: Engine;
/**
* Optional language code for the Synthesize Speech request. This is only necessary if using a bilingual voice, such as Aditi, which can be used for either Indian English (en-IN) or Hindi (hi-IN). If a bilingual voice is used and no language code is specified, Amazon Polly uses the default language of the bilingual voice. The default language for any voice is the one returned by the DescribeVoices operation for the LanguageCode parameter. For example, if no language code is specified, Aditi will use Indian English rather than Hindi.
*/
LanguageCode?: LanguageCode;
/**
* List of one or more pronunciation lexicon names you want the service to apply during synthesis. Lexicons are applied only if the language of the lexicon is the same as the language of the voice. For information about storing lexicons, see PutLexicon.
*/
LexiconNames?: LexiconNameList;
/**
* The format in which the returned output will be encoded. For audio stream, this will be mp3, ogg_vorbis, or pcm. For speech marks, this will be json. When pcm is used, the content returned is audio/pcm in a signed 16-bit, 1 channel (mono), little-endian format.
*/
OutputFormat: OutputFormat;
/**
* The audio frequency specified in Hz. The valid values for mp3 and ogg_vorbis are "8000", "16000", "22050", and "24000". The default value for standard voices is "22050". The default value for neural voices is "24000". Valid values for pcm are "8000" and "16000" The default value is "16000".
*/
SampleRate?: SampleRate;
/**
* The type of speech marks returned for the input text.
*/
SpeechMarkTypes?: SpeechMarkTypeList;
/**
* Input text to synthesize. If you specify ssml as the TextType, follow the SSML format for the input text.
*/
Text: Text;
/**
* Specifies whether the input text is plain text or SSML. The default value is plain text. For more information, see Using SSML.
*/
TextType?: TextType;
/**
* Voice ID to use for the synthesis. You can get a list of available voice IDs by calling the DescribeVoices operation.
*/
VoiceId: VoiceId;
}
export interface SynthesizeSpeechOutput {
/**
* Stream containing the synthesized speech.
*/
AudioStream?: AudioStream;
/**
* Specifies the type audio stream. This should reflect the OutputFormat parameter in your request. If you request mp3 as the OutputFormat, the ContentType returned is audio/mpeg. If you request ogg_vorbis as the OutputFormat, the ContentType returned is audio/ogg. If you request pcm as the OutputFormat, the ContentType returned is audio/pcm in a signed 16-bit, 1 channel (mono), little-endian format. If you request json as the OutputFormat, the ContentType returned is audio/json.
*/
ContentType?: ContentType;
/**
* Number of characters synthesized.
*/
RequestCharacters?: RequestCharacters;
}
export type TaskId = string;
export type TaskStatus = "scheduled"|"inProgress"|"completed"|"failed"|string;
export type TaskStatusReason = string;
export type Text = string;
export type TextType = "ssml"|"text"|string;
export interface Voice {
/**
* Gender of the voice.
*/
Gender?: Gender;
/**
* Amazon Polly assigned voice ID. This is the ID that you specify when calling the SynthesizeSpeech operation.
*/
Id?: VoiceId;
/**
* Language code of the voice.
*/
LanguageCode?: LanguageCode;
/**
* Human readable name of the language in English.
*/
LanguageName?: LanguageName;
/**
* Name of the voice (for example, Salli, Kendra, etc.). This provides a human readable voice name that you might display in your application.
*/
Name?: VoiceName;
/**
* Additional codes for languages available for the specified voice in addition to its default language. For example, the default language for Aditi is Indian English (en-IN) because it was first used for that language. Since Aditi is bilingual and fluent in both Indian English and Hindi, this parameter would show the code hi-IN.
*/
AdditionalLanguageCodes?: LanguageCodeList;
/**
* Specifies which engines (standard or neural) that are supported by a given voice.
*/
SupportedEngines?: EngineList;
}
export type VoiceId = "Aditi"|"Amy"|"Astrid"|"Bianca"|"Brian"|"Camila"|"Carla"|"Carmen"|"Celine"|"Chantal"|"Conchita"|"Cristiano"|"Dora"|"Emma"|"Enrique"|"Ewa"|"Filiz"|"Gabrielle"|"Geraint"|"Giorgio"|"Gwyneth"|"Hans"|"Ines"|"Ivy"|"Jacek"|"Jan"|"Joanna"|"Joey"|"Justin"|"Karl"|"Kendra"|"Kevin"|"Kimberly"|"Lea"|"Liv"|"Lotte"|"Lucia"|"Lupe"|"Mads"|"Maja"|"Marlene"|"Mathieu"|"Matthew"|"Maxim"|"Mia"|"Miguel"|"Mizuki"|"Naja"|"Nicole"|"Olivia"|"Penelope"|"Raveena"|"Ricardo"|"Ruben"|"Russell"|"Salli"|"Seoyeon"|"Takumi"|"Tatyana"|"Vicki"|"Vitoria"|"Zeina"|"Zhiyu"|"Aria"|"Ayanda"|string;
export type VoiceList = Voice[];
export type VoiceName = string;
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
export type apiVersion = "2016-06-10"|"latest"|string;
export interface ClientApiVersions {
/**
* A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version.
*/
apiVersion?: apiVersion;
}
export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions;
/**
* Contains interfaces for use with the Polly client.
*/
export import Types = Polly;
}
export = Polly; | the_stack |
import * as React from "react"
import Downshift from "downshift"
import MenuItem from "@material-ui/core/MenuItem/MenuItem"
import { UiPaper, UiSearch } from "../ui-text-field/ui-text-field"
import { Suggestion, SuggestionSection } from "../../models/typeahead"
import { UiTypeaheadFetcher } from "./ui-typeahead-fetcher"
import { Cell, Grid } from "../ui-grid/ui-grid.component"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faUser, faTimes, faSearch, faCube } from "@fortawesome/free-solid-svg-icons"
import { theme, styled } from "../../theme"
import { EllipsisText, Text } from "../text/text.component"
import { UiHrDense } from "../ui-hr/ui-hr"
import { t } from "i18next"
import { LoadingOutlined } from "@ant-design/icons"
type OnCloseListener = () => void
const PaperContainer: React.ComponentType<any> = styled.div`
position: relative;
`
const SearchIcon: React.ComponentType<any> = styled(FontAwesomeIcon)`
width: 18px;
`
const SearchWrapper: React.ComponentType<any> = styled.div`
position: relative;
`
const RoundedSpinnerCube: React.ComponentType<any> = styled(LoadingOutlined)`
width: 28px !important;
height: 28px !important;
margin-right: auto;
margin-left: auto;
`
const SearchButton: React.ComponentType<any> = styled.div`
position: absolute;
border: none !important;
cursor: pointer;
color: #fff;
border-radius: 0px !important;
padding: 0 6px;
&:disabled {
cursor: inherit;
}
width: fit-content;
top: 19px;
right: 11px;
font-size: 38px;
@media (max-width: 767px) {
top: 12px;
left: 8px;
font-size: 28px;
}
`
const SyntaxBox: React.ComponentType<any> = styled.div`
width: auto;
font-size: 16px;
border-radius: 3px;
padding: 3px 1px;
line-height: 16px;
margin-bottom: 5px;
height: auto;
display: inline-block;
background-color: rgba(101, 101, 111, 0.1);
`
const DeleteIcon: React.ComponentType<any> = styled(FontAwesomeIcon)`
position: absolute;
color: #fff;
&:disabled {
cursor: inherit;
}
&:hover {
cursor: pointer;
}
top: 29px;
right: 70px;
@media (max-width: 767px) {
top: 18px;
right: 15px;
}
`
const ResponsiveContainer: React.ComponentType<any> = styled(Cell)`
@media (max-width: 767px) {
div:nth-child(1n + 4) {
display: none;
}
}
`
interface Props {
placeholder: string
defaultQuery?: string
getItems: (inputValue: string | null) => Promise<SuggestionSection[]>
help?: JSX.Element | string
clickToFollowTypes?: string[]
onSubmit: (query: string) => Promise<any>
}
interface State {
value: string
searching: boolean
}
function renderInput(inputProps: any) {
const { InputProps, ref, ...other } = inputProps
return (
<UiSearch
autoCapitalize="none"
inputRef={ref}
{...InputProps}
{...other}
width="100%"
disableUnderline={true}
/>
)
}
function formatBold(content: string) {
const regex: RegExp = /(\S*:)/g
return (
<EllipsisText whiteSpace="pre-wrap !important" fontFamily="Roboto Condensed" fontSize={[3]}>
{content.split(regex).map((value: string, index: number) => {
if (regex.test(value)) {
return <SyntaxBox key={index}>{value}</SyntaxBox>
}
return value
})}
</EllipsisText>
)
}
function renderSummary(summary: string, accountName: string, isHighlighted: boolean) {
return (
<Text
pt={[2, 0]}
fontSize={[2]}
lineHeight={[2]}
color={isHighlighted ? "white" : theme.colors.grey5}
>
{t(`search.suggestions.summary.${summary}`, { accountName })}
</Text>
)
}
export class UiTypeahead extends React.Component<Props, State> {
suggestions: SuggestionSection[] = []
constructor(props: Props) {
super(props)
this.state = {
value: props.defaultQuery ? props.defaultQuery : "",
searching: false
}
}
componentDidUpdate(prevProps: Props): void {
if (this.props.defaultQuery && this.props.defaultQuery !== prevProps.defaultQuery) {
// eslint-disable-next-line react/no-did-update-set-state
this.setState({
value: this.props.defaultQuery,
searching: false
})
}
}
renderSuggestion(params: {
groupId: string
suggestion: { label: string; summary?: string }
index: number
itemProps: any
highlightedIndex: number | null
selectedItem: string
}) {
const isHighlighted =
params.highlightedIndex !== null ? params.highlightedIndex === params.index : false
const isSelected = (params.selectedItem || "").indexOf(params.suggestion.label) > -1
let icon: any = faSearch
if (params.groupId === "accounts") {
icon = faUser
} else if (params.groupId === "blocks") {
icon = faCube
}
return (
<MenuItem
{...params.itemProps}
key={params.suggestion.label}
selected={isHighlighted}
component="div"
className={params.groupId}
style={{
fontWeight: isSelected ? 600 : 400,
backgroundColor: isHighlighted ? theme.colors.green5 : "white",
color: isHighlighted ? "white" : "black",
height: "auto"
}}
>
<Grid width="100%" gridTemplateColumns={["30px 1fr"]}>
<Cell display="inline-block" mr={[3]}>
<FontAwesomeIcon icon={icon} />
</Cell>
<Cell>{formatBold(params.suggestion.label)}</Cell>
<Cell gridColumn={["2"]}>
{params.suggestion.summary
? renderSummary(params.suggestion.summary, this.state.value, isHighlighted)
: null}
</Cell>
</Grid>
</MenuItem>
)
}
getHighlightedItem(
highlightedIndex: number
): { suggestion: Suggestion | undefined; id: string | undefined } {
let index = 0
let suggestion
let id
this.suggestions.forEach((suggestionGroup: SuggestionSection) => {
suggestionGroup.suggestions.forEach((suggestionRef: Suggestion) => {
if (index === highlightedIndex) {
suggestion = suggestionRef
id = suggestionGroup.id
}
index += 1
})
})
return { suggestion, id }
}
getItemByValue(
selectedItemValue: string
): { suggestion: Suggestion | undefined; id: string | undefined; index: number } {
let suggestion
let id
let index = 0
let i = 0
this.suggestions.forEach((suggestionGroup: SuggestionSection) => {
suggestionGroup.suggestions.forEach((suggestionRef: Suggestion) => {
if (suggestionRef.key === selectedItemValue) {
suggestion = suggestionRef
id = suggestionGroup.id
index = i
}
i += 1
})
})
return { suggestion, id, index }
}
handleStateChange = (changes: any) => {
if (changes.type === Downshift.stateChangeTypes.clickItem) {
// eslint-disable-next-line no-prototype-builtins
const ref = changes.hasOwnProperty("selectedItem")
? this.getItemByValue(changes.selectedItem)
: this.getItemByValue(this.state.value)
if (ref.id && (this.props.clickToFollowTypes || []).includes(ref.id)) {
this.onSubmitInternal(() => {
return undefined
}, ref.index)
} else {
this.setState({ value: changes.selectedItem })
}
}
// eslint-disable-next-line no-prototype-builtins
if (changes.hasOwnProperty("selectedItem")) {
this.setState({ value: changes.selectedItem })
// eslint-disable-next-line no-prototype-builtins
} else if (changes.hasOwnProperty("inputValue")) {
this.setState({ value: changes.inputValue })
}
}
handleKeyDown = (
event: KeyboardEvent,
closeMenu: (cb?: OnCloseListener) => any,
selectHighlightedItem: (params: any, cb: any) => any,
highlightedIndex: number | null
) => {
if (event.keyCode === 13) {
if (highlightedIndex !== null) {
selectHighlightedItem({}, () => {
const ref = this.getHighlightedItem(highlightedIndex)
if (ref.id && (this.props.clickToFollowTypes || []).includes(ref.id)) {
this.onSubmitInternal(closeMenu, highlightedIndex)
}
})
} else {
this.onSubmitInternal(closeMenu, null)
}
}
}
handleInputChange = (event: any) => {
this.setState({ value: event.target.value })
}
resetField = () => {
this.setState({
value: ""
})
}
renderItems(
items: SuggestionSection[],
getItemProps: any,
highlightedIndex: number | null,
selectedItem: any
) {
let totalIndex = 0
return (items || []).map((suggestionGroup: SuggestionSection, index: number) => {
if (suggestionGroup.suggestions && suggestionGroup.suggestions.length > 0) {
let groupItems: any = []
const groupItemsContent = suggestionGroup.suggestions.map((suggestion: Suggestion) => {
const render = this.renderSuggestion({
groupId: suggestionGroup.id,
suggestion,
index: totalIndex,
itemProps: getItemProps({ item: suggestion.label }),
highlightedIndex,
selectedItem
})
totalIndex += 1
return render
})
groupItems = [
...groupItems,
<ResponsiveContainer key={suggestionGroup.id}>{groupItemsContent}</ResponsiveContainer>
]
if (index < items.length - 1) {
groupItems = groupItems.concat([<UiHrDense key={`${index}-separator`} />])
}
return groupItems
}
return null
})
}
onSubmitInternal = (
closeMenu: (cb?: OnCloseListener) => any,
highlightedIndex: number | null
) => {
if (!this.state.searching) {
closeMenu()
let { value } = this.state
let suggestionWithId
if (highlightedIndex !== null) {
suggestionWithId = this.getHighlightedItem(highlightedIndex)
if (suggestionWithId.suggestion) {
value = suggestionWithId.suggestion.label
}
}
this.setState({ value, searching: true }, () => {
this.props.onSubmit(value).then(
() => {
this.setState({ value, searching: false })
},
() => {
this.setState({ value, searching: false })
}
)
})
}
}
renderSearchButton(closeMenu: (cb?: OnCloseListener) => any, highlightedIndex: number | null) {
if (this.state.searching) {
return (
<SearchButton key="1" name="search" disabled={true}>
<RoundedSpinnerCube color="white" fadeIn="none" name="double-bounce" />
</SearchButton>
)
}
return (
<SearchButton
key="2"
onClick={() => this.onSubmitInternal(closeMenu, highlightedIndex)}
name="search"
>
<SearchIcon icon={faSearch} />
</SearchButton>
)
}
renderDeleteIcon() {
return this.state.value && this.state.value.length > 0 ? (
<DeleteIcon onClick={this.resetField} icon={faTimes} size="lg" />
) : null
}
render() {
let popperNode: any
const { value } = this.state
return (
<Downshift selectedItem={value} onStateChange={this.handleStateChange}>
{({
getInputProps,
getMenuProps,
getItemProps,
isOpen,
selectedItem,
inputValue,
highlightedIndex,
selectHighlightedItem,
clearItems,
setItemCount,
getRootProps,
closeMenu,
setHighlightedIndex
}) => (
<SearchWrapper {...getRootProps()}>
{renderInput({
fullWidth: true,
InputProps: getInputProps({
onChange: this.handleInputChange,
onKeyDown: (event: KeyboardEvent) =>
this.handleKeyDown(event, closeMenu, selectHighlightedItem, highlightedIndex),
placeholder: this.props.placeholder
}),
ref: (node: any) => {
popperNode = node
}
})}
{this.renderSearchButton(closeMenu, highlightedIndex)}
{this.renderDeleteIcon()}
<PaperContainer {...getMenuProps()}>
{isOpen ? (
<UiPaper
square={true}
style={{ marginTop: 0, width: popperNode ? popperNode.clientWidth : null }}
>
<UiTypeaheadFetcher
fetchData={this.props.getItems}
searchValue={inputValue}
onLoaded={(suggestions) => {
clearItems()
if (suggestions) {
// @ts-ignore
setHighlightedIndex(null)
setItemCount(
suggestions
.map(
(suggestionGroup: SuggestionSection) =>
suggestionGroup.suggestions.length
)
.reduce((sum: number, current) => sum + current, 0)
)
this.suggestions = suggestions
}
}}
>
{({ loading, suggestions, error }) => {
if (loading) {
return (
<Cell px={[3]} py={[3]}>
<Text fontSize={[3]}>{t("search.loading")}</Text>
</Cell>
)
}
if (error) {
return (
<Cell px={[3]} py={[3]}>
<Text fontSize={[3]}>{t("search.errorFetch")}</Text>
</Cell>
)
}
return this.renderItems(
suggestions,
getItemProps,
highlightedIndex,
selectedItem
)
}}
</UiTypeaheadFetcher>
{this.props.help}
</UiPaper>
) : null}
</PaperContainer>
</SearchWrapper>
)}
</Downshift>
)
}
} | the_stack |
import { MetadataBearer as $MetadataBearer, SmithyException as __SmithyException } from "@aws-sdk/types";
/**
* <p>You don't have sufficient access to perform this action.</p>
*/
export interface AccessDeniedException extends __SmithyException, $MetadataBearer {
name: "AccessDeniedException";
$fault: "client";
message: string | undefined;
}
export namespace AccessDeniedException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: AccessDeniedException): any => ({
...obj,
});
}
export enum AttachmentStatus {
ATTACHED = "ATTACHED",
ATTACHING = "ATTACHING",
DETACHED = "DETACHED",
DETACHING = "DETACHING",
}
export interface CancelTaskInput {
/**
* <p>The ID of the task that you are attempting to cancel. You can retrieve a task ID by using
* the <code>ListTasks</code> operation.</p>
*/
taskId: string | undefined;
}
export namespace CancelTaskInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CancelTaskInput): any => ({
...obj,
});
}
export interface CancelTaskOutput {
/**
* <p>The ID of the task that you are attempting to cancel.</p>
*/
taskId?: string;
}
export namespace CancelTaskOutput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CancelTaskOutput): any => ({
...obj,
});
}
/**
* <p>An unexpected error occurred while processing the request.</p>
*/
export interface InternalServerException extends __SmithyException, $MetadataBearer {
name: "InternalServerException";
$fault: "server";
$retryable: {};
message: string | undefined;
}
export namespace InternalServerException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InternalServerException): any => ({
...obj,
});
}
/**
* <p>The request references a resource that doesn't exist.</p>
*/
export interface ResourceNotFoundException extends __SmithyException, $MetadataBearer {
name: "ResourceNotFoundException";
$fault: "client";
message: string | undefined;
}
export namespace ResourceNotFoundException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ResourceNotFoundException): any => ({
...obj,
});
}
/**
* <p>The request was denied due to request throttling.</p>
*/
export interface ThrottlingException extends __SmithyException, $MetadataBearer {
name: "ThrottlingException";
$fault: "client";
$retryable: {
throttling: true;
};
message: string | undefined;
}
export namespace ThrottlingException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ThrottlingException): any => ({
...obj,
});
}
/**
* <p>The input fails to satisfy the constraints specified by an Amazon Web Services service.</p>
*/
export interface ValidationException extends __SmithyException, $MetadataBearer {
name: "ValidationException";
$fault: "client";
message: string | undefined;
}
export namespace ValidationException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ValidationException): any => ({
...obj,
});
}
/**
* <p>The physical capacity of the Amazon Web Services Snow Family device. </p>
*/
export interface Capacity {
/**
* <p>The name of the type of capacity, such as memory.</p>
*/
name?: string;
/**
* <p>The unit of measure for the type of capacity.</p>
*/
unit?: string;
/**
* <p>The total capacity on the device.</p>
*/
total?: number;
/**
* <p>The amount of capacity used on the device.</p>
*/
used?: number;
/**
* <p>The amount of capacity available for use on the device.</p>
*/
available?: number;
}
export namespace Capacity {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Capacity): any => ({
...obj,
});
}
/**
* <p>A structure used to reboot the device.</p>
*/
export interface Reboot {}
export namespace Reboot {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Reboot): any => ({
...obj,
});
}
/**
* <p>A structure used to unlock a device.</p>
*/
export interface Unlock {}
export namespace Unlock {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Unlock): any => ({
...obj,
});
}
/**
* <p>The command given to the device to execute.</p>
*/
export type Command = Command.RebootMember | Command.UnlockMember | Command.$UnknownMember;
export namespace Command {
/**
* <p>Unlocks the device.</p>
*/
export interface UnlockMember {
unlock: Unlock;
reboot?: never;
$unknown?: never;
}
/**
* <p>Reboots the device.</p>
*/
export interface RebootMember {
unlock?: never;
reboot: Reboot;
$unknown?: never;
}
export interface $UnknownMember {
unlock?: never;
reboot?: never;
$unknown: [string, any];
}
export interface Visitor<T> {
unlock: (value: Unlock) => T;
reboot: (value: Reboot) => T;
_: (name: string, value: any) => T;
}
export const visit = <T>(value: Command, visitor: Visitor<T>): T => {
if (value.unlock !== undefined) return visitor.unlock(value.unlock);
if (value.reboot !== undefined) return visitor.reboot(value.reboot);
return visitor._(value.$unknown[0], value.$unknown[1]);
};
/**
* @internal
*/
export const filterSensitiveLog = (obj: Command): any => {
if (obj.unlock !== undefined) return { unlock: Unlock.filterSensitiveLog(obj.unlock) };
if (obj.reboot !== undefined) return { reboot: Reboot.filterSensitiveLog(obj.reboot) };
if (obj.$unknown !== undefined) return { [obj.$unknown[0]]: "UNKNOWN" };
};
}
/**
* <p>The options for how a device's CPU is configured.</p>
*/
export interface CpuOptions {
/**
* <p>The number of cores that the CPU can use.</p>
*/
coreCount?: number;
/**
* <p>The number of threads per core in the CPU.</p>
*/
threadsPerCore?: number;
}
export namespace CpuOptions {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CpuOptions): any => ({
...obj,
});
}
export interface CreateTaskInput {
/**
* <p>A list of managed device IDs.</p>
*/
targets: string[] | undefined;
/**
* <p>The task to be performed. Only one task is executed on a device at a time.</p>
*/
command: Command | undefined;
/**
* <p>A description of the task and its targets.</p>
*/
description?: string;
/**
* <p>Optional metadata that you assign to a resource. You can use tags to categorize a resource
* in different ways, such as by purpose, owner, or environment. </p>
*/
tags?: { [key: string]: string };
/**
* <p>A token ensuring that the action is called only once with the specified details.</p>
*/
clientToken?: string;
}
export namespace CreateTaskInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateTaskInput): any => ({
...obj,
...(obj.command && { command: Command.filterSensitiveLog(obj.command) }),
});
}
export interface CreateTaskOutput {
/**
* <p>The ID of the task that you created.</p>
*/
taskId?: string;
/**
* <p>The Amazon Resource Name (ARN) of the task that you created.</p>
*/
taskArn?: string;
}
export namespace CreateTaskOutput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: CreateTaskOutput): any => ({
...obj,
});
}
/**
* <p>The request would cause a service quota to be exceeded.</p>
*/
export interface ServiceQuotaExceededException extends __SmithyException, $MetadataBearer {
name: "ServiceQuotaExceededException";
$fault: "client";
message: string | undefined;
}
export namespace ServiceQuotaExceededException {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ServiceQuotaExceededException): any => ({
...obj,
});
}
export interface DescribeDeviceInput {
/**
* <p>The ID of the device that you are checking the information of.</p>
*/
managedDeviceId: string | undefined;
}
export namespace DescribeDeviceInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeDeviceInput): any => ({
...obj,
});
}
export enum UnlockState {
LOCKED = "LOCKED",
UNLOCKED = "UNLOCKED",
UNLOCKING = "UNLOCKING",
}
export enum IpAddressAssignment {
DHCP = "DHCP",
STATIC = "STATIC",
}
export enum PhysicalConnectorType {
QSFP = "QSFP",
RJ45 = "RJ45",
RJ45_2 = "RJ45_2",
SFP_PLUS = "SFP_PLUS",
WIFI = "WIFI",
}
/**
* <p>The details about the physical network interface for the device.</p>
*/
export interface PhysicalNetworkInterface {
/**
* <p>The physical network interface ID.</p>
*/
physicalNetworkInterfaceId?: string;
/**
* <p>The
* physical
* connector type.</p>
*/
physicalConnectorType?: PhysicalConnectorType | string;
/**
* <p>A value that describes whether the IP address is dynamic or persistent.</p>
*/
ipAddressAssignment?: IpAddressAssignment | string;
/**
* <p>The IP address of the device.</p>
*/
ipAddress?: string;
/**
* <p>The netmask used to divide the IP address into subnets.</p>
*/
netmask?: string;
/**
* <p>The default gateway of the device.</p>
*/
defaultGateway?: string;
/**
* <p>The MAC address of the device.</p>
*/
macAddress?: string;
}
export namespace PhysicalNetworkInterface {
/**
* @internal
*/
export const filterSensitiveLog = (obj: PhysicalNetworkInterface): any => ({
...obj,
});
}
/**
* <p>Information about the software on the device.</p>
*/
export interface SoftwareInformation {
/**
* <p>The version of the software currently installed on the device.</p>
*/
installedVersion?: string;
/**
* <p>The version of the software being installed on the device.</p>
*/
installingVersion?: string;
/**
* <p>The state of the software that is installed or that is being installed on the
* device.</p>
*/
installState?: string;
}
export namespace SoftwareInformation {
/**
* @internal
*/
export const filterSensitiveLog = (obj: SoftwareInformation): any => ({
...obj,
});
}
export interface DescribeDeviceOutput {
/**
* <p>When the device last contacted the Amazon Web Services Cloud. Indicates that the device is
* online.</p>
*/
lastReachedOutAt?: Date;
/**
* <p>When the device last pushed an update to the Amazon Web Services Cloud. Indicates when the device cache
* was refreshed.</p>
*/
lastUpdatedAt?: Date;
/**
* <p>Optional metadata that you assign to a resource. You can use tags to categorize a resource
* in different ways, such as by purpose, owner, or environment. </p>
*/
tags?: { [key: string]: string };
/**
* <p>The ID of the device that you checked the information for.</p>
*/
managedDeviceId?: string;
/**
* <p>The Amazon Resource Name (ARN) of the device.</p>
*/
managedDeviceArn?: string;
/**
* <p>The type of Amazon Web Services Snow Family device.</p>
*/
deviceType?: string;
/**
* <p>The ID of the job used when ordering the device.</p>
*/
associatedWithJob?: string;
/**
* <p>The current state of the device.</p>
*/
deviceState?: UnlockState | string;
/**
* <p>The network interfaces available on the device.</p>
*/
physicalNetworkInterfaces?: PhysicalNetworkInterface[];
/**
* <p>The hardware specifications of the device. </p>
*/
deviceCapacities?: Capacity[];
/**
* <p>The software installed on the device.</p>
*/
software?: SoftwareInformation;
}
export namespace DescribeDeviceOutput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeDeviceOutput): any => ({
...obj,
});
}
export interface DescribeDeviceEc2Input {
/**
* <p>The ID of the managed device.</p>
*/
managedDeviceId: string | undefined;
/**
* <p>A list of instance IDs associated with the managed device.</p>
*/
instanceIds: string[] | undefined;
}
export namespace DescribeDeviceEc2Input {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeDeviceEc2Input): any => ({
...obj,
});
}
/**
* <p>Describes a parameter used to set up an Amazon Elastic Block Store (Amazon EBS) volume
* in a block device mapping.</p>
*/
export interface EbsInstanceBlockDevice {
/**
* <p>When the attachment was initiated.</p>
*/
attachTime?: Date;
/**
* <p>A value that indicates whether the volume is deleted on instance termination.</p>
*/
deleteOnTermination?: boolean;
/**
* <p>The attachment state.</p>
*/
status?: AttachmentStatus | string;
/**
* <p>The ID of the Amazon EBS volume.</p>
*/
volumeId?: string;
}
export namespace EbsInstanceBlockDevice {
/**
* @internal
*/
export const filterSensitiveLog = (obj: EbsInstanceBlockDevice): any => ({
...obj,
});
}
/**
* <p>The description of a block device mapping.</p>
*/
export interface InstanceBlockDeviceMapping {
/**
* <p>The block device name.</p>
*/
deviceName?: string;
/**
* <p>The parameters used to automatically set up Amazon Elastic Block Store (Amazon EBS)
* volumes when the instance is launched. </p>
*/
ebs?: EbsInstanceBlockDevice;
}
export namespace InstanceBlockDeviceMapping {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InstanceBlockDeviceMapping): any => ({
...obj,
});
}
/**
* <p>Information about the device's security group.</p>
*/
export interface SecurityGroupIdentifier {
/**
* <p>The security group ID.</p>
*/
groupId?: string;
/**
* <p>The security group name.</p>
*/
groupName?: string;
}
export namespace SecurityGroupIdentifier {
/**
* @internal
*/
export const filterSensitiveLog = (obj: SecurityGroupIdentifier): any => ({
...obj,
});
}
export enum InstanceStateName {
PENDING = "PENDING",
RUNNING = "RUNNING",
SHUTTING_DOWN = "SHUTTING_DOWN",
STOPPED = "STOPPED",
STOPPING = "STOPPING",
TERMINATED = "TERMINATED",
}
/**
* <p>The description of the current state of an instance.</p>
*/
export interface InstanceState {
/**
* <p>The state of the instance as a 16-bit unsigned integer. </p>
* <p>The high byte is all of the bits between 2^8 and (2^16)-1, which equals decimal values
* between 256 and 65,535. These numerical values are used for internal purposes and should be
* ignored. </p>
* <p>The low byte is all of the bits between 2^0 and (2^8)-1, which equals decimal values
* between 0 and 255. </p>
* <p>The valid values for the instance state code are all in the range of the low byte. These
* values are: </p>
* <ul>
* <li>
* <p>
* <code>0</code> : <code>pending</code>
* </p>
* </li>
* <li>
* <p>
* <code>16</code> : <code>running</code>
* </p>
* </li>
* <li>
* <p>
* <code>32</code> : <code>shutting-down</code>
* </p>
* </li>
* <li>
* <p>
* <code>48</code> : <code>terminated</code>
* </p>
* </li>
* <li>
* <p>
* <code>64</code> : <code>stopping</code>
* </p>
* </li>
* <li>
* <p>
* <code>80</code> : <code>stopped</code>
* </p>
* </li>
* </ul>
* <p>You can ignore the high byte value by zeroing out all of the bits above 2^8 or 256 in
* decimal. </p>
*/
code?: number;
/**
* <p>The current
* state
* of the instance.</p>
*/
name?: InstanceStateName | string;
}
export namespace InstanceState {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InstanceState): any => ({
...obj,
});
}
/**
* <p>The description of an
* instance.
* Currently, Amazon EC2 instances are the only supported instance type.</p>
*/
export interface Instance {
/**
* <p>The ID of the AMI used to launch the instance.</p>
*/
imageId?: string;
/**
* <p>The Amazon Machine Image (AMI) launch index, which you can use to find this instance in
* the launch group. </p>
*/
amiLaunchIndex?: number;
/**
* <p>The ID of the instance.</p>
*/
instanceId?: string;
/**
* <p>The description of the current state of an instance.</p>
*/
state?: InstanceState;
/**
* <p>The instance type.</p>
*/
instanceType?: string;
/**
* <p>The private IPv4 address assigned to the instance.</p>
*/
privateIpAddress?: string;
/**
* <p>The public IPv4 address assigned to the instance.</p>
*/
publicIpAddress?: string;
/**
* <p>When the instance was created.</p>
*/
createdAt?: Date;
/**
* <p>When the instance was last updated.</p>
*/
updatedAt?: Date;
/**
* <p>Any block device mapping entries for the instance.</p>
*/
blockDeviceMappings?: InstanceBlockDeviceMapping[];
/**
* <p>The security groups for the instance.</p>
*/
securityGroups?: SecurityGroupIdentifier[];
/**
* <p>The CPU options for the instance.</p>
*/
cpuOptions?: CpuOptions;
/**
* <p>The device name of the root device volume (for example, <code>/dev/sda1</code>). </p>
*/
rootDeviceName?: string;
}
export namespace Instance {
/**
* @internal
*/
export const filterSensitiveLog = (obj: Instance): any => ({
...obj,
});
}
/**
* <p>The details about the instance.</p>
*/
export interface InstanceSummary {
/**
* <p>A structure containing details about the instance.</p>
*/
instance?: Instance;
/**
* <p>When the instance summary was last updated.</p>
*/
lastUpdatedAt?: Date;
}
export namespace InstanceSummary {
/**
* @internal
*/
export const filterSensitiveLog = (obj: InstanceSummary): any => ({
...obj,
});
}
export interface DescribeDeviceEc2Output {
/**
* <p>A list of structures containing information about each instance. </p>
*/
instances?: InstanceSummary[];
}
export namespace DescribeDeviceEc2Output {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeDeviceEc2Output): any => ({
...obj,
});
}
export interface DescribeExecutionInput {
/**
* <p>The ID of the task that the action is describing.</p>
*/
taskId: string | undefined;
/**
* <p>The ID of the managed device.</p>
*/
managedDeviceId: string | undefined;
}
export namespace DescribeExecutionInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeExecutionInput): any => ({
...obj,
});
}
export enum ExecutionState {
CANCELED = "CANCELED",
FAILED = "FAILED",
IN_PROGRESS = "IN_PROGRESS",
QUEUED = "QUEUED",
REJECTED = "REJECTED",
SUCCEEDED = "SUCCEEDED",
TIMED_OUT = "TIMED_OUT",
}
export interface DescribeExecutionOutput {
/**
* <p>The ID of the task being executed on the device.</p>
*/
taskId?: string;
/**
* <p>The ID of the execution.</p>
*/
executionId?: string;
/**
* <p>The ID of the managed device that the task is being executed on.</p>
*/
managedDeviceId?: string;
/**
* <p>The current state of the execution.</p>
*/
state?: ExecutionState | string;
/**
* <p>When the execution began.</p>
*/
startedAt?: Date;
/**
* <p>When the status of the execution was last updated.</p>
*/
lastUpdatedAt?: Date;
}
export namespace DescribeExecutionOutput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeExecutionOutput): any => ({
...obj,
});
}
export interface DescribeTaskInput {
/**
* <p>The ID of the task to be described.</p>
*/
taskId: string | undefined;
}
export namespace DescribeTaskInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeTaskInput): any => ({
...obj,
});
}
export enum TaskState {
CANCELED = "CANCELED",
COMPLETED = "COMPLETED",
IN_PROGRESS = "IN_PROGRESS",
}
export interface DescribeTaskOutput {
/**
* <p>The ID of the task.</p>
*/
taskId?: string;
/**
* <p>The Amazon Resource Name (ARN) of the task.</p>
*/
taskArn?: string;
/**
* <p>The managed devices that the task was sent to.</p>
*/
targets?: string[];
/**
* <p>The current state of the task.</p>
*/
state?: TaskState | string;
/**
* <p>When the <code>CreateTask</code> operation was called.</p>
*/
createdAt?: Date;
/**
* <p>When the state of the task was last updated.</p>
*/
lastUpdatedAt?: Date;
/**
* <p>When the task was completed.</p>
*/
completedAt?: Date;
/**
* <p>The description provided of the task and managed devices.</p>
*/
description?: string;
/**
* <p>Optional metadata that you assign to a resource. You can use tags to categorize a resource
* in different ways, such as by purpose, owner, or environment.</p>
*/
tags?: { [key: string]: string };
}
export namespace DescribeTaskOutput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DescribeTaskOutput): any => ({
...obj,
});
}
/**
* <p>Identifying information about the device.</p>
*/
export interface DeviceSummary {
/**
* <p>The ID of the device.</p>
*/
managedDeviceId?: string;
/**
* <p>The Amazon Resource Name (ARN) of the device.</p>
*/
managedDeviceArn?: string;
/**
* <p>The ID of the job used to order the device.</p>
*/
associatedWithJob?: string;
/**
* <p>Optional metadata that you assign to a resource. You can use tags to categorize a resource
* in different ways, such as by purpose, owner, or environment.</p>
*/
tags?: { [key: string]: string };
}
export namespace DeviceSummary {
/**
* @internal
*/
export const filterSensitiveLog = (obj: DeviceSummary): any => ({
...obj,
});
}
export interface ListExecutionsInput {
/**
* <p>The ID of the task.</p>
*/
taskId: string | undefined;
/**
* <p>A structure used to filter the tasks by their current state.</p>
*/
state?: ExecutionState | string;
/**
* <p>The maximum number of tasks to list per page.</p>
*/
maxResults?: number;
/**
* <p>A pagination token to continue to the next page of tasks.</p>
*/
nextToken?: string;
}
export namespace ListExecutionsInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListExecutionsInput): any => ({
...obj,
});
}
/**
* <p>The summary of a task execution on a specified device.</p>
*/
export interface ExecutionSummary {
/**
* <p>The ID of the task.</p>
*/
taskId?: string;
/**
* <p>The ID of the execution.</p>
*/
executionId?: string;
/**
* <p>The ID of the managed device that the task is being executed on.</p>
*/
managedDeviceId?: string;
/**
* <p>The state of the execution.</p>
*/
state?: ExecutionState | string;
}
export namespace ExecutionSummary {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ExecutionSummary): any => ({
...obj,
});
}
export interface ListExecutionsOutput {
/**
* <p>A list of executions. Each execution contains the task ID, the device that the task is
* executing on, the execution ID, and the status of the execution.</p>
*/
executions?: ExecutionSummary[];
/**
* <p>A pagination token to continue to the next page of executions.</p>
*/
nextToken?: string;
}
export namespace ListExecutionsOutput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListExecutionsOutput): any => ({
...obj,
});
}
export interface ListDeviceResourcesInput {
/**
* <p>The ID of the managed device that you are listing the resources of.</p>
*/
managedDeviceId: string | undefined;
/**
* <p>A structure used to filter the results by type of resource.</p>
*/
type?: string;
/**
* <p>The maximum number of resources per page.</p>
*/
maxResults?: number;
/**
* <p>A pagination token to continue to the next page of results.</p>
*/
nextToken?: string;
}
export namespace ListDeviceResourcesInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListDeviceResourcesInput): any => ({
...obj,
});
}
/**
* <p>A summary of a resource available on the device.</p>
*/
export interface ResourceSummary {
/**
* <p>The resource type.</p>
*/
resourceType: string | undefined;
/**
* <p>The Amazon Resource Name (ARN) of the resource.</p>
*/
arn?: string;
/**
* <p>The ID of the resource.</p>
*/
id?: string;
}
export namespace ResourceSummary {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ResourceSummary): any => ({
...obj,
});
}
export interface ListDeviceResourcesOutput {
/**
* <p>A structure defining the resource's type, Amazon Resource Name (ARN), and ID.</p>
*/
resources?: ResourceSummary[];
/**
* <p>A pagination token to continue to the next page of results.</p>
*/
nextToken?: string;
}
export namespace ListDeviceResourcesOutput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListDeviceResourcesOutput): any => ({
...obj,
});
}
export interface ListDevicesInput {
/**
* <p>The ID of the job used to order the device.</p>
*/
jobId?: string;
/**
* <p>The maximum number of devices to list per page.</p>
*/
maxResults?: number;
/**
* <p>A pagination token to continue to the next page of results.</p>
*/
nextToken?: string;
}
export namespace ListDevicesInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListDevicesInput): any => ({
...obj,
});
}
export interface ListDevicesOutput {
/**
* <p>A list of device structures that contain information about the device.</p>
*/
devices?: DeviceSummary[];
/**
* <p>A pagination token to continue to the next page of devices.</p>
*/
nextToken?: string;
}
export namespace ListDevicesOutput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListDevicesOutput): any => ({
...obj,
});
}
export interface ListTagsForResourceInput {
/**
* <p>The Amazon Resource Name (ARN) of the device or task.</p>
*/
resourceArn: string | undefined;
}
export namespace ListTagsForResourceInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListTagsForResourceInput): any => ({
...obj,
});
}
export interface ListTagsForResourceOutput {
/**
* <p>The list of tags for the device or task.</p>
*/
tags?: { [key: string]: string };
}
export namespace ListTagsForResourceOutput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListTagsForResourceOutput): any => ({
...obj,
});
}
export interface ListTasksInput {
/**
* <p>A structure used to filter the list of tasks.</p>
*/
state?: TaskState | string;
/**
* <p>The maximum number of tasks per page.</p>
*/
maxResults?: number;
/**
* <p>A pagination token to continue to the next page of tasks.</p>
*/
nextToken?: string;
}
export namespace ListTasksInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListTasksInput): any => ({
...obj,
});
}
/**
* <p>Information about the task assigned to one or many devices.</p>
*/
export interface TaskSummary {
/**
* <p>The task ID.</p>
*/
taskId: string | undefined;
/**
* <p>The Amazon Resource Name (ARN) of the task.</p>
*/
taskArn?: string;
/**
* <p>The state of the task assigned to one or many devices.</p>
*/
state?: TaskState | string;
/**
* <p>Optional metadata that you assign to a resource. You can use tags to categorize a resource
* in different ways, such as by purpose, owner, or environment.</p>
*/
tags?: { [key: string]: string };
}
export namespace TaskSummary {
/**
* @internal
*/
export const filterSensitiveLog = (obj: TaskSummary): any => ({
...obj,
});
}
export interface ListTasksOutput {
/**
* <p>A list of task structures containing details about each task.</p>
*/
tasks?: TaskSummary[];
/**
* <p>A pagination token to continue to the next page of tasks.</p>
*/
nextToken?: string;
}
export namespace ListTasksOutput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: ListTasksOutput): any => ({
...obj,
});
}
export interface TagResourceInput {
/**
* <p>The Amazon Resource Name (ARN) of the device or task.</p>
*/
resourceArn: string | undefined;
/**
* <p>Optional metadata that you assign to a resource. You can use tags to categorize a resource
* in different ways, such as by purpose, owner, or environment.</p>
*/
tags: { [key: string]: string } | undefined;
}
export namespace TagResourceInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: TagResourceInput): any => ({
...obj,
});
}
export interface UntagResourceInput {
/**
* <p>The Amazon Resource Name (ARN) of the device or task.</p>
*/
resourceArn: string | undefined;
/**
* <p>Optional metadata that you assign to a resource. You can use tags to categorize a resource
* in different ways, such as by purpose, owner, or environment.</p>
*/
tagKeys: string[] | undefined;
}
export namespace UntagResourceInput {
/**
* @internal
*/
export const filterSensitiveLog = (obj: UntagResourceInput): any => ({
...obj,
});
} | the_stack |
import type {
DbOptions,
Document,
ExplainVerbosityLike,
FindOneAndDeleteOptions,
FindOneAndReplaceOptions,
FindOneAndUpdateOptions,
DeleteOptions,
MapReduceOptions,
KMSProviders,
ExplainOptions
} from '@mongosh/service-provider-core';
import { CommonErrors, MongoshInvalidInputError, MongoshUnimplementedError } from '@mongosh/errors';
import crypto from 'crypto';
import type Database from './database';
import type Collection from './collection';
import { CursorIterationResult } from './result';
import { ShellApiErrors } from './error-codes';
import { BinaryType, ReplPlatform } from '@mongosh/service-provider-core';
import { ClientSideFieldLevelEncryptionOptions } from './field-level-encryption';
import { AutoEncryptionOptions } from 'mongodb';
import { shellApiType } from './enums';
import type { AbstractCursor } from './abstract-cursor';
import type ChangeStreamCursor from './change-stream-cursor';
import type { ShellBson } from './shell-bson';
import { inspect } from 'util';
/**
* Helper method to adapt aggregation pipeline options.
* This is here so that it's not visible to the user.
*
* @param options
*/
export function adaptAggregateOptions(options: any = {}): {
aggOptions: Document;
dbOptions: DbOptions;
explain?: ExplainVerbosityLike & string;
} {
const aggOptions = { ...options };
const dbOptions: DbOptions = {};
let explain;
if ('readConcern' in aggOptions) {
dbOptions.readConcern = options.readConcern;
delete aggOptions.readConcern;
}
if ('writeConcern' in aggOptions) {
Object.assign(dbOptions, options.writeConcern);
delete aggOptions.writeConcern;
}
if ('explain' in aggOptions) {
explain = validateExplainableVerbosity(aggOptions.explain);
delete aggOptions.explain;
}
return { aggOptions, dbOptions, explain };
}
export function validateExplainableVerbosity(verbosity: ExplainVerbosityLike): ExplainVerbosityLike & string {
// Legacy shell behavior.
if (verbosity === true) {
verbosity = 'allPlansExecution';
} else if (verbosity === false) {
verbosity = 'queryPlanner';
}
if (typeof verbosity !== 'string') {
throw new MongoshInvalidInputError('verbosity must be a string', CommonErrors.InvalidArgument);
}
return verbosity;
}
function getAssertCaller(caller?: string): string {
return caller ? ` (${caller})` : '';
}
export function assertArgsDefinedType(args: any[], expectedTypes: Array<true|string|Array<string | undefined>>, func?: string): void {
args.forEach((arg, i) => {
const expected = expectedTypes[i];
if (arg === undefined) {
if (expected !== true && Array.isArray(expected) && expected.includes(undefined)) {
return;
}
throw new MongoshInvalidInputError(
`Missing required argument at position ${i}${getAssertCaller(func)}`,
CommonErrors.InvalidArgument
);
} else if (expected === true) {
return;
}
if (((typeof expected === 'string' && typeof arg !== expected) || !expected.includes(typeof arg))) {
const expectedMsg = typeof expected === 'string' ? expected : expected.filter(e => e !== undefined).join(' or ');
throw new MongoshInvalidInputError(
`Argument at position ${i} must be of type ${expectedMsg}, got ${typeof arg} instead${getAssertCaller(func)}`,
CommonErrors.InvalidArgument
);
}
});
}
export function assertKeysDefined(object: any, keys: string[]): void {
for (const key of keys) {
if (object[key] === undefined) {
throw new MongoshInvalidInputError(`Missing required property: ${JSON.stringify(key)}`, CommonErrors.InvalidArgument);
}
}
}
/**
* Helper method to adapt objects that are slightly different from Shell to SP API.
*
* @param {Object} shellToCommand - a map of the shell key to the command key. If null, then omit.
* @param {Object} shellDoc - the document to be adapted
*/
export function adaptOptions(shellToCommand: any, additions: any, shellDoc: any): any {
return Object.keys(shellDoc).reduce((result, shellKey) => {
if (shellToCommand[shellKey] === null) {
return result;
}
result[ shellToCommand[shellKey] || shellKey ] = shellDoc[shellKey];
return result;
}, additions);
}
/**
* Optionally digest password if passwordDigestor field set to 'client'. If it's false,
* then hash the password.
*
* @param username
* @param passwordDigestor
* @param {Object} command
*/
export function processDigestPassword(
username: string,
passwordDigestor: 'server' | 'client',
command: { pwd: string }): { digestPassword?: boolean; pwd?: string } {
if (passwordDigestor === undefined) {
return {};
}
if (passwordDigestor !== 'server' && passwordDigestor !== 'client') {
throw new MongoshInvalidInputError(
`Invalid field: passwordDigestor must be 'client' or 'server', got ${passwordDigestor}`,
CommonErrors.InvalidArgument
);
}
if (passwordDigestor === 'client') {
if (typeof command.pwd !== 'string') {
throw new MongoshInvalidInputError(
`User passwords must be of type string. Was given password with type ${typeof command.pwd}`,
CommonErrors.InvalidArgument
);
}
const hash = crypto.createHash('md5');
hash.update(`${username}:mongo:${command.pwd}`);
const digested = hash.digest('hex');
return { digestPassword: false, pwd: digested };
}
return { digestPassword: true };
}
/**
* Return an object which will become a ShardingStatusResult
* @param mongo
* @param configDB
* @param verbose
*/
export async function getPrintableShardStatus(configDB: Database, verbose: boolean): Promise<Document> {
const result = {} as any;
// configDB is a DB object that contains the sharding metadata of interest.
const mongosColl = configDB.getCollection('mongos');
const versionColl = configDB.getCollection('version');
const shardsColl = configDB.getCollection('shards');
const chunksColl = configDB.getCollection('chunks');
const settingsColl = configDB.getCollection('settings');
const changelogColl = configDB.getCollection('changelog');
const [ version, shards, mostRecentMongos ] = await Promise.all([
versionColl.findOne(),
shardsColl.find().then(cursor => cursor.sort({ _id: 1 }).toArray()),
mongosColl.find().then(cursor => cursor.sort({ ping: -1 }).limit(1).tryNext())
]);
if (version === null) {
throw new MongoshInvalidInputError(
'This db does not have sharding enabled. Be sure you are connecting to a mongos from the shell and not to a mongod.',
ShellApiErrors.NotConnectedToMongos
);
}
result.shardingVersion = version;
result.shards = shards;
// (most recently) active mongoses
const mongosActiveThresholdMs = 60000;
let mostRecentMongosTime = null;
let mongosAdjective = 'most recently active';
if (mostRecentMongos !== null) {
mostRecentMongosTime = mostRecentMongos.ping;
// Mongoses older than the threshold are the most recent, but cannot be
// considered "active" mongoses. (This is more likely to be an old(er)
// configdb dump, or all the mongoses have been stopped.)
if (mostRecentMongosTime.getTime() >= Date.now() - mongosActiveThresholdMs) {
mongosAdjective = 'active';
}
}
mongosAdjective = `${mongosAdjective} mongoses`;
if (mostRecentMongosTime === null) {
result[mongosAdjective] = 'none';
} else {
const recentMongosQuery = {
ping: {
$gt: ((): any => {
const d = mostRecentMongosTime;
d.setTime(d.getTime() - mongosActiveThresholdMs);
return d;
})()
}
};
if (verbose) {
result[mongosAdjective] = await (await mongosColl
.find(recentMongosQuery))
.sort({ ping: -1 })
.toArray();
} else {
result[mongosAdjective] = (await (await mongosColl.aggregate([
{ $match: recentMongosQuery },
{ $group: { _id: '$mongoVersion', num: { $sum: 1 } } },
{ $sort: { num: -1 } }
])).toArray() as any[]).map((z: { _id: string; num: number }) => {
return { [z._id]: z.num };
});
}
}
const balancerRes: Record<string, any> = {};
await Promise.all([
(async(): Promise<void> => {
// Is autosplit currently enabled
const autosplit = await settingsColl.findOne({ _id: 'autosplit' }) as any;
result.autosplit = { 'Currently enabled': autosplit === null || autosplit.enabled ? 'yes' : 'no' };
})(),
(async(): Promise<void> => {
// Is the balancer currently enabled
const balancerEnabled = await settingsColl.findOne({ _id: 'balancer' }) as any;
balancerRes['Currently enabled'] = balancerEnabled === null || !balancerEnabled.stopped ? 'yes' : 'no';
})(),
(async(): Promise<void> => {
// Is the balancer currently active
let balancerRunning = 'unknown';
try {
const balancerStatus = await configDB.adminCommand({ balancerStatus: 1 });
balancerRunning = balancerStatus.inBalancerRound ? 'yes' : 'no';
} catch (err) {
// pass, ignore all error messages
}
balancerRes['Currently running'] = balancerRunning;
})(),
(async(): Promise<void> => {
// Output the balancer window
const settings = await settingsColl.findOne({ _id: 'balancer' });
if (settings !== null && settings.hasOwnProperty('activeWindow')) {
const balSettings = settings.activeWindow;
balancerRes['Balancer active window is set between'] = `${balSettings.start} and ${balSettings.stop} server local time`;
}
})(),
(async(): Promise<void> => {
// Output the list of active migrations
type Lock = { _id: string; when: Date };
const activeLocks: Lock[] = await (await configDB.getCollection('locks').find({ state: { $eq: 2 } })).toArray() as Lock[];
if (activeLocks?.length > 0) {
balancerRes['Collections with active migrations'] = activeLocks.map((lock) => {
return `${lock._id} started at ${lock.when}`;
});
}
})(),
(async(): Promise<void> => {
// Actionlog and version checking only works on 2.7 and greater
let versionHasActionlog = false;
const metaDataVersion = version.currentVersion;
if (metaDataVersion > 5) {
versionHasActionlog = true;
}
if (metaDataVersion === 5) {
const verArray = (await configDB.serverBuildInfo()).versionArray;
if (verArray[0] === 2 && verArray[1] > 6) {
versionHasActionlog = true;
}
}
if (versionHasActionlog) {
// Review config.actionlog for errors
const balErrs = await (await configDB.getCollection('actionlog').find({ what: 'balancer.round' })).sort({ time: -1 }).limit(5).toArray();
const actionReport = { count: 0, lastErr: '', lastTime: ' ' };
if (balErrs !== null) {
balErrs.forEach((r: any) => {
if (r.details.errorOccured) {
actionReport.count += 1;
if (actionReport.count === 1) {
actionReport.lastErr = r.details.errmsg;
actionReport.lastTime = r.time;
}
}
});
}
// Always print the number of failed rounds
balancerRes['Failed balancer rounds in last 5 attempts'] = actionReport.count;
// Only print the errors if there are any
if (actionReport.count > 0) {
balancerRes['Last reported error'] = actionReport.lastErr;
balancerRes['Time of Reported error'] = actionReport.lastTime;
}
// const migrations = sh.getRecentMigrations(configDB);
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
// Successful migrations.
let migrations = await (await changelogColl
.aggregate([
{
$match: {
time: { $gt: yesterday },
what: 'moveChunk.from',
'details.errmsg': { $exists: false },
'details.note': 'success'
}
},
{ $group: { _id: { msg: '$details.errmsg' }, count: { $sum: 1 } } },
{ $project: { _id: { $ifNull: ['$_id.msg', 'Success'] }, count: '$count' } }
]))
.toArray();
// Failed migrations.
migrations = migrations.concat(
await (await changelogColl
.aggregate([
{
$match: {
time: { $gt: yesterday },
what: 'moveChunk.from',
$or: [
{ 'details.errmsg': { $exists: true } },
{ 'details.note': { $ne: 'success' } }
]
}
},
{
$group: {
_id: { msg: '$details.errmsg', from: '$details.from', to: '$details.to' },
count: { $sum: 1 }
}
},
{
$project: {
_id: { $ifNull: ['$_id.msg', 'aborted'] },
from: '$_id.from',
to: '$_id.to',
count: '$count'
}
}
]))
.toArray());
const migrationsRes: Record<number, string> = {};
migrations.forEach((x: any) => {
if (x._id === 'Success') {
migrationsRes[x.count] = x._id;
} else {
migrationsRes[x.count] = `Failed with error '${x._id}', from ${x.from} to ${x.to}`;
}
});
if (migrations.length === 0) {
balancerRes['Migration Results for the last 24 hours'] = 'No recent migrations';
} else {
balancerRes['Migration Results for the last 24 hours'] = migrationsRes;
}
}
})()
]);
result.balancer = balancerRes;
const dbRes: any[] = [];
result.databases = dbRes;
const databases = await (await configDB.getCollection('databases').find()).sort({ name: 1 }).toArray();
// Special case the config db, since it doesn't have a record in config.databases.
databases.push({ '_id': 'config', 'primary': 'config', 'partitioned': true });
databases.sort((a: any, b: any): number => {
return a._id.localeCompare(b._id);
});
result.databases = await Promise.all(databases.map(async(db) => {
const escapeRegex = (string: string): string => {
return string.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};
const colls = await (await configDB.getCollection('collections')
.find({ _id: new RegExp('^' + escapeRegex(db._id) + '\\.') }))
.sort({ _id: 1 })
.toArray();
const collList: any =
await Promise.all(colls.filter(coll => !coll.dropped).map(async(coll) => {
const collRes = {} as any;
collRes.shardKey = coll.key;
collRes.unique = !!coll.unique;
if (typeof coll.unique !== 'boolean' && typeof coll.unique !== 'undefined') {
collRes.unique = [ !!coll.unique, { unique: coll.unique } ];
}
collRes.balancing = !coll.noBalance;
if (typeof coll.noBalance !== 'boolean' && typeof coll.noBalance !== 'undefined') {
collRes.balancing = [ !coll.noBalance, { noBalance: coll.noBalance } ];
}
const chunksRes = [];
const chunksCollMatch =
coll.uuid ? { $or: [ { uuid: coll.uuid }, { ns: coll._id } ] } : { ns: coll._id };
const chunks = await
(await chunksColl.aggregate([
{ $match: chunksCollMatch },
{ $group: { _id: '$shard', cnt: { $sum: 1 } } },
{ $project: { _id: 0, shard: '$_id', nChunks: '$cnt' } },
{ $sort: { shard: 1 } }
])).toArray();
let totalChunks = 0;
collRes.chunkMetadata = [];
chunks.forEach((z: any) => {
totalChunks += z.nChunks;
collRes.chunkMetadata.push({ shard: z.shard, nChunks: z.nChunks });
});
// NOTE: this will return the chunk info as a string, and will print ugly BSON
if (totalChunks < 20 || verbose) {
for await (const chunk of (await chunksColl.find(chunksCollMatch)).sort({ min: 1 })) {
const c = {
min: chunk.min,
max: chunk.max,
'on shard': chunk.shard,
'last modified': chunk.lastmod
} as any;
// Displaying a full, multi-line output for each chunk is a bit verbose,
// even if there are only a few chunks. Where supported, we use a custom
// inspection function to inspect a copy of this object with an unlimited
// line break length (i.e. all objects on a single line).
Object.defineProperty(c, Symbol.for('nodejs.util.inspect.custom'), {
value: function(depth: number, options: any): string {
return inspect({ ...this }, { ...options, breakLength: Infinity });
},
writable: true,
configurable: true
});
if (chunk.jumbo) c.jumbo = 'yes';
chunksRes.push(c);
}
} else {
chunksRes.push('too many chunks to print, use verbose if you want to force print');
}
const tagsRes: any[] = [];
for await (const tag of (await configDB.getCollection('tags').find(chunksCollMatch)).sort({ min: 1 })) {
tagsRes.push({
tag: tag.tag,
min: tag.min,
max: tag.max
});
}
collRes.chunks = chunksRes;
collRes.tags = tagsRes;
return [coll._id, collRes];
}));
return { database: db, collections: Object.fromEntries(collList) };
}));
return result;
}
export async function getConfigDB(db: Database): Promise<Database> {
const helloResult = await db._maybeCachedHello();
if (helloResult.msg !== 'isdbgrid') {
await db._instanceState.printWarning(
'MongoshWarning: [SHAPI-10003] You are not connected to a mongos. This command may not work as expected.');
}
return db.getSiblingDB('config');
}
export function dataFormat(bytes?: number): string {
if (bytes === null || bytes === undefined) {
return '0B';
}
if (bytes < 1024) {
return Math.floor(bytes) + 'B';
}
if (bytes < 1024 * 1024) {
return Math.floor(bytes / 1024) + 'KiB';
}
if (bytes < 1024 * 1024 * 1024) {
return Math.floor((Math.floor(bytes / 1024) / 1024) * 100) / 100 + 'MiB';
}
return Math.floor((Math.floor(bytes / (1024 * 1024)) / 1024) * 100) / 100 + 'GiB';
}
export function tsToSeconds(x: any): number {
if (x.t && x.i) {
return x.t;
}
return x / 4294967296; // low 32 bits are ordinal #s within a second
}
export function addHiddenDataProperty<T = any>(target: T, key: string|symbol, value: any): T {
Object.defineProperty(target, key, {
value,
enumerable: false,
writable: true,
configurable: true
});
return target;
}
export async function iterate(
results: CursorIterationResult,
cursor: AbstractCursor<any> | ChangeStreamCursor,
batchSize: number): Promise<CursorIterationResult> {
if (cursor.isClosed()) {
return results;
}
for (let i = 0; i < batchSize; i++) {
const doc = await cursor.tryNext();
if (doc === null) {
results.cursorHasMore = false;
break;
}
results.documents.push(doc);
}
return results;
}
// This is only used by collection.findAndModify() itself.
export type FindAndModifyMethodShellOptions = {
query: Document;
sort?: (FindOneAndDeleteOptions | FindOneAndReplaceOptions | FindOneAndUpdateOptions)['sort'];
update?: Document | Document[];
remove?: boolean;
new?: boolean;
fields?: Document;
upsert?: boolean;
bypassDocumentValidation?: boolean;
writeConcern?: Document;
collation?: (FindOneAndDeleteOptions | FindOneAndReplaceOptions | FindOneAndUpdateOptions)['collation'];
arrayFilters?: Document[];
explain?: ExplainVerbosityLike;
};
// These are used by findOneAndUpdate + findOneAndReplace.
export type FindAndModifyShellOptions<BaseOptions extends FindOneAndReplaceOptions | FindOneAndUpdateOptions> = BaseOptions & {
returnOriginal?: boolean;
returnNewDocument?: boolean;
new?: boolean;
};
export function processFindAndModifyOptions<BaseOptions extends FindOneAndReplaceOptions | FindOneAndUpdateOptions>(options: FindAndModifyShellOptions<BaseOptions>): BaseOptions {
options = { ...options };
if ('returnDocument' in options) {
if (options.returnDocument !== 'before' && options.returnDocument !== 'after') {
throw new MongoshInvalidInputError(
"returnDocument needs to be either 'before' or 'after'",
CommonErrors.InvalidArgument
);
}
delete options.returnNewDocument;
delete options.returnOriginal;
return options;
}
if ('returnOriginal' in options) {
options.returnDocument = options.returnOriginal ? 'before' : 'after';
delete options.returnOriginal;
delete options.returnNewDocument;
return options;
}
if ('returnNewDocument' in options) {
options.returnDocument = options.returnNewDocument ? 'after' : 'before';
delete options.returnOriginal;
delete options.returnNewDocument;
return options;
}
if ('new' in options) {
options.returnDocument = options.new ? 'after' : 'before';
delete options.returnOriginal;
delete options.returnNewDocument;
return options;
}
// No explicit option passed: We set 'returnDocument' to 'before' because the
// default of the shell differs from the default of the browser.
options.returnDocument = 'before';
return options;
}
export type RemoveShellOptions = DeleteOptions & { justOne?: boolean };
export function processRemoveOptions(options: boolean | RemoveShellOptions): RemoveShellOptions {
if (typeof options === 'boolean') {
return { justOne: options };
}
return { justOne: false, ...options };
}
export type MapReduceShellOptions = Document | string;
export function processMapReduceOptions(optionsOrOutString: MapReduceShellOptions): MapReduceOptions {
if (typeof optionsOrOutString === 'string') {
return { out: optionsOrOutString } as any;
} else if (optionsOrOutString.out === undefined) {
throw new MongoshInvalidInputError('Missing \'out\' option', CommonErrors.InvalidArgument);
} else {
return optionsOrOutString;
}
}
export async function setHideIndex(coll: Collection, index: string | Document, hidden: boolean): Promise<Document> {
const cmd = typeof index === 'string' ? {
name: index, hidden
} : {
keyPattern: index, hidden
};
return await coll._database._runCommand({
collMod: coll._name,
index: cmd
});
}
export function assertCLI(platform: ReplPlatform, features: string): void {
if (
platform !== ReplPlatform.CLI
) {
throw new MongoshUnimplementedError(
`${features} are not supported for current platform: ${ReplPlatform[platform]}`,
CommonErrors.NotImplemented
);
}
}
export function processFLEOptions(fleOptions: ClientSideFieldLevelEncryptionOptions): AutoEncryptionOptions {
assertKeysDefined(fleOptions, ['keyVaultNamespace', 'kmsProviders']);
Object.keys(fleOptions).forEach(k => {
if (['keyVaultClient', 'keyVaultNamespace', 'kmsProviders', 'schemaMap', 'bypassAutoEncryption'].indexOf(k) === -1) {
throw new MongoshInvalidInputError(`Unrecognized FLE Client Option ${k}`);
}
});
const autoEncryption: AutoEncryptionOptions = {
keyVaultClient: fleOptions.keyVaultClient?._serviceProvider.getRawClient(),
keyVaultNamespace: fleOptions.keyVaultNamespace
};
const localKey = fleOptions.kmsProviders.local?.key;
if (localKey && (localKey as BinaryType)._bsontype === 'Binary') {
const rawBuff = (localKey as BinaryType).value(true);
if (Buffer.isBuffer(rawBuff)) {
autoEncryption.kmsProviders = {
...fleOptions.kmsProviders,
local: {
key: rawBuff
}
};
} else {
throw new MongoshInvalidInputError('When specifying the key of a local KMS as BSON binary it must be constructed from a base64 encoded string');
}
} else {
autoEncryption.kmsProviders = { ...fleOptions.kmsProviders } as KMSProviders;
}
if (fleOptions.schemaMap) {
autoEncryption.schemaMap = fleOptions.schemaMap;
}
if (fleOptions.bypassAutoEncryption !== undefined) {
autoEncryption.bypassAutoEncryption = fleOptions.bypassAutoEncryption;
}
return autoEncryption;
}
// The then?: never check is to make sure this doesn't accidentally get applied
// to an un-awaited Promise, which is something that the author of this function
// might have messed up while implementing this.
type NotAPromise = { [key: string]: any, then?: never };
export function maybeMarkAsExplainOutput<T extends NotAPromise>(value: T, options: ExplainOptions): T {
if ('explain' in options) {
return markAsExplainOutput(value);
}
return value;
}
export function markAsExplainOutput<T extends NotAPromise>(value: T): T {
if (value !== null && typeof value === 'object') {
addHiddenDataProperty(value as any, shellApiType, 'ExplainOutput');
}
return value;
}
// https://docs.mongodb.com/v5.0/reference/limits/#naming-restrictions
// For db names, $ can be valid in some contexts (e.g. $external),
// so we let the server reject it if necessary.
export function isValidDatabaseName(name: string): boolean {
return !!name && !/[/\\. "\0]/.test(name);
}
export function isValidCollectionName(name: string): boolean {
return !!name && !/[$\0]/.test(name);
}
export function shouldRunAggregationImmediately(pipeline: Document[]): boolean {
return pipeline.some(stage =>
Object.keys(stage).some(
stageName => stageName === '$merge' || stageName === '$out'));
}
function isBSONDoubleConvertible(val: any): boolean {
return (typeof val === 'number' && Number.isInteger(val)) || val?._bsontype === 'Int32';
}
export function adjustRunCommand(cmd: Document, shellBson: ShellBson): Document {
if (cmd.replSetResizeOplog) {
if ('size' in cmd && isBSONDoubleConvertible(cmd.size)) {
return adjustRunCommand({ ...cmd, size: new shellBson.Double(+cmd.size) }, shellBson);
}
if ('minRetentionHours' in cmd && isBSONDoubleConvertible(cmd.minRetentionHours)) {
return adjustRunCommand({ ...cmd, minRetentionHours: new shellBson.Double(+cmd.minRetentionHours) }, shellBson);
}
}
if (cmd.profile) {
if ('sampleRate' in cmd && isBSONDoubleConvertible(cmd.sampleRate)) {
return adjustRunCommand({ ...cmd, sampleRate: new shellBson.Double(+cmd.sampleRate) }, shellBson);
}
}
return cmd;
} | the_stack |
* @module Rendering
*/
import { assert } from "@itwin/core-bentley";
import { Point3d, Vector3d } from "@itwin/core-geometry";
import { LinePixels, PolylineData, PolylineTypeFlags, QPoint3dList } from "@itwin/core-common";
import { MeshArgs, PolylineArgs } from "./mesh/MeshPrimitives";
import { VertexIndices, VertexTable } from "./VertexTable";
/** Parameter associated with each vertex index of a tesselated polyline. */
const enum PolylineParam { // eslint-disable-line no-restricted-syntax
kNone = 0,
kSquare = 1 * 3,
kMiter = 2 * 3,
kMiterInsideOnly = 3 * 3,
kJointBase = 4 * 3,
kNegatePerp = 8 * 3,
kNegateAlong = 16 * 3,
kNoneAdjustWeight = 32 * 3,
}
/**
* Represents a tesselated polyline.
* Given a polyline as a line string, each segment of the line string is triangulated into a quad.
* Based on the angle between two segments, additional joint triangles may be inserted in between to enable smoothly-rounded corners.
* @internal
*/
export interface TesselatedPolyline {
/** 24-bit index of each vertex. */
readonly indices: VertexIndices;
/** 24-bit index of the previous vertex in the polyline. */
readonly prevIndices: VertexIndices;
/** 24-bit index of the next vertex in the polyline, plus 8-bit parameter describing the semantics of this vertex. */
readonly nextIndicesAndParams: Uint8Array;
}
export namespace TesselatedPolyline {
export function fromMesh(args: MeshArgs): TesselatedPolyline | undefined {
const tesselator = PolylineTesselator.fromMesh(args);
return tesselator?.tesselate();
}
}
class PolylineVertex {
public isSegmentStart: boolean = false;
public isPolylineStartOrEnd: boolean = false;
public vertexIndex: number = 0;
public prevIndex: number = 0;
public nextIndex: number = 0;
public constructor() { }
public init(isSegmentStart: boolean, isPolylineStartOrEnd: boolean, vertexIndex: number, prevIndex: number, nextIndex: number) {
this.isSegmentStart = isSegmentStart;
this.isPolylineStartOrEnd = isPolylineStartOrEnd;
this.vertexIndex = vertexIndex;
this.prevIndex = prevIndex;
this.nextIndex = nextIndex;
}
public computeParam(negatePerp: boolean, adjacentToJoint: boolean = false, joint: boolean = false, noDisplacement: boolean = false): number {
if (joint)
return PolylineParam.kJointBase;
let param: PolylineParam;
if (noDisplacement)
param = PolylineParam.kNoneAdjustWeight; // prevent getting tossed before width adjustment
else if (adjacentToJoint)
param = PolylineParam.kMiterInsideOnly;
else
param = this.isPolylineStartOrEnd ? PolylineParam.kSquare : PolylineParam.kMiter;
let adjust = 0;
if (negatePerp)
adjust = PolylineParam.kNegatePerp;
if (!this.isSegmentStart)
adjust += PolylineParam.kNegateAlong;
return param + adjust;
}
}
class PolylineTesselator {
private _polylines: PolylineData[];
private _doJoints: boolean;
private _numIndices = 0;
private _vertIndex: number[] = [];
private _prevIndex: number[] = [];
private _nextIndex: number[] = [];
private _nextParam: number[] = [];
private _position: Point3d[] = [];
public constructor(polylines: PolylineData[], points: QPoint3dList | Point3d[], doJointTriangles: boolean) {
this._polylines = polylines;
if (points instanceof QPoint3dList) {
for (const p of points.list)
this._position.push(p.unquantize(points.params));
} else {
this._position = points;
}
this._doJoints = doJointTriangles;
}
public static fromPolyline(args: PolylineArgs): PolylineTesselator {
return new PolylineTesselator(args.polylines, args.points, wantJointTriangles(args.width, args.flags.is2d));
}
public static fromMesh(args: MeshArgs): PolylineTesselator | undefined {
if (undefined !== args.edges?.polylines.lines && undefined !== args.points)
return new PolylineTesselator(args.edges.polylines.lines, args.points, wantJointTriangles(args.edges.width, true === args.is2d));
return undefined;
}
public tesselate(): TesselatedPolyline {
this._tesselate();
const vertIndex = VertexIndices.fromArray(this._vertIndex);
const prevIndex = VertexIndices.fromArray(this._prevIndex);
const nextIndexAndParam = new Uint8Array(this._numIndices * 4);
for (let i = 0; i < this._numIndices; i++) {
const index = this._nextIndex[i];
const j = i * 4;
VertexIndices.encodeIndex(index, nextIndexAndParam, j);
nextIndexAndParam[j + 3] = this._nextParam[i] & 0x000000ff;
}
return {
indices: vertIndex,
prevIndices: prevIndex,
nextIndicesAndParams: nextIndexAndParam,
};
}
private _tesselate() {
const v0 = new PolylineVertex(), v1 = new PolylineVertex();
const maxJointDot = -0.7;
for (const line of this._polylines) {
if (line.numIndices < 2)
continue;
const last = line.numIndices - 1;
const isClosed: boolean = line.vertIndices[0] === line.vertIndices[last];
for (let i = 0; i < last; ++i) {
const idx0 = line.vertIndices[i];
const idx1 = line.vertIndices[i + 1];
const isStart: boolean = (0 === i);
const isEnd: boolean = (last - 1 === i);
const prevIdx0 = isStart ? (isClosed ? line.vertIndices[last - 1] : idx0) : line.vertIndices[i - 1];
const nextIdx1 = isEnd ? (isClosed ? line.vertIndices[1] : idx1) : line.vertIndices[i + 2];
v0.init(true, isStart && !isClosed, idx0, prevIdx0, idx1);
v1.init(false, isEnd && !isClosed, idx1, nextIdx1, idx0);
const jointAt0: boolean = this._doJoints && (isClosed || !isStart) && this._dotProduct(v0) > maxJointDot;
const jointAt1: boolean = this._doJoints && (isClosed || !isEnd) && this._dotProduct(v1) > maxJointDot;
if (jointAt0 || jointAt1) {
this._addVertex(v0, v0.computeParam(true, jointAt0, false, false));
this._addVertex(v1, v1.computeParam(false, jointAt1, false, false));
this._addVertex(v0, v0.computeParam(false, jointAt0, false, true));
this._addVertex(v0, v0.computeParam(false, jointAt0, false, true));
this._addVertex(v1, v1.computeParam(false, jointAt1, false, false));
this._addVertex(v1, v1.computeParam(false, jointAt1, false, true));
this._addVertex(v0, v0.computeParam(false, jointAt0, false, true));
this._addVertex(v1, v1.computeParam(false, jointAt1, false, true));
this._addVertex(v0, v0.computeParam(false, jointAt0, false, false));
this._addVertex(v0, v0.computeParam(false, jointAt0, false, false));
this._addVertex(v1, v1.computeParam(false, jointAt1, false, true));
this._addVertex(v1, v1.computeParam(true, jointAt1, false, false));
if (jointAt0)
this.addJointTriangles(v0, v0.computeParam(false, true, false, true), v0);
if (jointAt1)
this.addJointTriangles(v1, v1.computeParam(false, true, false, true), v1);
} else {
this._addVertex(v0, v0.computeParam(true));
this._addVertex(v1, v1.computeParam(false));
this._addVertex(v0, v0.computeParam(false));
this._addVertex(v0, v0.computeParam(false));
this._addVertex(v1, v1.computeParam(false));
this._addVertex(v1, v1.computeParam(true));
}
}
}
}
private addJointTriangles(v0: PolylineVertex, p0: number, v1: PolylineVertex): void {
const param = v1.computeParam(false, false, true);
for (let i = 0; i < 3; i++) {
this._addVertex(v0, p0);
this._addVertex(v1, param + i + 1);
this._addVertex(v1, param + i);
}
}
private _dotProduct(v: PolylineVertex): number {
const pos: Point3d = this._position[v.vertexIndex];
const prevDir: Vector3d = Vector3d.createStartEnd(this._position[v.prevIndex], pos);
const nextDir: Vector3d = Vector3d.createStartEnd(this._position[v.nextIndex], pos);
return prevDir.dotProduct(nextDir);
}
private _addVertex(vertex: PolylineVertex, param: number): void {
this._vertIndex[this._numIndices] = vertex.vertexIndex;
this._prevIndex[this._numIndices] = vertex.prevIndex;
this._nextIndex[this._numIndices] = vertex.nextIndex;
this._nextParam[this._numIndices] = param;
this._numIndices++;
}
}
/** Strictly for tests. @internal */
export function tesselatePolyline(polylines: PolylineData[], points: QPoint3dList, doJointTriangles: boolean): TesselatedPolyline {
const tesselator = new PolylineTesselator(polylines, points, doJointTriangles);
return tesselator.tesselate();
}
/**
* Describes a set of tesselated polylines.
* Each segment of each polyline is triangulated into a quad. Additional triangles may be inserted
* between segments to enable rounded corners.
*/
export class PolylineParams {
public readonly vertices: VertexTable;
public readonly polyline: TesselatedPolyline;
public readonly isPlanar: boolean;
public readonly type: PolylineTypeFlags;
public readonly weight: number;
public readonly linePixels: LinePixels;
/** Directly construct a PolylineParams. The PolylineParams takes ownership of all input data. */
public constructor(vertices: VertexTable, polyline: TesselatedPolyline, weight: number, linePixels: LinePixels, isPlanar: boolean, type: PolylineTypeFlags = PolylineTypeFlags.Normal) {
this.vertices = vertices;
this.polyline = polyline;
this.isPlanar = isPlanar;
this.weight = weight;
this.linePixels = linePixels;
this.type = type;
}
/** Construct from an PolylineArgs. */
public static create(args: PolylineArgs): PolylineParams | undefined {
assert(!args.flags.isDisjoint);
const vertices = VertexTable.createForPolylines(args);
if (undefined === vertices)
return undefined;
const tesselator = PolylineTesselator.fromPolyline(args);
if (undefined === tesselator)
return undefined;
return new PolylineParams(vertices, tesselator.tesselate(), args.width, args.linePixels, args.flags.isPlanar, args.flags.type);
}
}
export function wantJointTriangles(weight: number, is2d: boolean): boolean {
// Joints are incredibly expensive. In 3d, only generate them if the line is sufficiently wide for them to be noticeable.
const jointWidthThreshold = 3;
return is2d || weight >= jointWidthThreshold;
} | the_stack |
import G6 from '@antv/g6';
import Tooltip from '../../src/tooltip';
const div = document.createElement('div');
div.id = 'tooltip-plugin';
document.body.appendChild(div);
const data = {
nodes: [
{
id: 'node1',
label: 'node1',
x: 100,
y: 100,
},
{
id: 'node2',
label: 'node2',
x: 150,
y: 300,
},
],
edges: [
{
source: 'node1',
target: 'node2',
},
],
};
describe('tooltip', () => {
it('tooltip with default', () => {
const tooltip = new Tooltip();
const graph = new G6.Graph({
container: div,
width: 500,
height: 500,
plugins: [tooltip],
modes: {
default: ['drag-node', 'zoom-canvas', 'drag-canvas'],
},
defaultNode: {
type: 'rect',
},
defaultEdge: {
style: {
lineAppendWidth: 20,
},
},
});
graph.data(data);
graph.render();
const tooltipPlugin = graph.get('plugins')[0];
expect(tooltipPlugin.get('offsetX')).toBe(6);
expect(tooltipPlugin.get('tooltip').outerHTML).toBe(
`<div class="g6-component-tooltip" style="position: absolute; visibility: hidden; display: none;"></div>`,
);
graph.emit('node:mouseenter', { item: graph.getNodes()[0] });
expect(tooltipPlugin.get('tooltip').style.visibility).toEqual('visible');
graph.emit('node:mouseleave', { item: graph.getNodes()[0] });
expect(tooltipPlugin.get('tooltip').style.visibility).toEqual('hidden');
graph.destroy();
});
it('tooltip with dom', () => {
const tooltip = new Tooltip({
offsetX: 10,
getContent(e) {
const outDiv = document.createElement('div');
outDiv.style.width = '180px';
outDiv.innerHTML = `
<h4>自定义tooltip</h4>
<ul>
<li>Label: ${e.item.getModel().label || e.item.getModel().id}</li>
</ul>`;
return outDiv;
},
});
expect(tooltip.get('offsetX')).toBe(10);
const graph = new G6.Graph({
container: div,
width: 500,
height: 500,
plugins: [tooltip],
modes: {
default: ['drag-node', 'zoom-canvas', 'drag-canvas'],
},
defaultEdge: {
style: {
lineAppendWidth: 20,
},
},
});
graph.data(data);
graph.render();
const tooltipPlugin = graph.get('plugins')[0];
expect(tooltipPlugin.get('offsetX')).toBe(10);
graph.destroy();
});
it('tooltip with string', () => {
const tooltip = new Tooltip({
getContent(e) {
return `<div style='width: 180px;'>
<ul id='menu'>
<li title='1'>测试02</li>
<li title='2'>测试02</li>
<li>测试02</li>
<li>测试02</li>
<li>测试02</li>
</ul>
</div>`;
},
});
expect(tooltip.get('offsetX')).toBe(6);
const graph = new G6.Graph({
container: div,
width: 500,
height: 500,
plugins: [tooltip],
modes: {
default: ['drag-node', 'zoom-canvas', 'drag-canvas'],
},
});
graph.data(data);
graph.render();
graph.destroy();
});
it('tooltip fix to item', () => {
data.nodes[0].x = 120;
data.nodes[0].y = 20;
data.nodes[1].x = 450;
data.nodes[1].y = 450;
const offsetX = 0 // 5 + 20; // 当前 canvas 的左侧元素宽度总和
const offsetY = 0 // 162 + 20; // 当前 canvas 的上方元素高度总和
const fixToNode = [1, 0.5];
const tooltip = new Tooltip({
getContent(e) {
return `<div style='width: 180px;'>
<ul id='menu'>
<li title='1'>测试02</li>
<li title='2'>测试02</li>
<li>测试02</li>
<li>测试02</li>
<li>测试02</li>
</ul>
</div>`;
},
fixToNode,
offsetX,
offsetY,
trigger: 'click'
});
const graph = new G6.Graph({
container: div,
width: 500,
height: 500,
plugins: [tooltip],
modes: {
default: ['drag-node', 'zoom-canvas', 'drag-canvas'],
},
});
graph.getContainer().style.backgroundColor = '#ccc'
graph.data(data);
graph.render();
const tooltipPlugin = graph.get('plugins')[0];
graph.emit('node:click', { item: graph.getNodes()[0] });
const dom = tooltipPlugin.get('tooltip')
expect(dom.style.visibility).toEqual('visible');
const nodeBBox = graph.getNodes()[0].getBBox();
const expectPoint = {
x: nodeBBox.minX + nodeBBox.width * fixToNode[0],
y: nodeBBox.minY + nodeBBox.height * fixToNode[1]
}
const expectCanvasXY = graph.getCanvasByPoint(expectPoint.x, expectPoint.y);
const graphContainer = graph.getContainer();
expectCanvasXY.x += graphContainer.offsetLeft + offsetX;
expectCanvasXY.y += graphContainer.offsetTop + offsetY;
expect(dom.style.left).toEqual(`${expectCanvasXY.x}px`)
expect(dom.style.top).toEqual(`${expectCanvasXY.y}px`)
graph.emit('canvas:click', { item: graph.getNodes()[0] });
expect(dom.style.visibility).toEqual('hidden');
graph.emit('node:click', { item: graph.getNodes()[1] });
const nodeBBox2 = graph.getNodes()[0].getBBox();
const expectPoint2 = {
x: nodeBBox2.minX + nodeBBox2.width * fixToNode[0],
y: nodeBBox2.minY + nodeBBox2.height * fixToNode[1]
}
const expectCanvasXY2 = graph.getCanvasByPoint(expectPoint2.x, expectPoint2.y);
expectCanvasXY2.x += graphContainer.offsetLeft + offsetX;
expectCanvasXY2.y += graphContainer.offsetTop + offsetY;
// 此时超出了下边界和右边界
const bbox = dom.getBoundingClientRect();
expectCanvasXY2.x -= bbox.width + offsetX;
expectCanvasXY2.y -= bbox.height + offsetY;
// 由于测试界面图上方的 DOM 未渲染出来导致的误差,下面内容无法判断
// expect(dom.style.left === `${expectCanvasXY2.x}px`).toEqual(true)
// expect(dom.style.top === `${expectCanvasXY2.y}px`).toEqual(true)
graph.destroy();
});
});
describe('tooltip mouse out of view', () => {
it('tooltip mouse out of view', () => {
// 扩展studio节点
G6.registerNode(
'pai-studio-node',
{
afterDraw(cfg: any, group: any) {
if (cfg.ports) {
const [width, height] = cfg.size;
const ports = [...(cfg.ports?.inputPorts ?? []), ...(cfg.ports?.outputPorts ?? [])];
const anchorPoints = getAnchorPoints(cfg.ports?.inputPorts ?? [], cfg.ports?.outputPorts ?? []);
anchorPoints.forEach((point, index) => {
let text = 'undefined';
if (cfg.ports) {
if (!ports[index].desc) {
return;
}
text = ports[index].desc;
}
const textWidth = parseInt(G6.Util.getTextSize(text, 12)[0]) + 28;
const x = point[0] * width - width / 2;
const y = point[1] * height - height / 2;
const rectTranslateY = point[1] === 0 ? -40 - 14 : 14;
const textTranslateY = point[1] === 0 ? -40 - 14 + 20 : 14 + 20;
group.addShape('circle', {
attrs: {
x,
y,
r: 5,
fill: '#fff',
stroke: '#8086a2',
cursor: 'pointer',
opacity: 0,
},
name: 'link-point',
index,
model: ports[index],
tooltip: {
rect: {
attrs: {
x: x - textWidth / 2,
y: y + rectTranslateY,
width: textWidth,
height: 40,
fill: 'rgba(0, 0, 0, 0.75)',
radius: [4, 4],
},
name: 'link-point-tooltip-rect-shape',
index,
},
text: {
attrs: {
text,
x: x - textWidth / 2 + 8,
y: y + textTranslateY,
fontSize: 12,
textAlign: 'left',
textBaseline: 'middle',
fill: '#fff',
},
name: 'link-point-tooltip-text-shape',
index,
},
arrow: {
attrs: {
x,
y: point[1] === 0 ? -30.6 : 30.6,
r: 4,
fill: 'rgba(0, 0, 0, 0.75)',
symbol: point[1] === 0 ? 'triangle-down' : 'triangle',
},
name: 'link-point-tooltip-arrow-shape',
index,
},
},
});
});
}
group.addShape('rect', {
attrs: {
x: -86,
y: -16,
width: 32,
height: 32,
stroke: null,
fill: '#f00',
radius: [12, 12],
},
zIndex: 1,
name: 'rect-shape',
});
group.addShape('image', {
attrs: {
x: -78,
y: -8,
width: 16,
height: 16,
img: 'https://img.alicdn.com/tfs/TB1fyIo3KL2gK0jSZFmXXc7iXXa-200-200.png',
},
name: 'logo-icon',
zIndex: 10,
});
},
afterUpdate(cfg: any, node: any) {
const g = node._cfg.group;
const children = g.get('children');
const anchors = children.filter((child) => {
return child.cfg.name === 'link-point';
});
if (anchors.length) {
anchors.forEach((item) => {
g.removeChild(item);
});
}
if (cfg.ports) {
const [width, height] = cfg.size;
const ports = [...(cfg.ports?.inputPorts ?? []), ...(cfg.ports?.outputPorts ?? [])];
const anchorPoints = getAnchorPoints(cfg.ports?.inputPorts ?? [], cfg.ports?.outputPorts ?? []);
anchorPoints.forEach((point, index) => {
let text = 'undefined';
if (cfg.ports) {
if (!ports[index].desc) {
return;
}
text = ports[index].desc;
}
const textWidth = parseInt(G6.Util.getTextSize(text, 12)[0]) + 28;
const x = point[0] * width - width / 2;
const y = point[1] * height - height / 2;
const rectTranslateY = point[1] === 0 ? -40 - 14 : 14;
const textTranslateY = point[1] === 0 ? -40 - 14 + 20 : 14 + 20;
g.addShape('circle', {
attrs: {
x,
y,
r: 5,
fill: '#fff',
stroke: '#8086a2',
cursor: 'pointer',
opacity: 0,
},
name: 'link-point',
index,
model: ports[index],
tooltip: {
rect: {
attrs: {
x: x - textWidth / 2,
y: y + rectTranslateY,
width: textWidth,
height: 40,
fill: 'rgba(0, 0, 0, 0.75)',
radius: [4, 4],
},
name: 'link-point-tooltip-rect-shape',
index,
},
text: {
attrs: {
text,
x: x - textWidth / 2 + 8,
y: y + textTranslateY,
fontSize: 12,
textAlign: 'left',
textBaseline: 'middle',
fill: '#fff',
},
name: 'link-point-tooltip-text-shape',
index,
},
arrow: {
attrs: {
x,
y: point[1] === 0 ? -30.6 : 30.6,
r: 4,
fill: 'rgba(0, 0, 0, 0.75)',
symbol: point[1] === 0 ? 'triangle-down' : 'triangle',
},
name: 'link-point-tooltip-arrow-shape',
index,
},
},
});
});
}
const nodeStatus = cfg.Status;
const nodeStatusType = cfg.StatusType;
const { group } = node._cfg;
const icon = group.find((item) => {
return item.cfg.name === 'status-icon';
});
if (icon) {
if (icon.cfg?.Status === nodeStatus && icon.cfg?.StatusType === nodeStatusType) {
return;
} else {
group.removeChild(icon);
}
}
let statusIcon;
if (cfg.StatusType === 1) {
statusIcon = statusMap['Edited'];
} else {
statusIcon = status.includes(nodeStatus) ? statusMap[nodeStatus] : null;
}
if (statusIcon) {
const image = group.addShape('image', {
// 节点状态图标
attrs: {
x: 68,
y: -8,
width: 16,
height: 16,
img: statusIcon,
},
name: 'status-icon',
status: nodeStatus,
});
if (nodeStatus === 'Running') {
image.animate(
(ratio) => {
const matrix = [1, 0, 0, 0, 1, 0, 0, 0, 1];
const toMatrix = G6.Util.transform(matrix, [
['t', -76, 0],
['r', ratio * Math.PI * 2],
['t', 76, 0],
]);
return {
matrix: toMatrix,
};
},
{
repeat: true,
duration: 2000,
easing: 'easeLinear',
},
);
}
}
},
// 响应状态变化
setState(name, value, item: any) {
const group = item.getContainer();
const children = group.get('children');
const keyShape = children.find((child) => child.cfg.name === 'pai-studio-node-keyShape');
if (name === 'hover') {
if (value) {
keyShape.attr('stroke', '#CFD4E5');
keyShape.attr('lineWidth', 2.5);
} else {
keyShape.attr('stroke', '#c9cbc9');
keyShape.attr('lineWidth', 1);
}
}
if (name === 'click') {
if (value) {
keyShape.attr('fill', '#F6F7FB');
keyShape.attr('stroke', '#D7DBE9');
keyShape.attr('lineWidth', 1);
} else {
keyShape.attr('fill', '#FFFFFF');
keyShape.attr('stroke', '#D7DBE9');
keyShape.attr('lineWidth', 1);
}
}
if (name === 'selected') {
if (value) {
keyShape.attr('fill', '#E2F2FF');
keyShape.attr('stroke', '#D7DBE9');
keyShape.attr('lineWidth', 1);
} else {
keyShape.attr('fill', '#FFFFFF');
keyShape.attr('stroke', '#D7DBE9');
keyShape.attr('lineWidth', 1);
}
}
},
},
'modelRect',
);
// 扩展边
const lineDash = [4, 2, 1, 2]; // 描述边虚线
G6.registerEdge(
'pai-studio-edge',
{
afterUpdate(cfg: any, edge: any) {
const { group } = edge._cfg;
const s = cfg.Status;
const shape = group.get('children')[0]; // 获得该边的第一个图形,这里是边的 path
if (s === 'Running') {
let index = 0;
// 边 path 图形的动画
shape.animate(
() => {
index++;
if (index > 9) {
index = 0;
}
return {
lineDash,
lineDashOffset: -index,
};
},
{
repeat: true, // 动画重复
duration: 3000, // 一次动画的时长为 3000
},
);
shape.attr('stroke', '#00C800');
} else {
shape.stopAnimate();
shape.attr('lineDash', null);
shape.attr('stroke', '#969BB4');
}
},
// 响应状态变化
setState(name, value, item: any) {
const shape = item.get('keyShape');
if (name === 'hover') {
if (value) {
shape.attr('lineWidth', 3);
} else if (item.get('states').includes('click')) {
shape.attr('lineWidth', 3);
} else {
shape.attr('lineWidth', 1);
}
}
if (name === 'click') {
if (value) {
shape.attr('lineWidth', 3);
} else {
shape.attr('lineWidth', 1);
}
}
},
},
'cubic-vertical',
);
const tooltip = new Tooltip();
const graph = new G6.Graph({
container: div,
width: 500,
height: 500,fitCenter: true, // 图居中
enabledStack: true, // 设置为true,启用 redo & undo 栈功能
defaultNode: {
type: 'pai-studio-node',
size: [180, 40],
logoIcon: {
show: true,
width: 22,
height: 22,
img: null,
},
stateIcon: {
show: false, // 默认节点中表示状态的icon配置
},
style: {
cursor: 'pointer',
radius: 12,
stroke: '#c9cbc9',
fill: '#ffffff',
},
labelCfg: {
position: 'center',
style: {
fill: '#595959',
fontSize: 12,
cursor: 'pointer',
color: '#262831',
},
offset: 20,
},
preRect: {
show: false, // 默认节点左侧的小矩形
},
},
defaultEdge: {
type: 'pai-studio-edge',
style: {
stroke: '#969BB4',
endArrow: {
path: G6.Arrow.triangle(8, 8, 0),
fill: '#969BB4',
},
lineWidth: 1.5,
},
minCurveOffset: [70, -70],
},
modes: {
default: [
{
type: 'drag-canvas',
scalableRange: -100,
},
{
type: 'drag-node',
onlyChangeComboSize: true,
},
'double-finger-drag-canvas',
],
brush: [
{
type: 'brush-select',
trigger: 'drag',
includeEdges: true,
brushStyle: {
stroke: '#0070cc',
lineWidth: 1,
fill: '#eee',
fillOpacity: 0.3,
},
},
],
},
});
const d = {
RequestId: '2C28B8C7-A2FD-436E-A254-9269719DB501',
Content: {
nodes: [
{
id: '9a69c538b1eb4a3583e04bc4e88d2c66',
label: '特征分桶特征分桶特征分桶',
hasPipelines: false,
metadata: {
provider: 'pai',
identifier: '特征分桶',
version: 'v1',
signature: '159593978189133',
io: {
inputs: {
inputArtifact1: 1,
},
},
},
position: {
x: -300,
y: -180,
},
properties: [
{
label: 'detailColName',
value: '1024',
},
{
label: 'testColName',
value: '1',
},
{
label: '_advanced',
value: true,
},
{
label: 'selectColumns',
value: 'a,b,hour,pm10,so2,co,no2,pm2',
},
{
label: 'selectTest',
value: 'info',
},
{
label: 'oss',
value: 'https://mocks.alibaba-inc.com/project/STo77KX31/EditExp',
},
{
label: 'datePicker',
value: '2020/7/30',
},
{
label: 'editor',
value: 'Test Editor',
},
{
label: 'model_opt_lr',
value: {
seq_lenght: 1,
batch_size: 2,
learning_rate: 3,
save_steps: 4,
probe_steps: 5,
train_steps: '',
train_stepssssssss: '',
},
},
{
label: 'train_params',
value: {
seq_lenght: '',
batch_size: '',
learning_rate: '',
save_steps: '',
probe_steps: '',
train_steps: '',
train_stepssssssss: '',
},
},
{
label: 'joinInput',
value: 'value1:value2',
},
{
label: 'scoreColName',
value: 'scoreColName',
},
{
label: 'positiveLabel',
value: 22,
},
{
label: 'infos',
value: [
{
columnName: 'categorycategorycategory',
columnType: 'STRING',
dataRange: '体育,女性,娱乐',
},
{
columnName: 'title',
columnType: 'STRING',
dataRange:
'全国10个城市的男人最有魅力基因,图文:美国高尔夫公开赛次轮 加西亚充满自信,王丽雅走秀自爆喝水太少导致尿血胃痉挛(图),组图:王励勤传闻女友大比拼 小爱可爱赵薇性感,组图:穆雷摔倒拇指受伤 稚气古尔比斯草场做秀',
},
{
columnName: 'content',
columnType: 'STRING',
dataRange:
'体育讯 北京时间6月14日,2008美国高尔夫公开赛第二轮继续展开激烈的争夺。首轮结束后,美国球手凯文-斯特里尔曼和贾斯汀-希克斯并列占据了成绩榜的榜首位置,两人都在星期四打出了68杆低于标准杆3杆的...,我来说两句作者:CFP2008年6月12日,台湾,名模外型亮丽,却不一定比一般人更懂保养身体,王丽雅日前血尿吓得赶紧看医生,病因竟是她太少喝水!昨天(6月11日)走彩妆秀失手掉产品的钱帅君,和同门陈志...,我来说两句广州男人:爱拼才会赢无可否认,广州男人发了,广州男人财大气粗,似乎分分秒秒都在挣钱。广州男人形象并不高大,皮肤也黝黑,但他们用豪华私家车、别墅、名牌西服、名牌衬衣、名牌皮鞋所包装出的气派,却...,跳转至:页12/18我来说两句北京时间6月12日晚,总奖金额为71.3万欧元的英国女王草地杯开始第四比赛日角逐。在男单第三轮争夺中,大赛6号种子、英国天才少年安迪-穆雷在先丢一盘的情况下上演大逆转,最...,跳转至:页15/40我来说两句名人的爱情本就一直受到众人的关注,尤其是当被套上乒乓球奥运冠军和娱乐圈美女的光环之后,恐怕想低调都很难。中国乒坛的“文体恋”更是受人关注,那些奥运冠军和娱乐圈美女的爱情故...',
},
],
},
],
},
{
id: '9a69c538b1eb4a3583e04bc4e88d2110',
label: '通用模型导出',
hasPipelines: false,
metadata: {
provider: 'pai',
identifier: '通用模型导出',
version: 'v1',
signature: '159593978189110',
},
position: {
x: 0,
y: 50,
},
properties: [],
},
{
id: '9a69c538b1eb4a3583e0dsfsdff4bc4e88d2110',
label: '逻辑回归二分类预发',
hasPipelines: false,
metadata: {
provider: 'pai',
identifier: 'logisticregression_binary',
version: 'v1',
signature: '9aebba164fc81ad71ae45446c18ccbb5048acd5b',
},
position: {
x: 0,
y: 50,
},
properties: [],
},
{
id: '9a69c538b1eb4a3583e04bc4e88d2111',
label: 'Etrec',
hasPipelines: false,
metadata: {
provider: 'pai',
identifier: 'Etrec',
version: 'v1',
signature: '159593978189110',
},
position: {
x: 0,
y: 100,
},
properties: [],
},
{
id: '9a69c538b1eb4a3583e04bc4e88d2112',
label: 'ALS',
hasPipelines: false,
metadata: {
provider: 'pai',
identifier: 'ALS',
version: 'v1',
signature: '159593978189110',
},
position: {
x: 0,
y: 150,
},
properties: [],
},
{
id: '9a69c538b1eb4a3583e04bc4e88d2113',
label: 'GraphSage',
hasPipelines: false,
metadata: {
provider: 'pai',
identifier: 'GraphSage',
version: 'v1',
signature: '159593978189110',
},
position: {
x: 0,
y: 200,
},
properties: [],
},
{
id: '9a69c538b1eb4a3583e04bc4e88d2114',
label: 'DeepFM',
hasPipelines: false,
metadata: {
provider: 'pai',
identifier: 'DeepFM',
version: 'v1',
signature: '159593978189110',
},
position: {
x: 0,
y: 250,
},
properties: [],
},
{
id: '9a69c538b1eb4a3583e04bc4e88d1122',
label: '读数据表',
hasPipelines: false,
metadata: {
provider: 'pai',
identifier: '读数据表',
version: 'v1',
signature: '1595939781122',
},
position: {
x: 0,
y: 300,
},
properties: [
{
label: 'inputTable',
value: 'testValue',
},
],
},
{
id: '36a9883cd71c4a8d95774b29dd0a9cdd',
label: 'Split',
hasPipelines: false,
pipelines: {
nodes: [
{
id: 'child_1',
label: 'child_1',
},
],
edges: [
{
source: '9a69c538b1eb4a3583e04bc4e88d2c66',
target: 'child_1',
},
{
source: '9a69c538b1eb4a3583e04bc4e88d2c66',
target: 'child_2',
},
{
source: 'child_1',
target: 'ebbb9038f9914d839e4a22d78e4e4991',
},
{
source: 'child_2',
target: 'ebbb9038f9914d839e4a22d78e4e4991',
},
],
},
metadata: {
provider: 'pai',
identifier: 'Logistic regression',
version: 'v1',
signature: '1595939781891',
},
position: {
x: -300,
y: 0,
},
properties: [
{
label: 'detailColName',
value: '0.8',
},
{
label: 'inputColName',
value: '10',
},
{
label: 'outputColName',
value: '10',
},
{
label: 'infoTable',
value: [
{
columnName: 'categorycategorycategory',
columnType: 'STRING',
dataRange: '体育,女性,娱乐',
},
{
columnName: 'title',
columnType: 'STRING',
dataRange:
'全国10个城市的男人最有魅力基因,图文:美国高尔夫公开赛次轮 加西亚充满自信,王丽雅走秀自爆喝水太少导致尿血胃痉挛(图),组图:王励勤传闻女友大比拼 小爱可爱赵薇性感,组图:穆雷摔倒拇指受伤 稚气古尔比斯草场做秀',
},
{
columnName: 'content',
columnType: 'STRING',
dataRange:
'体育讯 北京时间6月14日,2008美国高尔夫公开赛第二轮继续展开激烈的争夺。首轮结束后,美国球手凯文-斯特里尔曼和贾斯汀-希克斯并列占据了成绩榜的榜首位置,两人都在星期四打出了68杆低于标准杆3杆的...,我来说两句作者:CFP2008年6月12日,台湾,名模外型亮丽,却不一定比一般人更懂保养身体,王丽雅日前血尿吓得赶紧看医生,病因竟是她太少喝水!昨天(6月11日)走彩妆秀失手掉产品的钱帅君,和同门陈志...,我来说两句广州男人:爱拼才会赢无可否认,广州男人发了,广州男人财大气粗,似乎分分秒秒都在挣钱。广州男人形象并不高大,皮肤也黝黑,但他们用豪华私家车、别墅、名牌西服、名牌衬衣、名牌皮鞋所包装出的气派,却...,跳转至:页12/18我来说两句北京时间6月12日晚,总奖金额为71.3万欧元的英国女王草地杯开始第四比赛日角逐。在男单第三轮争夺中,大赛6号种子、英国天才少年安迪-穆雷在先丢一盘的情况下上演大逆转,最...,跳转至:页15/40我来说两句名人的爱情本就一直受到众人的关注,尤其是当被套上乒乓球奥运冠军和娱乐圈美女的光环之后,恐怕想低调都很难。中国乒坛的“文体恋”更是受人关注,那些奥运冠军和娱乐圈美女的爱情故...',
},
],
},
],
},
{
id: 'ebbb9038f9914d839e4a22d78e4e4991',
label: '逻辑回归二分类-1',
hasPipelines: false,
metadata: {
provider: 'pai',
identifier: 'Logistic regression',
version: 'v1',
signature: '1595939781891',
},
position: {
x: -300,
y: 180,
},
properties: [
{
inputTable: {
label: 'inputTable',
ref: {
nodeId: '36a9883cd71c4a8d95774b29dd0a9cdd',
propertityName: 'outputTable1Artifact',
},
},
},
{
label: 'featureColNames',
value: 'column1,column2,column3',
},
{
label: 'labelColName',
value: 'column4',
},
{
label: 'goodValue',
value: '1',
},
{
label: 'enableSparse',
value: 'false',
},
{
label: 'regularizedType',
value: 'L1',
},
{
label: 'maxIter',
value: '100',
},
{
label: 'regularizedLevel',
value: '1',
},
{
label: 'epsilon',
value: '0.000001',
},
{
label: 'regularizedLevel',
value: '1',
},
{
label: 'regularizedLevel',
value: '1',
},
{
label: 'regularizedLevel',
value: '1',
},
{
label: 'coreNum',
value: '10',
},
{
label: 'memSizePerCore',
value: '1024',
},
{
label: 'itemDelimiter',
value: ',',
},
{
label: 'kvDelimiter',
value: ':',
},
{
label: 'outputModelName',
value: 'xxxx',
},
],
},
],
edges: [
{
source: '9a69c538b1eb4a3583e04bc4e88d2c66',
sourceAnchor: 'outputsArtifact1',
target: '36a9883cd71c4a8d95774b29dd0a9cdd',
targetAnchor: 'inputArtifact1',
targetAnchorIndex: 0,
},
{
source: '36a9883cd71c4a8d95774b29dd0a9cdd',
sourceAnchor: 'outputsArtifact1',
target: 'ebbb9038f9914d839e4a22d78e4e4991',
targetAnchor: 'inputArtifact1',
targetAnchorIndex: 1,
},
],
globalParams: [
{
label: 'bucket',
value: 'oss-bucket',
},
{
label: 'execution',
value: 'test',
},
],
globalSettings: [],
},
Creator: '1557702098194904',
Description: '机器学习算法计算出二氧化氮对于雾霾影响最大testsststtsssssssssssssssssssss',
ExperimentId: 'experiment-kftihe4c1w5gx2slsf',
GmtCreateTime: '2021-01-30T12:51:33.028Z',
GmtModifiedTime: '2021-01-30T12:51:33.028Z',
Name: '雾霾天气预测11111',
Source: 'string',
Version: 0,
WorkspaceId: 'ws-5fys1on3yn5lymx637',
};
graph.data(d.Content);
graph.render();
})
}); | the_stack |
import { fakeAsync, tick } from '@angular/core/testing';
import { Observable, Subject, Subscription } from 'rxjs';
import { Notification } from 'rxjs/internal/Notification';
import { reduce } from 'rxjs/operators';
import { fromWorkerPool } from './from-worker-pool';
// tslint:disable:no-non-null-assertion
describe('fromWorkerPool', () => {
let stubbedWorkers: Worker[];
let workerFactorySpy: jasmine.Spy;
beforeEach(() => {
stubbedWorkers = [];
workerFactorySpy = jasmine.createSpy('workerFactorySpy');
let stubWorkerIndex = 0;
workerFactorySpy.and.callFake(() => {
const stubWorker = jasmine.createSpyObj(`stubWorker${stubWorkerIndex++}`, ['postMessage', 'terminate']);
stubbedWorkers.push(stubWorker);
return stubWorker;
});
});
describe('with observable input', () => {
let input$: Subject<number>;
let stubbedWorkerStream: Observable<number>;
beforeEach(() => {
input$ = new Subject();
stubbedWorkerStream = fromWorkerPool<number, number>(workerFactorySpy, input$);
});
it('constructs one worker for one piece of work', () => {
expect(workerFactorySpy).not.toHaveBeenCalled();
const subscriptionSpy = jasmine.createSpy('subscriptionSpy');
const sub = stubbedWorkerStream.subscribe(subscriptionSpy);
expect(workerFactorySpy).not.toHaveBeenCalled();
expect(subscriptionSpy).not.toHaveBeenCalled();
input$.next(1);
expect(workerFactorySpy).toHaveBeenCalledWith(0);
sub.unsubscribe();
});
it('constructs as many workers as concurrency allows when the input exceeds the output', () => {
const subscriptionSpy = jasmine.createSpy('subscriptionSpy');
const sub = stubbedWorkerStream.subscribe(subscriptionSpy);
for (let i = 0; i < 20; i++) {
input$.next(i);
}
expect(workerFactorySpy).toHaveBeenCalledTimes(navigator.hardwareConcurrency - 1);
expect(stubbedWorkers[0].postMessage).toHaveBeenCalledWith(jasmine.objectContaining({ kind: 'N', value: 0 }));
sub.unsubscribe();
});
it('shuts down workers when subscriber unsubscribes', () => {
const subscriptionSpy = jasmine.createSpy('subscriptionSpy');
const sub = stubbedWorkerStream.subscribe(subscriptionSpy);
for (let i = 0; i < 20; i++) {
input$.next(i);
}
for (let i = 0; i < navigator.hardwareConcurrency - 1; i++) {
expect(stubbedWorkers[i].terminate).not.toHaveBeenCalled();
}
sub.unsubscribe();
for (let i = 0; i < navigator.hardwareConcurrency - 1; i++) {
expect(stubbedWorkers[i].terminate).toHaveBeenCalledTimes(1);
}
});
it('does not shut down workers when outstanding work remains', () => {
const subscriptionSpy = jasmine.createSpy('subscriptionSpy');
const sub = stubbedWorkerStream.subscribe(subscriptionSpy);
for (let i = 0; i < 20; i++) {
input$.next(i);
}
for (let i = 0; i < navigator.hardwareConcurrency - 1; i++) {
const stubWorker = stubbedWorkers[i];
stubWorker.onmessage!(
new MessageEvent('message', {
data: new Notification('N', i),
}),
);
expect(subscriptionSpy).toHaveBeenCalledWith(i);
stubWorker.onmessage!(
new MessageEvent('message', {
data: new Notification('C'),
}),
);
expect(stubbedWorkers[i].terminate).not.toHaveBeenCalled();
}
sub.unsubscribe();
});
});
describe('with array input', () => {
it('should be able to use array as input', () => {
const workerCount = 7;
const input = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const testWorkerStream$ = fromWorkerPool<number, number>(workerFactorySpy, input, { workerCount });
const subscriptionSpy = jasmine.createSpy('subscriptionSpy');
const sub = testWorkerStream$
.pipe(
reduce((out: number[], res: number) => {
out.push(res);
return out;
}, []),
)
.subscribe(subscriptionSpy);
for (const i of input) {
const stubWorker = stubbedWorkers[i % workerCount];
stubWorker.onmessage!(
new MessageEvent('message', {
data: new Notification('N', i),
}),
);
stubWorker.onmessage!(
new MessageEvent('message', {
data: new Notification('C'),
}),
);
}
expect(subscriptionSpy).toHaveBeenCalledWith([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
sub.unsubscribe();
});
});
describe('with iterator input', () => {
it('should be able to use iterator/generator as input', () => {
const workerCount = 7;
function* generator() {
yield 0;
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
yield 6;
yield 7;
yield 8;
yield 9;
}
const input = generator();
const testWorkerStream$ = fromWorkerPool<number, number>(workerFactorySpy, input, { workerCount });
const subscriptionSpy = jasmine.createSpy('subscriptionSpy');
const sub = testWorkerStream$
.pipe(
reduce((out: number[], res: number) => {
out.push(res);
return out;
}, []),
)
.subscribe(subscriptionSpy);
for (const i of generator()) {
const stubWorker = stubbedWorkers[i % workerCount];
stubWorker.onmessage!(
new MessageEvent('message', {
data: new Notification('N', i),
}),
);
stubWorker.onmessage!(
new MessageEvent('message', {
data: new Notification('C'),
}),
);
}
expect(workerFactorySpy).toHaveBeenCalledTimes(7);
expect(subscriptionSpy).toHaveBeenCalledWith([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
sub.unsubscribe();
});
});
describe('with undefined navigator.hardwareConcurrency', () => {
it('runs a default fallback number of workers', () => {
spyOnProperty(window.navigator, 'hardwareConcurrency').and.returnValue(undefined);
const input = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const testWorkerStream$ = fromWorkerPool<number, number>(workerFactorySpy, input);
const subscriptionSpy = jasmine.createSpy('subscriptionSpy');
const sub = testWorkerStream$.subscribe(subscriptionSpy);
expect(workerFactorySpy).toHaveBeenCalledTimes(3);
sub.unsubscribe();
});
it('runs a configured fallback number of workers', () => {
spyOnProperty(window.navigator, 'hardwareConcurrency').and.returnValue(undefined);
const input = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const testWorkerStream$ = fromWorkerPool<number, number>(workerFactorySpy, input, { fallbackWorkerCount: 2 });
const subscriptionSpy = jasmine.createSpy('subscriptionSpy');
const sub = testWorkerStream$.subscribe(subscriptionSpy);
expect(workerFactorySpy).toHaveBeenCalledTimes(2);
sub.unsubscribe();
});
});
describe('output strategy', () => {
it('[default] outputs results as they are available', fakeAsync(() => {
const workerCount = 7;
const input = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const testWorkerStream$ = fromWorkerPool<number, number>(workerFactorySpy, input, { workerCount });
const subscriptionSpy = jasmine.createSpy('subscriptionSpy');
const sub = testWorkerStream$
.pipe(
reduce((out: number[], res: number) => {
out.push(res);
return out;
}, []),
)
.subscribe(subscriptionSpy);
for (let i = 0; i < input.length; i++) {
setTimeout(() => {
const stubWorker = stubbedWorkers[i % workerCount];
stubWorker.onmessage!(
new MessageEvent('message', {
data: new Notification('N', input[i]),
}),
);
stubWorker.onmessage!(
new MessageEvent('message', {
data: new Notification('C'),
}),
);
}, 10 - i); // output each result in successively less time for each value
}
tick(10);
expect(workerFactorySpy).toHaveBeenCalledTimes(7);
expect(subscriptionSpy).toHaveBeenCalledWith([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]);
sub.unsubscribe();
}));
it('outputs results as specified by custom passed flattening operator', fakeAsync(() => {
const workerCount = 7;
const input = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const operatorSpy = jasmine.createSpy('subscriptionSpy');
function customOperator(outerObservable$: Observable<Observable<number>>): Observable<number> {
return new Observable<number>(subscriber => {
const innerSubs: Subscription[] = [];
const outerSub = outerObservable$.subscribe(innerObservable$ => {
innerSubs.push(
innerObservable$.subscribe(value => {
subscriber.next(value * 2);
operatorSpy();
}),
);
});
return () => {
innerSubs.forEach(s => s.unsubscribe());
outerSub.unsubscribe();
};
});
}
const testWorkerStream$ = fromWorkerPool<number, number>(workerFactorySpy, input, {
workerCount,
flattenOperator: customOperator,
});
const subscriptionSpy = jasmine.createSpy('subscriptionSpy');
const sub = testWorkerStream$
.pipe(
reduce((out: number[], res: number) => {
out.push(res);
return out;
}, []),
)
.subscribe(subscriptionSpy);
for (let i = 0; i < input.length; i++) {
setTimeout(() => {
const stubWorker = stubbedWorkers[i % workerCount];
stubWorker.onmessage!(
new MessageEvent('message', {
data: new Notification('N', input[i]),
}),
);
stubWorker.onmessage!(
new MessageEvent('message', {
data: new Notification('C'),
}),
);
}, 10 - i); // output each result in successively less time for each value
}
tick(10);
expect(subscriptionSpy).toHaveBeenCalledWith([18, 16, 14, 12, 10, 8, 6, 4, 2, 0]);
expect(operatorSpy).toHaveBeenCalledTimes(10);
sub.unsubscribe();
}));
});
}); | the_stack |
import * as SDPUtils from 'sdp';
import { JingleAction, JingleReasonCondition, JingleSessionRole } from '../Constants';
import { NS_JINGLE_ICE_UDP_1 } from '../Namespaces';
import { Jingle, JingleContent, JingleIce, JingleReason } from '../protocol';
import { exportToSDP, importFromSDP } from './sdp/Intermediate';
import {
convertCandidateToIntermediate,
convertIntermediateToCandidate,
convertIntermediateToTransport,
convertRequestToIntermediate
} from './sdp/Protocol';
import BaseSession, { ActionCallback, SessionOpts } from './Session';
import { SessionManagerConfig } from './SessionManager';
export interface ICESessionOpts extends SessionOpts {
maxRelayBandwidth?: number;
iceServers?: RTCIceServer[];
config?: SessionManagerConfig['peerConnectionConfig'];
constraints?: SessionManagerConfig['peerConnectionConstraints'];
}
export default class ICESession extends BaseSession {
public pc!: RTCPeerConnection;
public bitrateLimit = 0;
public maximumBitrate?: number;
public currentBitrate?: number;
public maxRelayBandwidth?: number;
public candidateBuffer: Array<{
sdpMid: string;
candidate: string;
} | null> = [];
public transportType: JingleIce['transportType'] = NS_JINGLE_ICE_UDP_1;
public restartingIce = false;
public usingRelay = false;
private _maybeRestartingIce: any;
constructor(opts: ICESessionOpts) {
super(opts);
this.maxRelayBandwidth = opts.maxRelayBandwidth;
this.pc = this.parent.createPeerConnection(this, {
...opts.config,
iceServers: opts.iceServers
})!;
this.pc.oniceconnectionstatechange = () => {
this.onIceStateChange();
};
this.pc.onicecandidate = e => {
if (e.candidate) {
this.onIceCandidate(e);
} else {
this.onIceEndOfCandidates();
}
};
this.restrictRelayBandwidth();
}
public end(reason: JingleReasonCondition | JingleReason = 'success', silent = false): void {
this.pc.close();
super.end(reason, silent);
}
/* actually do an ice restart */
public async restartIce(): Promise<void> {
// only initiators do an ice-restart to avoid conflicts.
if (!this.isInitiator) {
return;
}
if (this._maybeRestartingIce !== undefined) {
clearTimeout(this._maybeRestartingIce);
}
this.restartingIce = true;
try {
await this.processLocal('restart-ice', async () => {
const offer = await this.pc.createOffer({ iceRestart: true });
// extract new ufrag / pwd, send transport-info with just that.
const json = importFromSDP(offer.sdp!);
this.send(JingleAction.TransportInfo, {
contents: json.media.map<JingleContent>(media => ({
creator: JingleSessionRole.Initiator,
name: media.mid,
transport: convertIntermediateToTransport(media, this.transportType)
})),
sid: this.sid
});
await this.pc.setLocalDescription(offer);
});
} catch (err) {
this._log('error', 'Could not create WebRTC offer', err);
this.end(JingleReasonCondition.FailedTransport, true);
}
}
// set the maximum bitrate. Only supported in Chrome and Firefox right now.
public async setMaximumBitrate(maximumBitrate: number): Promise<void> {
if (this.maximumBitrate) {
// potentially take into account bandwidth restrictions due to using TURN.
maximumBitrate = Math.min(maximumBitrate, this.maximumBitrate);
}
this.currentBitrate = maximumBitrate;
// changes the maximum bandwidth using RTCRtpSender.setParameters.
const sender = this.pc.getSenders().find(s => !!s.track && s.track.kind === 'video');
if (!sender || !sender.getParameters) {
return;
}
try {
await this.processLocal('set-bitrate', async () => {
const parameters = sender.getParameters();
if (!parameters.encodings || !parameters.encodings.length) {
parameters.encodings = [{}];
}
if (maximumBitrate === 0) {
delete parameters.encodings[0].maxBitrate;
} else {
parameters.encodings[0].maxBitrate = maximumBitrate;
}
await sender.setParameters(parameters);
});
} catch (err) {
this._log('error', 'Set maximumBitrate failed', err);
}
}
// ----------------------------------------------------------------
// Jingle action handers
// ----------------------------------------------------------------
protected async onTransportInfo(changes: Jingle, cb: ActionCallback): Promise<void> {
if (
changes.contents &&
changes.contents[0] &&
(changes.contents[0].transport! as JingleIce).gatheringComplete
) {
const candidate = { sdpMid: changes.contents[0].name, candidate: '' };
try {
if (this.pc.signalingState === 'stable') {
await this.pc.addIceCandidate(candidate);
} else {
this.candidateBuffer.push(candidate);
}
} catch (err) {
this._log('debug', 'Could not add null end-of-candidate');
} finally {
cb();
}
return;
}
// detect an ice restart.
if (this.pc.remoteDescription) {
const remoteDescription = this.pc.remoteDescription;
const remoteJSON = importFromSDP(remoteDescription.sdp);
const remoteMedia = remoteJSON.media.find(m => m.mid === changes.contents![0].name);
const currentUsernameFragment = remoteMedia!.iceParameters!.usernameFragment;
const remoteUsernameFragment = (changes.contents![0].transport! as JingleIce)
.usernameFragment;
if (remoteUsernameFragment && currentUsernameFragment !== remoteUsernameFragment) {
for (const [idx, content] of changes.contents!.entries()) {
const transport = content.transport! as JingleIce;
remoteJSON.media[idx].iceParameters = {
password: transport.password!,
usernameFragment: transport.usernameFragment!
};
remoteJSON.media[idx].candidates = [];
}
try {
await this.pc.setRemoteDescription({
type: remoteDescription.type,
sdp: exportToSDP(remoteJSON)
});
await this.processBufferedCandidates();
if (remoteDescription.type === 'offer') {
const answer = await this.pc.createAnswer();
await this.pc.setLocalDescription(answer);
const json = importFromSDP(answer.sdp!);
this.send(JingleAction.TransportInfo, {
contents: json.media.map(media => ({
creator: JingleSessionRole.Initiator,
name: media.mid,
transport: convertIntermediateToTransport(media, this.transportType)
})),
sid: this.sid
});
} else {
this.restartingIce = false;
}
} catch (err) {
this._log('error', 'Could not do remote ICE restart', err);
cb(err);
this.end(JingleReasonCondition.FailedTransport);
return;
}
}
}
const all = (changes.contents || []).map(content => {
const sdpMid = content.name;
const results = ((content.transport! as JingleIce).candidates || []).map(async json => {
const candidate = SDPUtils.writeCandidate(convertCandidateToIntermediate(json));
if (this.pc.remoteDescription && this.pc.signalingState === 'stable') {
try {
await this.pc.addIceCandidate({ sdpMid, candidate });
} catch (err) {
this._log('error', 'Could not add ICE candidate', err);
}
} else {
this.candidateBuffer.push({ sdpMid, candidate });
}
});
return Promise.all(results);
});
try {
await Promise.all(all);
cb();
} catch (err) {
this._log('error', `Could not process transport-info: ${err}`);
cb(err);
}
}
protected async onSessionAccept(changes: Jingle, cb: ActionCallback): Promise<void> {
this.state = 'active';
const json = convertRequestToIntermediate(changes, this.peerRole);
const sdp = exportToSDP(json);
try {
await this.pc.setRemoteDescription({ type: 'answer', sdp });
await this.processBufferedCandidates();
this.parent.emit('accepted', this, undefined);
cb();
} catch (err) {
this._log('error', `Could not process WebRTC answer: ${err}`);
cb({ condition: 'general-error' });
}
}
protected onSessionTerminate(changes: Jingle, cb: ActionCallback): void {
this._log('info', 'Terminating session');
this.pc.close();
super.end(changes.reason, true);
cb();
}
// ----------------------------------------------------------------
// ICE action handers
// ----------------------------------------------------------------
protected onIceCandidate(e: RTCPeerConnectionIceEvent): void {
if (!e.candidate || !e.candidate.candidate) {
return;
}
const candidate = SDPUtils.parseCandidate(e.candidate.candidate);
const jingle: Partial<Jingle> = {
contents: [
{
creator: JingleSessionRole.Initiator,
name: e.candidate.sdpMid!,
transport: {
candidates: [convertIntermediateToCandidate(candidate)],
transportType: this.transportType,
usernameFragment: candidate.usernameFragment
} as JingleIce
}
]
};
this._log('info', 'Discovered new ICE candidate', jingle);
this.send(JingleAction.TransportInfo, jingle);
}
protected onIceEndOfCandidates(): void {
this._log('info', 'ICE end of candidates');
const json = importFromSDP(this.pc.localDescription!.sdp);
const firstMedia = json.media[0];
// signal end-of-candidates with our first media mid/ufrag
this.send(JingleAction.TransportInfo, {
contents: [
{
creator: JingleSessionRole.Initiator,
name: firstMedia.mid,
transport: {
gatheringComplete: true,
transportType: this.transportType,
usernameFragment: firstMedia.iceParameters!.usernameFragment
} as JingleIce
}
]
});
}
protected onIceStateChange(): void {
switch (this.pc.iceConnectionState) {
case 'checking':
this.connectionState = 'connecting';
break;
case 'completed':
case 'connected':
this.connectionState = 'connected';
break;
case 'disconnected':
if (this.pc.signalingState === 'stable') {
this.connectionState = 'interrupted';
} else {
this.connectionState = 'disconnected';
}
if (this.restartingIce) {
this.end(JingleReasonCondition.FailedTransport);
return;
}
this.maybeRestartIce();
break;
case 'failed':
if (this.connectionState === 'failed' || this.restartingIce) {
this.end(JingleReasonCondition.FailedTransport);
return;
}
this.connectionState = 'failed';
this.restartIce();
break;
case 'closed':
this.connectionState = 'disconnected';
if (this.restartingIce) {
this.end(JingleReasonCondition.FailedTransport);
} else {
this.end();
}
break;
}
}
protected async processBufferedCandidates(): Promise<void> {
for (const candidate of this.candidateBuffer) {
try {
await this.pc.addIceCandidate(candidate!);
} catch (err) {
this._log('error', 'Could not add ICE candidate', err);
}
}
this.candidateBuffer = [];
}
/* when using TURN, we might want to restrict the bandwidth
* to the value specified by MAX_RELAY_BANDWIDTH
* in order to prevent sending excessive traffic through
* the TURN server.
*/
private restrictRelayBandwidth(): void {
this.pc.addEventListener('iceconnectionstatechange', async () => {
if (
this.pc.iceConnectionState !== 'completed' &&
this.pc.iceConnectionState !== 'connected'
) {
return;
}
const stats = await this.pc.getStats();
let activeCandidatePair: any;
stats.forEach(report => {
if (report.type === 'transport') {
activeCandidatePair = (stats as any).get(report.selectedCandidatePairId);
}
});
// Fallback for Firefox.
if (!activeCandidatePair) {
stats.forEach(report => {
if (report.type === 'candidate-pair' && report.selected) {
activeCandidatePair = report;
}
});
}
if (!activeCandidatePair) {
return;
}
let isRelay = false;
let localCandidateType = '';
let remoteCandidateType = '';
if (activeCandidatePair.remoteCandidateId) {
const remoteCandidate = (stats as any).get(activeCandidatePair.remoteCandidateId);
if (remoteCandidate) {
remoteCandidateType = remoteCandidate.candidateType;
}
}
if (activeCandidatePair.localCandidateId) {
const localCandidate = (stats as any).get(activeCandidatePair.localCandidateId);
if (localCandidate) {
localCandidateType = localCandidate.candidateType;
}
}
if (localCandidateType === 'relay' || remoteCandidateType === 'relay') {
isRelay = true;
}
this.usingRelay = isRelay;
this.parent.emit('iceConnectionType', this, {
localCandidateType,
relayed: isRelay,
remoteCandidateType
});
if (isRelay && this.maxRelayBandwidth !== undefined) {
this.maximumBitrate = this.maxRelayBandwidth;
if (this.currentBitrate) {
this.setMaximumBitrate(Math.min(this.currentBitrate, this.maximumBitrate));
} else {
this.setMaximumBitrate(this.maximumBitrate);
}
}
});
}
/* determine whether an ICE restart is in order
* when transitioning to disconnected. Strategy is
* 'wait 2 seconds for things to repair themselves'
* 'maybe check if bytes are sent/received' by comparing
* getStats measurements
*/
private maybeRestartIce(): void {
// only initiators do an ice-restart to avoid conflicts.
if (!this.isInitiator) {
return;
}
if (this._maybeRestartingIce !== undefined) {
clearTimeout(this._maybeRestartingIce);
}
this._maybeRestartingIce = setTimeout(() => {
this._maybeRestartingIce = undefined;
if (this.pc.iceConnectionState === 'disconnected') {
this.restartIce();
}
}, 2000);
}
} | the_stack |
import * as path from 'path';
import {
CallExpression,
ClassDeclaration,
Decorator,
Identifier,
ImportClause,
ImportDeclaration,
ImportSpecifier,
NamedImports,
Node,
NodeArray,
ObjectLiteralElement, // tslint:disable-line: no-unused-variable
ObjectLiteralExpression,
PropertyAssignment,
ArrayLiteralExpression,
ScriptTarget,
SourceFile,
StringLiteral,
SyntaxKind,
createSourceFile,
} from 'typescript';
import { rangeReplace, stringSplice } from './helpers';
export function getTypescriptSourceFile(filePath: string, fileContent: string, languageVersion: ScriptTarget = ScriptTarget.Latest, setParentNodes: boolean = false): SourceFile {
return createSourceFile(filePath, fileContent, languageVersion, setParentNodes);
}
export function removeDecorators(fileName: string, source: string): string {
const sourceFile = createSourceFile(fileName, source, ScriptTarget.Latest);
const decorators = findNodes(sourceFile, sourceFile, SyntaxKind.Decorator, true);
decorators.sort((a, b) => b.pos - a.pos);
decorators.forEach(d => {
source = source.slice(0, d.pos) + source.slice(d.end);
});
return source;
}
export function findNodes(sourceFile: SourceFile, node: Node, kind: SyntaxKind, keepGoing = false): Node[] {
if (node.kind === kind && !keepGoing) {
return [node];
}
return node.getChildren(sourceFile).reduce((result, n) => {
return result.concat(findNodes(sourceFile, n, kind, keepGoing));
}, node.kind === kind ? [node] : []);
}
export function replaceNode(filePath: string, fileContent: string, node: Node, replacement: string): string {
const sourceFile = getTypescriptSourceFile(filePath, fileContent, ScriptTarget.Latest, false);
const startIndex = node.getStart(sourceFile);
const endIndex = node.getEnd();
const modifiedContent = rangeReplace(fileContent, startIndex, endIndex, replacement);
return modifiedContent;
}
export function removeNode(filePath: string, fileContent: string, node: Node) {
const sourceFile = getTypescriptSourceFile(filePath, fileContent, ScriptTarget.Latest, false);
const startIndex = node.getStart(sourceFile);
const endIndex = node.getEnd();
const modifiedContent = rangeReplace(fileContent, startIndex, endIndex, '');
return modifiedContent;
}
export function getNodeStringContent(sourceFile: SourceFile, node: Node) {
return sourceFile.getFullText().substring(node.getStart(sourceFile), node.getEnd());
}
export function appendAfter(source: string, node: Node, toAppend: string): string {
return stringSplice(source, node.getEnd(), 0, toAppend);
}
export function appendEmpty(source: string, position: number, toAppend: string): string {
return stringSplice(source, position, 0, toAppend);
}
export function appendBefore(filePath: string, fileContent: string, node: Node, toAppend: string): string {
const sourceFile = getTypescriptSourceFile(filePath, fileContent, ScriptTarget.Latest, false);
return stringSplice(fileContent, node.getStart(sourceFile), 0, toAppend);
}
export function insertNamedImportIfNeeded(filePath: string, fileContent: string, namedImport: string, fromModule: string) {
const sourceFile = getTypescriptSourceFile(filePath, fileContent, ScriptTarget.Latest, false);
const allImports = findNodes(sourceFile, sourceFile, SyntaxKind.ImportDeclaration);
const maybeImports = allImports.filter((node: ImportDeclaration) => {
return node.moduleSpecifier.kind === SyntaxKind.StringLiteral
&& (node.moduleSpecifier as StringLiteral).text === fromModule;
}).filter((node: ImportDeclaration) => {
// Remove import statements that are either `import 'XYZ'` or `import * as X from 'XYZ'`.
const clause = node.importClause as ImportClause;
if (!clause || clause.name || !clause.namedBindings) {
return false;
}
return clause.namedBindings.kind === SyntaxKind.NamedImports;
}).map((node: ImportDeclaration) => {
return (node.importClause as ImportClause).namedBindings as NamedImports;
});
if (maybeImports.length) {
// There's an `import {A, B, C} from 'modulePath'`.
// Find if it's in either imports. If so, just return; nothing to do.
const hasImportAlready = maybeImports.some((node: NamedImports) => {
return node.elements.some((element: ImportSpecifier) => {
return element.name.text === namedImport;
});
});
if (hasImportAlready) {
// it's already imported, so just return the original text
return fileContent;
}
// Just pick the first one and insert at the end of its identifier list.
fileContent = appendAfter(fileContent, maybeImports[0].elements[maybeImports[0].elements.length - 1], `, ${namedImport}`);
} else {
// Find the last import and insert after.
fileContent = appendAfter(fileContent, allImports[allImports.length - 1],
`\nimport { ${namedImport} } from '${fromModule}';`);
}
return fileContent;
}
export function replaceNamedImport(filePath: string, fileContent: string, namedImportOriginal: string, namedImportReplacement: string) {
const sourceFile = getTypescriptSourceFile(filePath, fileContent, ScriptTarget.Latest, false);
const allImports = findNodes(sourceFile, sourceFile, SyntaxKind.ImportDeclaration);
let modifiedContent = fileContent;
allImports.filter((node: ImportDeclaration) => {
if (node.importClause && node.importClause.namedBindings) {
return node.importClause.namedBindings.kind === SyntaxKind.NamedImports;
}
}).map((importDeclaration: ImportDeclaration) => {
return (importDeclaration.importClause as ImportClause).namedBindings as NamedImports;
}).forEach((namedImport: NamedImports) => {
return namedImport.elements.forEach((element: ImportSpecifier) => {
if (element.name.text === namedImportOriginal) {
modifiedContent = replaceNode(filePath, modifiedContent, element, namedImportReplacement);
}
});
});
return modifiedContent;
}
export function replaceImportModuleSpecifier(filePath: string, fileContent: string, moduleSpecifierOriginal: string, moduleSpecifierReplacement: string) {
const sourceFile = getTypescriptSourceFile(filePath, fileContent, ScriptTarget.Latest, false);
const allImports = findNodes(sourceFile, sourceFile, SyntaxKind.ImportDeclaration);
let modifiedContent = fileContent;
allImports.forEach((node: ImportDeclaration) => {
if (node.moduleSpecifier.kind === SyntaxKind.StringLiteral && (node.moduleSpecifier as StringLiteral).text === moduleSpecifierOriginal) {
modifiedContent = replaceNode(filePath, modifiedContent, node.moduleSpecifier, `'${moduleSpecifierReplacement}'`);
}
});
return modifiedContent;
}
export function checkIfFunctionIsCalled(filePath: string, fileContent: string, functionName: string) {
const sourceFile = getTypescriptSourceFile(filePath, fileContent, ScriptTarget.Latest, false);
const allCalls = findNodes(sourceFile, sourceFile, SyntaxKind.CallExpression, true) as CallExpression[];
const functionCallList = allCalls.filter(call => call.expression && call.expression.kind === SyntaxKind.Identifier && (call.expression as Identifier).text === functionName);
return functionCallList.length > 0;
}
export function getClassDeclarations(sourceFile: SourceFile) {
return findNodes(sourceFile, sourceFile, SyntaxKind.ClassDeclaration, true) as ClassDeclaration[];
}
export function getNgModuleClassName(filePath: string, fileContent: string) {
const ngModuleSourceFile = getTypescriptSourceFile(filePath, fileContent);
const classDeclarations = getClassDeclarations(ngModuleSourceFile);
// find the class with NgModule decorator;
const classNameList: string[] = [];
classDeclarations.forEach(classDeclaration => {
if (classDeclaration && classDeclaration.decorators) {
classDeclaration.decorators.forEach(decorator => {
if (decorator.expression && (decorator.expression as CallExpression).expression && ((decorator.expression as CallExpression).expression as Identifier).text === NG_MODULE_DECORATOR_TEXT) {
const className = (classDeclaration.name as Identifier).text;
classNameList.push(className);
}
});
}
});
if (classNameList.length === 0) {
throw new Error(`Could not find a class declaration in ${filePath}`);
}
if (classNameList.length > 1) {
throw new Error(`Multiple class declarations with NgModule in ${filePath}. The correct class to use could not be determined.`);
}
return classNameList[0];
}
export function getNgModuleDecorator(fileName: string, sourceFile: SourceFile) {
const ngModuleDecorators: Decorator[] = [];
const classDeclarations = getClassDeclarations(sourceFile);
classDeclarations.forEach(classDeclaration => {
if (classDeclaration && classDeclaration.decorators) {
classDeclaration.decorators.forEach(decorator => {
if (decorator.expression && (decorator.expression as CallExpression).expression && ((decorator.expression as CallExpression).expression as Identifier).text === NG_MODULE_DECORATOR_TEXT) {
ngModuleDecorators.push(decorator);
}
});
}
});
if (ngModuleDecorators.length === 0) {
throw new Error(`Could not find an "NgModule" decorator in ${fileName}`);
}
if (ngModuleDecorators.length > 1) {
throw new Error(`Multiple "NgModule" decorators found in ${fileName}. The correct one to use could not be determined`);
}
return ngModuleDecorators[0];
}
export function getNgModuleObjectLiteralArg(decorator: Decorator) {
const ngModuleArgs = (decorator.expression as CallExpression).arguments;
if (!ngModuleArgs || ngModuleArgs.length === 0 || ngModuleArgs.length > 1) {
throw new Error(`Invalid NgModule Argument`);
}
return ngModuleArgs[0] as ObjectLiteralExpression;
}
export function findObjectLiteralElementByName(properties: NodeArray<ObjectLiteralElement>, identifierToLookFor: string) {
return properties.filter((propertyNode) => {
return propertyNode && (propertyNode as PropertyAssignment).name && ((propertyNode as PropertyAssignment).name as Identifier).text === identifierToLookFor;
})[0];
}
export function appendNgModuleDeclaration(filePath: string, fileContent: string, declaration: string, ): string {
const sourceFile = getTypescriptSourceFile(filePath, fileContent, ScriptTarget.Latest, false);
const decorator = getNgModuleDecorator(path.basename(filePath), sourceFile);
const obj = getNgModuleObjectLiteralArg(decorator);
const properties = (findObjectLiteralElementByName(obj.properties, 'declarations') as PropertyAssignment);
const declarations = (properties.initializer as ArrayLiteralExpression).elements;
if (declarations.length === 0) {
return appendEmpty(fileContent, declarations['end'], declaration);
} else {
return appendAfter(fileContent, declarations[declarations.length - 1], `,\n ${declaration}`);
}
}
export function appendNgModuleProvider(filePath: string, fileContent: string, declaration: string): string {
const sourceFile = getTypescriptSourceFile(filePath, fileContent, ScriptTarget.Latest, false);
const decorator = getNgModuleDecorator(path.basename(filePath), sourceFile);
const obj = getNgModuleObjectLiteralArg(decorator);
const properties = (findObjectLiteralElementByName(obj.properties, 'providers') as PropertyAssignment);
const providers = (properties.initializer as ArrayLiteralExpression).elements;
if (providers.length === 0) {
return appendEmpty(fileContent, providers['end'], declaration);
} else {
return appendAfter(fileContent, providers[providers.length - 1], `,\n ${declaration}`);
}
}
export function appendNgModuleExports(filePath: string, fileContent: string, declaration: string): string {
const sourceFile = getTypescriptSourceFile(filePath, fileContent, ScriptTarget.Latest, false);
const decorator = getNgModuleDecorator(path.basename(filePath), sourceFile);
const obj = getNgModuleObjectLiteralArg(decorator);
const properties = (findObjectLiteralElementByName(obj.properties, 'exports') as PropertyAssignment);
const exportsProp = (properties.initializer as ArrayLiteralExpression).elements;
if (exportsProp.length === 0) {
return appendEmpty(fileContent, exportsProp['end'], declaration);
} else {
return appendAfter(fileContent, exportsProp[exportsProp.length - 1], `,\n ${declaration}`);
}
}
export const NG_MODULE_DECORATOR_TEXT = 'NgModule'; | the_stack |
import { alert } from 'vs/base/browser/ui/aria/aria';
import { asArray, isNonEmptyArray } from 'vs/base/common/arrays';
import { CancellationToken, CancellationTokenSource } from 'vs/base/common/cancellation';
import { onUnexpectedExternalError } from 'vs/base/common/errors';
import { Iterable } from 'vs/base/common/iterator';
import { IDisposable } from 'vs/base/common/lifecycle';
import { LinkedList } from 'vs/base/common/linkedList';
import { assertType } from 'vs/base/common/types';
import { URI } from 'vs/base/common/uri';
import { CodeEditorStateFlag, EditorStateCancellationTokenSource, TextModelCancellationTokenSource } from 'vs/editor/contrib/editorState/browser/editorState';
import { IActiveCodeEditor, isCodeEditor } from 'vs/editor/browser/editorBrowser';
import { ServicesAccessor } from 'vs/editor/browser/editorExtensions';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { Selection } from 'vs/editor/common/core/selection';
import { ScrollType } from 'vs/editor/common/editorCommon';
import { ITextModel } from 'vs/editor/common/model';
import { ISingleEditOperation } from 'vs/editor/common/core/editOperation';
import { DocumentFormattingEditProvider, DocumentRangeFormattingEditProvider, FormattingOptions, TextEdit } from 'vs/editor/common/languages';
import { IEditorWorkerService } from 'vs/editor/common/services/editorWorker';
import { ITextModelService } from 'vs/editor/common/services/resolverService';
import { FormattingEdit } from 'vs/editor/contrib/format/browser/formattingEdit';
import * as nls from 'vs/nls';
import { CommandsRegistry } from 'vs/platform/commands/common/commands';
import { ExtensionIdentifier } from 'vs/platform/extensions/common/extensions';
import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation';
import { IProgress } from 'vs/platform/progress/common/progress';
import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures';
import { LanguageFeatureRegistry } from 'vs/editor/common/languageFeatureRegistry';
export function alertFormattingEdits(edits: ISingleEditOperation[]): void {
edits = edits.filter(edit => edit.range);
if (!edits.length) {
return;
}
let { range } = edits[0];
for (let i = 1; i < edits.length; i++) {
range = Range.plusRange(range, edits[i].range);
}
const { startLineNumber, endLineNumber } = range;
if (startLineNumber === endLineNumber) {
if (edits.length === 1) {
alert(nls.localize('hint11', "Made 1 formatting edit on line {0}", startLineNumber));
} else {
alert(nls.localize('hintn1', "Made {0} formatting edits on line {1}", edits.length, startLineNumber));
}
} else {
if (edits.length === 1) {
alert(nls.localize('hint1n', "Made 1 formatting edit between lines {0} and {1}", startLineNumber, endLineNumber));
} else {
alert(nls.localize('hintnn', "Made {0} formatting edits between lines {1} and {2}", edits.length, startLineNumber, endLineNumber));
}
}
}
export function getRealAndSyntheticDocumentFormattersOrdered(
documentFormattingEditProvider: LanguageFeatureRegistry<DocumentFormattingEditProvider>,
documentRangeFormattingEditProvider: LanguageFeatureRegistry<DocumentRangeFormattingEditProvider>,
model: ITextModel
): DocumentFormattingEditProvider[] {
const result: DocumentFormattingEditProvider[] = [];
const seen = new Set<string>();
// (1) add all document formatter
const docFormatter = documentFormattingEditProvider.ordered(model);
for (const formatter of docFormatter) {
result.push(formatter);
if (formatter.extensionId) {
seen.add(ExtensionIdentifier.toKey(formatter.extensionId));
}
}
// (2) add all range formatter as document formatter (unless the same extension already did that)
const rangeFormatter = documentRangeFormattingEditProvider.ordered(model);
for (const formatter of rangeFormatter) {
if (formatter.extensionId) {
if (seen.has(ExtensionIdentifier.toKey(formatter.extensionId))) {
continue;
}
seen.add(ExtensionIdentifier.toKey(formatter.extensionId));
}
result.push({
displayName: formatter.displayName,
extensionId: formatter.extensionId,
provideDocumentFormattingEdits(model, options, token) {
return formatter.provideDocumentRangeFormattingEdits(model, model.getFullModelRange(), options, token);
}
});
}
return result;
}
export const enum FormattingMode {
Explicit = 1,
Silent = 2
}
export interface IFormattingEditProviderSelector {
<T extends (DocumentFormattingEditProvider | DocumentRangeFormattingEditProvider)>(formatter: T[], document: ITextModel, mode: FormattingMode): Promise<T | undefined>;
}
export abstract class FormattingConflicts {
private static readonly _selectors = new LinkedList<IFormattingEditProviderSelector>();
static setFormatterSelector(selector: IFormattingEditProviderSelector): IDisposable {
const remove = FormattingConflicts._selectors.unshift(selector);
return { dispose: remove };
}
static async select<T extends (DocumentFormattingEditProvider | DocumentRangeFormattingEditProvider)>(formatter: T[], document: ITextModel, mode: FormattingMode): Promise<T | undefined> {
if (formatter.length === 0) {
return undefined;
}
const selector = Iterable.first(FormattingConflicts._selectors);
if (selector) {
return await selector(formatter, document, mode);
}
return undefined;
}
}
export async function formatDocumentRangesWithSelectedProvider(
accessor: ServicesAccessor,
editorOrModel: ITextModel | IActiveCodeEditor,
rangeOrRanges: Range | Range[],
mode: FormattingMode,
progress: IProgress<DocumentRangeFormattingEditProvider>,
token: CancellationToken
): Promise<void> {
const instaService = accessor.get(IInstantiationService);
const { documentRangeFormattingEditProvider: documentRangeFormattingEditProviderRegistry } = accessor.get(ILanguageFeaturesService);
const model = isCodeEditor(editorOrModel) ? editorOrModel.getModel() : editorOrModel;
const provider = documentRangeFormattingEditProviderRegistry.ordered(model);
const selected = await FormattingConflicts.select(provider, model, mode);
if (selected) {
progress.report(selected);
await instaService.invokeFunction(formatDocumentRangesWithProvider, selected, editorOrModel, rangeOrRanges, token);
}
}
export async function formatDocumentRangesWithProvider(
accessor: ServicesAccessor,
provider: DocumentRangeFormattingEditProvider,
editorOrModel: ITextModel | IActiveCodeEditor,
rangeOrRanges: Range | Range[],
token: CancellationToken
): Promise<boolean> {
const workerService = accessor.get(IEditorWorkerService);
let model: ITextModel;
let cts: CancellationTokenSource;
if (isCodeEditor(editorOrModel)) {
model = editorOrModel.getModel();
cts = new EditorStateCancellationTokenSource(editorOrModel, CodeEditorStateFlag.Value | CodeEditorStateFlag.Position, undefined, token);
} else {
model = editorOrModel;
cts = new TextModelCancellationTokenSource(editorOrModel, token);
}
// make sure that ranges don't overlap nor touch each other
const ranges: Range[] = [];
let len = 0;
for (const range of asArray(rangeOrRanges).sort(Range.compareRangesUsingStarts)) {
if (len > 0 && Range.areIntersectingOrTouching(ranges[len - 1], range)) {
ranges[len - 1] = Range.fromPositions(ranges[len - 1].getStartPosition(), range.getEndPosition());
} else {
len = ranges.push(range);
}
}
const computeEdits = async (range: Range) => {
return (await provider.provideDocumentRangeFormattingEdits(
model,
range,
model.getFormattingOptions(),
cts.token
)) || [];
};
const hasIntersectingEdit = (a: TextEdit[], b: TextEdit[]) => {
if (!a.length || !b.length) {
return false;
}
// quick exit if the list of ranges are completely unrelated [O(n)]
const mergedA = a.reduce((acc, val) => { return Range.plusRange(acc, val.range); }, a[0].range);
if (!b.some(x => { return Range.intersectRanges(mergedA, x.range); })) {
return false;
}
// fallback to a complete check [O(n^2)]
for (const edit of a) {
for (const otherEdit of b) {
if (Range.intersectRanges(edit.range, otherEdit.range)) {
return true;
}
}
}
return false;
};
const allEdits: TextEdit[] = [];
const rawEditsList: TextEdit[][] = [];
try {
for (const range of ranges) {
if (cts.token.isCancellationRequested) {
return true;
}
rawEditsList.push(await computeEdits(range));
}
for (let i = 0; i < ranges.length; ++i) {
for (let j = i + 1; j < ranges.length; ++j) {
if (cts.token.isCancellationRequested) {
return true;
}
if (hasIntersectingEdit(rawEditsList[i], rawEditsList[j])) {
// Merge ranges i and j into a single range, recompute the associated edits
const mergedRange = Range.plusRange(ranges[i], ranges[j]);
const edits = await computeEdits(mergedRange);
ranges.splice(j, 1);
ranges.splice(i, 1);
ranges.push(mergedRange);
rawEditsList.splice(j, 1);
rawEditsList.splice(i, 1);
rawEditsList.push(edits);
// Restart scanning
i = 0;
j = 0;
}
}
}
for (const rawEdits of rawEditsList) {
if (cts.token.isCancellationRequested) {
return true;
}
const minimalEdits = await workerService.computeMoreMinimalEdits(model.uri, rawEdits);
if (minimalEdits) {
allEdits.push(...minimalEdits);
}
}
} finally {
cts.dispose();
}
if (allEdits.length === 0) {
return false;
}
if (isCodeEditor(editorOrModel)) {
// use editor to apply edits
FormattingEdit.execute(editorOrModel, allEdits, true);
alertFormattingEdits(allEdits);
editorOrModel.revealPositionInCenterIfOutsideViewport(editorOrModel.getPosition(), ScrollType.Immediate);
} else {
// use model to apply edits
const [{ range }] = allEdits;
const initialSelection = new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
model.pushEditOperations([initialSelection], allEdits.map(edit => {
return {
text: edit.text,
range: Range.lift(edit.range),
forceMoveMarkers: true
};
}), undoEdits => {
for (const { range } of undoEdits) {
if (Range.areIntersectingOrTouching(range, initialSelection)) {
return [new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn)];
}
}
return null;
});
}
return true;
}
export async function formatDocumentWithSelectedProvider(
accessor: ServicesAccessor,
editorOrModel: ITextModel | IActiveCodeEditor,
mode: FormattingMode,
progress: IProgress<DocumentFormattingEditProvider>,
token: CancellationToken
): Promise<void> {
const instaService = accessor.get(IInstantiationService);
const languageFeaturesService = accessor.get(ILanguageFeaturesService);
const model = isCodeEditor(editorOrModel) ? editorOrModel.getModel() : editorOrModel;
const provider = getRealAndSyntheticDocumentFormattersOrdered(languageFeaturesService.documentFormattingEditProvider, languageFeaturesService.documentRangeFormattingEditProvider, model);
const selected = await FormattingConflicts.select(provider, model, mode);
if (selected) {
progress.report(selected);
await instaService.invokeFunction(formatDocumentWithProvider, selected, editorOrModel, mode, token);
}
}
export async function formatDocumentWithProvider(
accessor: ServicesAccessor,
provider: DocumentFormattingEditProvider,
editorOrModel: ITextModel | IActiveCodeEditor,
mode: FormattingMode,
token: CancellationToken
): Promise<boolean> {
const workerService = accessor.get(IEditorWorkerService);
let model: ITextModel;
let cts: CancellationTokenSource;
if (isCodeEditor(editorOrModel)) {
model = editorOrModel.getModel();
cts = new EditorStateCancellationTokenSource(editorOrModel, CodeEditorStateFlag.Value | CodeEditorStateFlag.Position, undefined, token);
} else {
model = editorOrModel;
cts = new TextModelCancellationTokenSource(editorOrModel, token);
}
let edits: TextEdit[] | undefined;
try {
const rawEdits = await provider.provideDocumentFormattingEdits(
model,
model.getFormattingOptions(),
cts.token
);
edits = await workerService.computeMoreMinimalEdits(model.uri, rawEdits);
if (cts.token.isCancellationRequested) {
return true;
}
} finally {
cts.dispose();
}
if (!edits || edits.length === 0) {
return false;
}
if (isCodeEditor(editorOrModel)) {
// use editor to apply edits
FormattingEdit.execute(editorOrModel, edits, mode !== FormattingMode.Silent);
if (mode !== FormattingMode.Silent) {
alertFormattingEdits(edits);
editorOrModel.revealPositionInCenterIfOutsideViewport(editorOrModel.getPosition(), ScrollType.Immediate);
}
} else {
// use model to apply edits
const [{ range }] = edits;
const initialSelection = new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn);
model.pushEditOperations([initialSelection], edits.map(edit => {
return {
text: edit.text,
range: Range.lift(edit.range),
forceMoveMarkers: true
};
}), undoEdits => {
for (const { range } of undoEdits) {
if (Range.areIntersectingOrTouching(range, initialSelection)) {
return [new Selection(range.startLineNumber, range.startColumn, range.endLineNumber, range.endColumn)];
}
}
return null;
});
}
return true;
}
export async function getDocumentRangeFormattingEditsUntilResult(
workerService: IEditorWorkerService,
languageFeaturesService: ILanguageFeaturesService,
model: ITextModel,
range: Range,
options: FormattingOptions,
token: CancellationToken
): Promise<TextEdit[] | undefined> {
const providers = languageFeaturesService.documentRangeFormattingEditProvider.ordered(model);
for (const provider of providers) {
const rawEdits = await Promise.resolve(provider.provideDocumentRangeFormattingEdits(model, range, options, token)).catch(onUnexpectedExternalError);
if (isNonEmptyArray(rawEdits)) {
return await workerService.computeMoreMinimalEdits(model.uri, rawEdits);
}
}
return undefined;
}
export async function getDocumentFormattingEditsUntilResult(
workerService: IEditorWorkerService,
languageFeaturesService: ILanguageFeaturesService,
model: ITextModel,
options: FormattingOptions,
token: CancellationToken
): Promise<TextEdit[] | undefined> {
const providers = getRealAndSyntheticDocumentFormattersOrdered(languageFeaturesService.documentFormattingEditProvider, languageFeaturesService.documentRangeFormattingEditProvider, model);
for (const provider of providers) {
const rawEdits = await Promise.resolve(provider.provideDocumentFormattingEdits(model, options, token)).catch(onUnexpectedExternalError);
if (isNonEmptyArray(rawEdits)) {
return await workerService.computeMoreMinimalEdits(model.uri, rawEdits);
}
}
return undefined;
}
export function getOnTypeFormattingEdits(
workerService: IEditorWorkerService,
languageFeaturesService: ILanguageFeaturesService,
model: ITextModel,
position: Position,
ch: string,
options: FormattingOptions,
token: CancellationToken
): Promise<TextEdit[] | null | undefined> {
const providers = languageFeaturesService.onTypeFormattingEditProvider.ordered(model);
if (providers.length === 0) {
return Promise.resolve(undefined);
}
if (providers[0].autoFormatTriggerCharacters.indexOf(ch) < 0) {
return Promise.resolve(undefined);
}
return Promise.resolve(providers[0].provideOnTypeFormattingEdits(model, position, ch, options, token)).catch(onUnexpectedExternalError).then(edits => {
return workerService.computeMoreMinimalEdits(model.uri, edits);
});
}
CommandsRegistry.registerCommand('_executeFormatRangeProvider', async function (accessor, ...args) {
const [resource, range, options] = args;
assertType(URI.isUri(resource));
assertType(Range.isIRange(range));
const resolverService = accessor.get(ITextModelService);
const workerService = accessor.get(IEditorWorkerService);
const languageFeaturesService = accessor.get(ILanguageFeaturesService);
const reference = await resolverService.createModelReference(resource);
try {
return getDocumentRangeFormattingEditsUntilResult(workerService, languageFeaturesService, reference.object.textEditorModel, Range.lift(range), options, CancellationToken.None);
} finally {
reference.dispose();
}
});
CommandsRegistry.registerCommand('_executeFormatDocumentProvider', async function (accessor, ...args) {
const [resource, options] = args;
assertType(URI.isUri(resource));
const resolverService = accessor.get(ITextModelService);
const workerService = accessor.get(IEditorWorkerService);
const languageFeaturesService = accessor.get(ILanguageFeaturesService);
const reference = await resolverService.createModelReference(resource);
try {
return getDocumentFormattingEditsUntilResult(workerService, languageFeaturesService, reference.object.textEditorModel, options, CancellationToken.None);
} finally {
reference.dispose();
}
});
CommandsRegistry.registerCommand('_executeFormatOnTypeProvider', async function (accessor, ...args) {
const [resource, position, ch, options] = args;
assertType(URI.isUri(resource));
assertType(Position.isIPosition(position));
assertType(typeof ch === 'string');
const resolverService = accessor.get(ITextModelService);
const workerService = accessor.get(IEditorWorkerService);
const languageFeaturesService = accessor.get(ILanguageFeaturesService);
const reference = await resolverService.createModelReference(resource);
try {
return getOnTypeFormattingEdits(workerService, languageFeaturesService, reference.object.textEditorModel, Position.lift(position), ch, options, CancellationToken.None);
} finally {
reference.dispose();
}
}); | the_stack |
import * as React from "react";
import { ComponentContext } from "./component-context";
import { Debounce } from "./debounce";
import { FieldBase, DynamicFormNode, BreadcumbComponentType, FormIncludes, BreadcumbNode } from "./types";
import { ComponentRegistry } from "./component-registry";
import { FormStateBuilder } from "./form-state-builder";
import { FieldsExtender } from "./fields-extender";
import { traverse, hasValidationErrorInTree } from "./utils";
const Fragment = React.Fragment;
const componentMarginTop = "16px";
type FormProps = {
values: any;
fields: Array<FieldBase & { [key: string]: any }>;
debug?: boolean | "value" | "state" | "value-raw";
rootName: string;
componentRegistry: ComponentRegistry;
breadcumbComponentType: BreadcumbComponentType;
plugins: any;
includes: FormIncludes;
onChange?: (data: () => any) => void;
onPathChange?: (path: string) => void;
onDebouncedChange?: () => void;
};
type FormState = {
path: string;
doc: any;
rawDoc: any;
docNeedNormalization: boolean;
fields: Array<any>; //we're going to use the fields from the state instead of the fields from props - it can't mutate
renderError: string | null;
};
export class HoForm extends React.Component<FormProps, FormState> {
currentNode: DynamicFormNode<FieldBase> | null;
root: DynamicFormNode<FieldBase>;
cache: any = {};
stateBuilder: FormStateBuilder;
forceUpdateThis: () => void;
constructor(props: FormProps) {
super(props);
this.stateBuilder = new FormStateBuilder(this.props.componentRegistry, props.includes);
const fieldsExtender = new FieldsExtender(this.props.componentRegistry, this.props.includes);
fieldsExtender.extendFields(props.fields);
Object.keys(props.includes).forEach(includeKey => {
fieldsExtender.extendFields(props.includes[includeKey]);
});
let formState = JSON.parse(JSON.stringify(props.values || {}));
this.stateBuilder.makeRootState(props.fields, formState);
let root = {
field: {
key: "root",
type: "root"
},
state: null,
parent: null /*: ?DynamicFormNode<FieldBase>*/
};
this.root = root;
this.currentNode = root;
this.state = {
rawDoc: props.values,
doc: formState,
docNeedNormalization: true,
path: "ROOT/",
fields: props.fields,
renderError: null
};
this.forceUpdateThis = () => {
this.forceUpdate();
if (this.props.onDebouncedChange) {
this.props.onDebouncedChange();
}
};
this.getFormDocClone = this.getFormDocClone.bind(this);
}
static getDerivedStateFromProps(props: FormProps, state: FormState) {
if (props.values != state.rawDoc) {
return { documentNeedNormalization: true, rawDoc: props.values, document: props.values };
} else {
return null;
}
}
normalizeDocSilently() {
if (this.state.docNeedNormalization) {
let formState = JSON.parse(JSON.stringify(this.props.values || {}));
this.stateBuilder.makeRootState(this.state.fields, formState);
const silentUpdate = (s: any, document: any) => {
s.doc = document;
s.docNeedNormalization = false;
};
silentUpdate(this.state, formState);
}
}
componentDidCatch(error: Error, info: React.ErrorInfo) {
this.setState({ renderError: error.message });
console.warn(error, info);
}
setPath(node: DynamicFormNode<FieldBase>) {
const path = this.buildDisplayPath(node);
if (path != this.state.path) {
this.currentNode = node;
this.setState({ path: this.buildDisplayPath(node) });
if (this.props.onPathChange) {
this.props.onPathChange(path);
}
}
}
buildDisplayPath(currentNode: DynamicFormNode<FieldBase> | null): string {
if (currentNode == null) return "";
let path = "";
let nodes = [];
let nodeLevel = 0;
do {
if (currentNode == null) break;
nodes.push(currentNode);
if (currentNode === this.root) {
path = "ROOT/" + path;
} else {
let componentProplessInstace = this.props.componentRegistry.getProplessInstance(currentNode.field.type);
if (componentProplessInstace) {
let fragment = componentProplessInstace.buildDisplayPathFragment(currentNode, nodeLevel++, nodes);
if (fragment) {
path = fragment + "/" + path;
}
} else {
throw new Error("Could not find component of type " + currentNode.field.type);
}
}
if (currentNode.parent == null) break;
else {
currentNode = currentNode.parent;
}
} while (true);
return path;
}
crawl() {
//this.stateValidator.resetValidation();
this.crawlLevel({
fields: this.state.fields,
state: this.state.doc,
parent: this.root
});
}
isValid(): boolean {
this.crawl();
(window as any).formstate = this.state;
const hasErrors = hasValidationErrorInTree(this.state.doc);
return !hasErrors;
}
getValues(): any {
return JSON.parse(JSON.stringify(this.state.doc));
}
/**
* Crawl a level of components
* Can be used recursively when called by a component
*
* @field - the parent field config of the level
* @state - the level state
* @parent - the previous renderLevel context object
*/
crawlLevel({
fields,
state,
parent
}: {
fields: Array<FieldBase> | null;
state: any;
parent: DynamicFormNode<FieldBase>;
}) {
if (this.props.debug) console.log("CRAWL LEVEL");
(fields || []).forEach((childField: FieldBase) => {
let data = { field: childField, state: state, parent };
let field = this.crawlField(data);
if (this.props.debug) {
console.log("FIELD", data, field);
console.log(this.buildDisplayPath(data));
}
});
}
crawlField(node: DynamicFormNode<FieldBase>) {
const { field } = node;
let component = this.props.componentRegistry.get(field.type);
try {
if (component == null) throw new Error("Could not find component of type " + field.type);
node.state = component.proplessInstance.allocateStateLevel(field, node.state, this.state.doc);
component.proplessInstance.crawlComponent({ form: this, node });
} catch (e) {
console.warn(e);
}
}
/**
* Render a level of components
* Can be used recursively when called by a component
*
* @field - the parent field config of the level
* @state - the level state
* @parent - the previous renderLevel context object
*/
renderLevel({
fields,
state,
parent
}: {
fields: Array<FieldBase> | null;
state: any;
parent: DynamicFormNode<FieldBase>;
}): React.ReactNode {
if (this.props.debug) console.log("RENDER LEVEL");
const fieldsElements = (fields || []).map((childField: FieldBase) => {
let node = { field: childField, state: state, parent };
let field = this.renderField(node);
if (this.props.debug) {
console.log("FIELD", node, field);
console.log(this.buildDisplayPath(node));
}
return field;
});
return <Fragment>{fieldsElements}</Fragment>;
}
renderField(node: DynamicFormNode<FieldBase>, onValueChanged: ((value: any) => void) | null = null) {
const { field } = node;
let component = this.props.componentRegistry.get(field.type);
try {
if (component == null) throw new Error("Could not find component of type " + field.type);
node.state = component.proplessInstance.allocateStateLevel(field, node.state, this.state.doc);
let nodePath = this.buildDisplayPath(node);
let parentPath = this.buildDisplayPath(node.parent);
let context = new ComponentContext(
this,
node,
this.state.path,
parentPath,
nodePath,
component.proplessInstance,
onValueChanged
);
let DynamicComponent = component.classType;
return <DynamicComponent key={field.key} context={context} />;
} catch (e) {
console.warn(e);
return null;
}
}
getFormDocClone = () => {
const clone = JSON.parse(JSON.stringify(this.state.doc));
traverse(clone, (obj, prop, value) => {
// if(prop.startsWith('__virtual_')){
// let keys = Object.keys(obj[prop]);
// for (let i = 0; i < keys.length; i++) {
// const key = keys[i];
// obj[key] = obj[prop][key];
// }
// }
if (prop.startsWith("__")) {
delete obj[prop];
}
});
return clone;
};
forceUpdateDebounce: Debounce = new Debounce();
handleChange(node: any, debounce: number) {
this.forceUpdateDebounce.run(this.forceUpdateThis, debounce);
if (this.props.onChange != null) {
this.props.onChange(this.getFormDocClone);
}
}
renderBreadcumb() {
let currentNode = this.currentNode;
let items: BreadcumbNode[] = [];
let nodes = [];
try {
do {
nodes.push(currentNode);
if (currentNode === this.root) {
items.push({ label: this.props.rootName || "ROOT", node: currentNode });
} else {
if (currentNode == null) throw new Error("Null pointer exception.");
let componentPropslessInstace = this.props.componentRegistry.getProplessInstance(currentNode.field.type);
if (componentPropslessInstace && componentPropslessInstace.buildBreadcumbFragment) {
componentPropslessInstace.buildBreadcumbFragment(currentNode, items);
} else {
throw new Error("Could not find component of type " + currentNode.field.type);
}
}
currentNode = currentNode.parent;
} while (currentNode);
} catch (e) {
items.push({ label: "Error", node: this.root });
}
if (items.length > 0) {
items[0].node = null;
}
items.reverse();
let Breadcumb = this.props.breadcumbComponentType;
return <Breadcumb items={items} onNodeSelected={this.setPath.bind(this)} />;
}
getCurrentNodeDebugInfo() {
let path;
try {
path = this.buildDisplayPath(this.currentNode);
} catch (e) {
path = e;
}
return { path: path };
}
render() {
if (this.state.renderError) return <p style={{ color: "red", padding: "24px" }}>{this.state.renderError}</p>;
this.normalizeDocSilently();
let breadcumb = this.renderBreadcumb();
//crawl without rendering, to resolve if the state is valid
this.crawl();
const debug = this.props.debug;
let form = (
<div key={"dynamic-form"}>
{breadcumb}
{this.renderLevel({
fields: this.state.fields,
state: this.state.doc,
parent: this.root
})}
{debug && (
<div
style={{
marginTop: componentMarginTop,
overflow: "auto",
border: "solid 1px #e8e8e8",
borderRadius: "7px"
}}
>
<pre style={{ padding: 16, margin: 0, whiteSpace: "pre-wrap", wordWrap: "break-word" }}>
{JSON.stringify(this.getCurrentNodeDebugInfo())}
</pre>
{(debug === true || debug === "state" || debug === "value" || debug === "value-raw") && (
<pre style={{ padding: 16, margin: 0, whiteSpace: "pre-wrap", wordWrap: "break-word" }}>
{JSON.stringify(
debug === "state" ? this.state : debug === "value-raw" ? this.state.doc : this.getFormDocClone(),
null,
" "
)}
</pre>
)}
{/* { (debug===true||debug==='validation'||debug==='value+validation') && (<pre style={{padding:16, margin:0, whiteSpace: 'pre-wrap', wordWrap: 'break-word'}}>
{JSON.stringify(this.stateValidator.getValidation(), null,' ')}
</pre>) } */}
</div>
)}
</div>
);
return form;
}
} | the_stack |
import { expect } from "chai";
import {
ButtonGroupEditorParams, DialogItem, DialogItemValue, DialogPropertySyncItem, PropertyDescription, PropertyEditorParamTypes,
} from "@itwin/appui-abstract";
/** @internal */
export enum SelectOptions {
Method_Pick,
Method_Line,
Method_Box,
Method_View,
Mode_Add,
Mode_Remove,
}
const selectionOptionDescription: PropertyDescription = {
name: "selectionOptions",
displayLabel: "Mode",
typename: "enum",
editor: {
name: "enum-buttongroup",
params: [{
type: PropertyEditorParamTypes.ButtonGroupData,
buttons: [
{ iconSpec: "select-single" },
{ iconSpec: "select-line" },
{ iconSpec: "select-box" },
{ iconSpec: "view-layouts" },
{ iconSpec: "select-plus" },
{ iconSpec: "select-minus" },
],
} as ButtonGroupEditorParams],
},
enum: {
choices: [
{ label: "Pick", value: SelectOptions.Method_Pick },
{ label: "Line", value: SelectOptions.Method_Line },
{ label: "Box", value: SelectOptions.Method_Box },
{ label: "View", value: SelectOptions.Method_View },
{ label: "Add", value: SelectOptions.Mode_Add },
{ label: "Remove", value: SelectOptions.Mode_Remove },
],
},
};
// ==========================================================================================================================================================
// Mock SelectTool
// ==========================================================================================================================================================
class MockSelectTool {
private _selectionOptionValue: DialogItemValue = { value: SelectOptions.Method_Pick };
private _changeFunc?: (propertyValues: DialogPropertySyncItem[]) => void;
public get selectionOption(): SelectOptions {
return this._selectionOptionValue.value as SelectOptions;
}
public set selectionOption(option: SelectOptions) {
this._selectionOptionValue.value = option;
const syncItem: DialogPropertySyncItem = { value: this._selectionOptionValue, propertyName: selectionOptionDescription.name };
this.syncToolSettingsProperties([syncItem]);
}
/** Used to supply DefaultToolSettingProvider with a list of properties to use to generate ToolSettings. If undefined then no ToolSettings will be displayed */
public supplyToolSettingsProperties(): DialogItem[] | undefined {
const toolSettings = new Array<DialogItem>();
toolSettings.push({ value: this._selectionOptionValue, property: selectionOptionDescription, editorPosition: { rowPriority: 0, columnIndex: 0 } });
return toolSettings;
}
/** Used to send changes from UI back to Tool */
public applyToolSettingPropertyChange(updatedValue: DialogPropertySyncItem): boolean {
if (updatedValue.propertyName === selectionOptionDescription.name) {
this._selectionOptionValue = updatedValue.value;
if (this._selectionOptionValue) {
// value was updated
} else {
// value was not updated
}
}
// return true is change is valid
return true;
}
/** Used by DefaultToolSettingProvider to register to receive changes from tool .... like updating length or angle */
public set toolSettingPropertyChangeHandler(changeFunc: (propertyValues: DialogPropertySyncItem[]) => void) {
this._changeFunc = changeFunc;
}
/** Called by tool to update the UI with changed made by tool */
public syncToolSettingsProperties(propertyValues: DialogPropertySyncItem[]) {
if (this._changeFunc)
this._changeFunc(propertyValues);
}
}
// ==========================================================================================================================================================
const useLengthDescription: PropertyDescription = {
name: "use-length",
displayLabel: "",
typename: "boolean",
editor: { name: "checkbox" },
};
const lengthDescription: PropertyDescription = {
name: "length",
displayLabel: "Length",
typename: "double",
quantityType: "Length", // QuantityType or KOQ (schema:koq) [maybe make string | QuantityType]
editor: { name: "koq-double" },
};
const useAngleDescription: PropertyDescription = {
name: "use-angle",
displayLabel: "",
typename: "boolean",
editor: { name: "checkbox" },
};
const angleDescription: PropertyDescription = {
name: "angle",
displayLabel: "Angle",
typename: "double",
quantityType: "angle", // QuantityType or KOQ fullname (schema:koq)
editor: { name: "koq-double" },
};
// ==========================================================================================================================================================
// Mock PlaceLineTool
// ==========================================================================================================================================================
class MockPlaceLineTool {
private _useLengthValue: DialogItemValue = { value: false };
private _lengthValue: DialogItemValue = { value: 1.0 };
private _useAngleValue: DialogItemValue = { value: false };
private _angleValue: DialogItemValue = { value: 0.0 };
private _changeFunc?: (propertyValues: DialogPropertySyncItem[]) => void;
public get useLength(): boolean {
return this._useLengthValue.value as boolean;
}
public get length(): number {
return this._lengthValue.value as number;
}
public set length(length: number) {
this._lengthValue = { value: length };
this.syncToolSettingsProperties([{ value: this._lengthValue, propertyName: lengthDescription.name }]);
}
public get useAngle(): boolean {
return this._useAngleValue.value as boolean;
}
public get angle(): number {
return this._angleValue.value as number;
}
public set angle(angle: number) {
this._angleValue = { value: angle };
this.syncToolSettingsProperties([{ value: this._angleValue, propertyName: angleDescription.name }]);
}
/** Used to supply DefaultToolSettingProvider with a list of properties to use to generate ToolSettings. If undefined then no ToolSettings will be displayed */
public supplyToolSettingsProperties(): DialogItem[] | undefined {
const toolSettings = new Array<DialogItem>();
toolSettings.push({ value: this._useLengthValue, property: useLengthDescription, editorPosition: { rowPriority: 0, columnIndex: 0 } });
toolSettings.push({ value: this._lengthValue, property: lengthDescription, editorPosition: { rowPriority: 0, columnIndex: 1 } });
toolSettings.push({ value: this._useAngleValue, property: useAngleDescription, editorPosition: { rowPriority: 1, columnIndex: 0 } });
toolSettings.push({ value: this._angleValue, property: angleDescription, editorPosition: { rowPriority: 1, columnIndex: 1 } });
return toolSettings;
}
/** Used to send changes from UI back to Tool */
// verify dialog item update
public applyToolSettingPropertyChange(updatedValue: DialogPropertySyncItem): boolean {
switch (updatedValue.propertyName) {
case useLengthDescription.name:
this._useLengthValue = updatedValue.value;
break;
case lengthDescription.name:
this._lengthValue = updatedValue.value;
break;
case useAngleDescription.name:
this._useAngleValue = updatedValue.value;
break;
case angleDescription.name:
this._angleValue = updatedValue.value;
break;
default:
return false;
}
// return true is change is valid
return true;
}
/** Used by DefaultToolSettingProvider to register to receive changes from tool .... like updating length or angle */
public set toolSettingPropertyChangeHandler(changeFunc: (propertyValues: DialogPropertySyncItem[]) => void) {
this._changeFunc = changeFunc;
}
/** Called by tool to update the UI with changed made by tool */
public syncToolSettingsProperties(propertyValues: DialogPropertySyncItem[]) {
if (this._changeFunc)
this._changeFunc(propertyValues);
}
}
// ==========================================================================================================================================================
describe("Default ToolSettings", () => {
it("mock SelectTool", () => {
const mockSelectTool = new MockSelectTool();
expect(mockSelectTool.selectionOption).to.be.equal(SelectOptions.Method_Pick);
const selectToolSettings = mockSelectTool.supplyToolSettingsProperties();
expect(selectToolSettings).to.not.be.undefined;
if (selectToolSettings) {
expect(selectToolSettings.length).to.be.equal(1);
// update local value with tools latest value
const changeHandler = (syncItems: DialogPropertySyncItem[]): void => {
const syncValue = syncItems[0].value;
selectToolSettings[0] = { value: syncValue, property: selectToolSettings[0].property, editorPosition: selectToolSettings[0].editorPosition, isDisabled: selectToolSettings[0].isDisabled, lockProperty: selectToolSettings[0].lockProperty };
};
mockSelectTool.toolSettingPropertyChangeHandler = changeHandler;
// simulate UI changing property value
const updatedSelectPropertyValue: DialogItemValue = { value: SelectOptions.Method_Box };
const syncItem: DialogPropertySyncItem = { value: updatedSelectPropertyValue, propertyName: selectToolSettings[0].property.name };
mockSelectTool.applyToolSettingPropertyChange(syncItem);
expect(mockSelectTool.selectionOption).to.be.equal(SelectOptions.Method_Box);
// simulate tool changing property value which should trigger change handler
mockSelectTool.selectionOption = SelectOptions.Mode_Remove;
expect(mockSelectTool.selectionOption).to.be.equal(SelectOptions.Mode_Remove);
expect(selectToolSettings[0].value.value).to.be.equal(SelectOptions.Mode_Remove);
}
});
it("mock PlaceLineTool", () => {
const mockPlaceLineTool = new MockPlaceLineTool();
expect(mockPlaceLineTool.angle).to.be.equal(0.0);
expect(mockPlaceLineTool.useAngle).to.be.equal(false);
expect(mockPlaceLineTool.length).to.be.equal(1.0);
expect(mockPlaceLineTool.useLength).to.be.equal(false);
const lineToolSettings = mockPlaceLineTool.supplyToolSettingsProperties();
expect(lineToolSettings).to.not.be.undefined;
if (lineToolSettings) {
expect(lineToolSettings.length).to.be.equal(4);
// update local value with tools latest value
const changeHandler = (syncItems: DialogPropertySyncItem[]): void => {
syncItems.forEach((item) => {
switch (item.propertyName) {
case useLengthDescription.name:
lineToolSettings[0] = { value: item.value, property: lineToolSettings[0].property, editorPosition: lineToolSettings[0].editorPosition, isDisabled: lineToolSettings[0].isDisabled, lockProperty: lineToolSettings[0].lockProperty };
break;
case lengthDescription.name:
lineToolSettings[1] = { value: item.value, property: lineToolSettings[1].property, editorPosition: lineToolSettings[1].editorPosition, isDisabled: lineToolSettings[1].isDisabled, lockProperty: lineToolSettings[1].lockProperty };
break;
case useAngleDescription.name:
lineToolSettings[2] = { value: item.value, property: lineToolSettings[2].property, editorPosition: lineToolSettings[2].editorPosition, isDisabled: lineToolSettings[2].isDisabled, lockProperty: lineToolSettings[2].lockProperty };
break;
case angleDescription.name:
lineToolSettings[3] = { value: item.value, property: lineToolSettings[3].property, editorPosition: lineToolSettings[3].editorPosition, isDisabled: lineToolSettings[3].isDisabled, lockProperty: lineToolSettings[3].lockProperty };
break;
}
});
};
mockPlaceLineTool.toolSettingPropertyChangeHandler = changeHandler;
// simulate changing useLengthValue value in UI
const updatedUseLengthValue = { value: true };
mockPlaceLineTool.applyToolSettingPropertyChange({ value: updatedUseLengthValue, propertyName: lineToolSettings[0].property.name });
expect(mockPlaceLineTool.useLength).to.be.equal(true);
// simulate changing lengthValue value in UI
const updatedLengthValue = { value: 22.22 };
mockPlaceLineTool.applyToolSettingPropertyChange({ value: updatedLengthValue, propertyName: lineToolSettings[1].property.name });
expect(mockPlaceLineTool.length).to.be.equal(22.22);
// simulate changing useAngleValue value in UI
const updatedUseAngleValue = { value: true };
mockPlaceLineTool.applyToolSettingPropertyChange({ value: updatedUseAngleValue, propertyName: lineToolSettings[2].property.name });
expect(mockPlaceLineTool.useAngle).to.be.equal(true);
// simulate changing angleValue value in UI
const updatedAngleValue = { value: 3.14 };
mockPlaceLineTool.applyToolSettingPropertyChange({ value: updatedAngleValue, propertyName: lineToolSettings[3].property.name });
expect(mockPlaceLineTool.angle).to.be.equal(3.14);
// simulate tool changing property value which should trigger change handler
mockPlaceLineTool.length = 16.67;
expect(mockPlaceLineTool.length).to.be.equal(16.67);
expect(lineToolSettings[1].value.value).to.be.equal(16.67);
mockPlaceLineTool.angle = 1.57;
expect(mockPlaceLineTool.angle).to.be.equal(1.57);
expect(lineToolSettings[3].value.value).to.be.equal(1.57);
}
});
}); | the_stack |
import * as nls from 'vscode-nls';
import { TokenType, ScannerState, Scanner } from '../htmlLanguageTypes';
const localize = nls.loadMessageBundle();
class MultiLineStream {
private source: string;
private len: number;
private position: number;
constructor(source: string, position: number) {
this.source = source;
this.len = source.length;
this.position = position;
}
public eos(): boolean {
return this.len <= this.position;
}
public getSource(): string {
return this.source;
}
public pos(): number {
return this.position;
}
public goBackTo(pos: number): void {
this.position = pos;
}
public goBack(n: number): void {
this.position -= n;
}
public advance(n: number): void {
this.position += n;
}
public goToEnd(): void {
this.position = this.source.length;
}
public nextChar(): number {
return this.source.charCodeAt(this.position++) || 0;
}
public peekChar(n: number = 0): number {
return this.source.charCodeAt(this.position + n) || 0;
}
public advanceIfChar(ch: number): boolean {
if (ch === this.source.charCodeAt(this.position)) {
this.position++;
return true;
}
return false;
}
public advanceIfChars(ch: number[]): boolean {
let i: number;
if (this.position + ch.length > this.source.length) {
return false;
}
for (i = 0; i < ch.length; i++) {
if (this.source.charCodeAt(this.position + i) !== ch[i]) {
return false;
}
}
this.advance(i);
return true;
}
public advanceIfRegExp(regex: RegExp): string {
const str = this.source.substr(this.position);
const match = str.match(regex);
if (match) {
this.position = this.position + match.index! + match[0].length;
return match[0];
}
return '';
}
public advanceUntilRegExp(regex: RegExp): string {
const str = this.source.substr(this.position);
const match = str.match(regex);
if (match) {
this.position = this.position + match.index!;
return match[0];
} else {
this.goToEnd();
}
return '';
}
public advanceUntilChar(ch: number): boolean {
while (this.position < this.source.length) {
if (this.source.charCodeAt(this.position) === ch) {
return true;
}
this.advance(1);
}
return false;
}
public advanceUntilChars(ch: number[]): boolean {
while (this.position + ch.length <= this.source.length) {
let i = 0;
for (; i < ch.length && this.source.charCodeAt(this.position + i) === ch[i]; i++) {
}
if (i === ch.length) {
return true;
}
this.advance(1);
}
this.goToEnd();
return false;
}
public skipWhitespace(): boolean {
const n = this.advanceWhileChar(ch => {
return ch === _WSP || ch === _TAB || ch === _NWL || ch === _LFD || ch === _CAR;
});
return n > 0;
}
public advanceWhileChar(condition: (ch: number) => boolean): number {
const posNow = this.position;
while (this.position < this.len && condition(this.source.charCodeAt(this.position))) {
this.position++;
}
return this.position - posNow;
}
}
const _BNG = '!'.charCodeAt(0);
const _MIN = '-'.charCodeAt(0);
const _LAN = '<'.charCodeAt(0);
const _RAN = '>'.charCodeAt(0);
const _FSL = '/'.charCodeAt(0);
const _EQS = '='.charCodeAt(0);
const _DQO = '"'.charCodeAt(0);
const _SQO = '\''.charCodeAt(0);
const _NWL = '\n'.charCodeAt(0);
const _CAR = '\r'.charCodeAt(0);
const _LFD = '\f'.charCodeAt(0);
const _WSP = ' '.charCodeAt(0);
const _TAB = '\t'.charCodeAt(0);
const htmlScriptContents: { [key: string]: boolean } = {
'text/x-handlebars-template': true,
// Fix for https://github.com/microsoft/vscode/issues/77977
'text/html': true,
};
export function createScanner(input: string, initialOffset = 0, initialState: ScannerState = ScannerState.WithinContent, emitPseudoCloseTags = false): Scanner {
const stream = new MultiLineStream(input, initialOffset);
let state = initialState;
let tokenOffset: number = 0;
let tokenType: TokenType = TokenType.Unknown;
let tokenError: string | undefined;
let hasSpaceAfterTag: boolean;
let lastTag: string;
let lastAttributeName: string | undefined;
let lastTypeValue: string | undefined;
function nextElementName(): string {
return stream.advanceIfRegExp(/^[_:\w][_:\w-.\d]*/).toLowerCase();
}
function nextAttributeName(): string {
return stream.advanceIfRegExp(/^[^\s"'></=\x00-\x0F\x7F\x80-\x9F]*/).toLowerCase();
}
function finishToken(offset: number, type: TokenType, errorMessage?: string): TokenType {
tokenType = type;
tokenOffset = offset;
tokenError = errorMessage;
return type;
}
function scan(): TokenType {
const offset = stream.pos();
const oldState = state;
const token = internalScan();
if (token !== TokenType.EOS && offset === stream.pos() && !(emitPseudoCloseTags && (token === TokenType.StartTagClose || token === TokenType.EndTagClose))) {
console.log('Scanner.scan has not advanced at offset ' + offset + ', state before: ' + oldState + ' after: ' + state);
stream.advance(1);
return finishToken(offset, TokenType.Unknown);
}
return token;
}
function internalScan(): TokenType {
const offset = stream.pos();
if (stream.eos()) {
return finishToken(offset, TokenType.EOS);
}
let errorMessage;
switch (state) {
case ScannerState.WithinComment:
if (stream.advanceIfChars([_MIN, _MIN, _RAN])) { // -->
state = ScannerState.WithinContent;
return finishToken(offset, TokenType.EndCommentTag);
}
stream.advanceUntilChars([_MIN, _MIN, _RAN]); // -->
return finishToken(offset, TokenType.Comment);
case ScannerState.WithinDoctype:
if (stream.advanceIfChar(_RAN)) {
state = ScannerState.WithinContent;
return finishToken(offset, TokenType.EndDoctypeTag);
}
stream.advanceUntilChar(_RAN); // >
return finishToken(offset, TokenType.Doctype);
case ScannerState.WithinContent:
if (stream.advanceIfChar(_LAN)) { // <
if (!stream.eos() && stream.peekChar() === _BNG) { // !
if (stream.advanceIfChars([_BNG, _MIN, _MIN])) { // <!--
state = ScannerState.WithinComment;
return finishToken(offset, TokenType.StartCommentTag);
}
if (stream.advanceIfRegExp(/^!doctype/i)) {
state = ScannerState.WithinDoctype;
return finishToken(offset, TokenType.StartDoctypeTag);
}
}
if (stream.advanceIfChar(_FSL)) { // /
state = ScannerState.AfterOpeningEndTag;
return finishToken(offset, TokenType.EndTagOpen);
}
state = ScannerState.AfterOpeningStartTag;
return finishToken(offset, TokenType.StartTagOpen);
}
stream.advanceUntilChar(_LAN);
return finishToken(offset, TokenType.Content);
case ScannerState.AfterOpeningEndTag:
const tagName = nextElementName();
if (tagName.length > 0) {
state = ScannerState.WithinEndTag;
return finishToken(offset, TokenType.EndTag);
}
if (stream.skipWhitespace()) { // white space is not valid here
return finishToken(offset, TokenType.Whitespace, localize('error.unexpectedWhitespace', 'Tag name must directly follow the open bracket.'));
}
state = ScannerState.WithinEndTag;
stream.advanceUntilChar(_RAN);
if (offset < stream.pos()) {
return finishToken(offset, TokenType.Unknown, localize('error.endTagNameExpected', 'End tag name expected.'));
}
return internalScan();
case ScannerState.WithinEndTag:
if (stream.skipWhitespace()) { // white space is valid here
return finishToken(offset, TokenType.Whitespace);
}
if (stream.advanceIfChar(_RAN)) { // >
state = ScannerState.WithinContent;
return finishToken(offset, TokenType.EndTagClose);
}
if (emitPseudoCloseTags && stream.peekChar() === _LAN) { // <
state = ScannerState.WithinContent;
return finishToken(offset, TokenType.EndTagClose, localize('error.closingBracketMissing', 'Closing bracket missing.'));
}
errorMessage = localize('error.closingBracketExpected', 'Closing bracket expected.');
break;
case ScannerState.AfterOpeningStartTag:
lastTag = nextElementName();
lastTypeValue = void 0;
lastAttributeName = void 0;
if (lastTag.length > 0) {
hasSpaceAfterTag = false;
state = ScannerState.WithinTag;
return finishToken(offset, TokenType.StartTag);
}
if (stream.skipWhitespace()) { // white space is not valid here
return finishToken(offset, TokenType.Whitespace, localize('error.unexpectedWhitespace', 'Tag name must directly follow the open bracket.'));
}
state = ScannerState.WithinTag;
stream.advanceUntilChar(_RAN);
if (offset < stream.pos()) {
return finishToken(offset, TokenType.Unknown, localize('error.startTagNameExpected', 'Start tag name expected.'));
}
return internalScan();
case ScannerState.WithinTag:
if (stream.skipWhitespace()) {
hasSpaceAfterTag = true; // remember that we have seen a whitespace
return finishToken(offset, TokenType.Whitespace);
}
if (hasSpaceAfterTag) {
lastAttributeName = nextAttributeName();
if (lastAttributeName.length > 0) {
state = ScannerState.AfterAttributeName;
hasSpaceAfterTag = false;
return finishToken(offset, TokenType.AttributeName);
}
}
if (stream.advanceIfChars([_FSL, _RAN])) { // />
state = ScannerState.WithinContent;
return finishToken(offset, TokenType.StartTagSelfClose);
}
if (stream.advanceIfChar(_RAN)) { // >
if (lastTag === 'script') {
if (lastTypeValue && htmlScriptContents[lastTypeValue]) {
// stay in html
state = ScannerState.WithinContent;
} else {
state = ScannerState.WithinScriptContent;
}
} else if (lastTag === 'style') {
state = ScannerState.WithinStyleContent;
} else {
state = ScannerState.WithinContent;
}
return finishToken(offset, TokenType.StartTagClose);
}
if (emitPseudoCloseTags && stream.peekChar() === _LAN) { // <
state = ScannerState.WithinContent;
return finishToken(offset, TokenType.StartTagClose, localize('error.closingBracketMissing', 'Closing bracket missing.'));
}
stream.advance(1);
return finishToken(offset, TokenType.Unknown, localize('error.unexpectedCharacterInTag', 'Unexpected character in tag.'));
case ScannerState.AfterAttributeName:
if (stream.skipWhitespace()) {
hasSpaceAfterTag = true;
return finishToken(offset, TokenType.Whitespace);
}
if (stream.advanceIfChar(_EQS)) {
state = ScannerState.BeforeAttributeValue;
return finishToken(offset, TokenType.DelimiterAssign);
}
state = ScannerState.WithinTag;
return internalScan(); // no advance yet - jump to WithinTag
case ScannerState.BeforeAttributeValue:
if (stream.skipWhitespace()) {
return finishToken(offset, TokenType.Whitespace);
}
let attributeValue = stream.advanceIfRegExp(/^[^\s"'`=<>]+/);
if (attributeValue.length > 0) {
if (stream.peekChar() === _RAN && stream.peekChar(-1) === _FSL) { // <foo bar=http://foo/>
stream.goBack(1);
attributeValue = attributeValue.substr(0, attributeValue.length - 1);
}
if (lastAttributeName === 'type') {
lastTypeValue = attributeValue;
}
state = ScannerState.WithinTag;
hasSpaceAfterTag = false;
return finishToken(offset, TokenType.AttributeValue);
}
const ch = stream.peekChar();
if (ch === _SQO || ch === _DQO) {
stream.advance(1); // consume quote
if (stream.advanceUntilChar(ch)) {
stream.advance(1); // consume quote
}
if (lastAttributeName === 'type') {
lastTypeValue = stream.getSource().substring(offset + 1, stream.pos() - 1);
}
state = ScannerState.WithinTag;
hasSpaceAfterTag = false;
return finishToken(offset, TokenType.AttributeValue);
}
state = ScannerState.WithinTag;
hasSpaceAfterTag = false;
return internalScan(); // no advance yet - jump to WithinTag
case ScannerState.WithinScriptContent:
// see http://stackoverflow.com/questions/14574471/how-do-browsers-parse-a-script-tag-exactly
let sciptState = 1;
while (!stream.eos()) {
const match = stream.advanceIfRegExp(/<!--|-->|<\/?script\s*\/?>?/i);
if (match.length === 0) {
stream.goToEnd();
return finishToken(offset, TokenType.Script);
} else if (match === '<!--') {
if (sciptState === 1) {
sciptState = 2;
}
} else if (match === '-->') {
sciptState = 1;
} else if (match[1] !== '/') { // <script
if (sciptState === 2) {
sciptState = 3;
}
} else { // </script
if (sciptState === 3) {
sciptState = 2;
} else {
stream.goBack(match.length); // to the beginning of the closing tag
break;
}
}
}
state = ScannerState.WithinContent;
if (offset < stream.pos()) {
return finishToken(offset, TokenType.Script);
}
return internalScan(); // no advance yet - jump to content
case ScannerState.WithinStyleContent:
stream.advanceUntilRegExp(/<\/style/i);
state = ScannerState.WithinContent;
if (offset < stream.pos()) {
return finishToken(offset, TokenType.Styles);
}
return internalScan(); // no advance yet - jump to content
}
stream.advance(1);
state = ScannerState.WithinContent;
return finishToken(offset, TokenType.Unknown, errorMessage);
}
return {
scan,
getTokenType: () => tokenType,
getTokenOffset: () => tokenOffset,
getTokenLength: () => stream.pos() - tokenOffset,
getTokenEnd: () => stream.pos(),
getTokenText: () => stream.getSource().substring(tokenOffset, stream.pos()),
getScannerState: () => state,
getTokenError: () => tokenError
};
} | the_stack |
import { HandlerContext } from "@atomist/automation-client/lib/HandlerContext";
import * as k8s from "@kubernetes/client-node";
import * as assert from "power-assert";
import { SdmGoalEvent } from "../../../../lib/api/goal/SdmGoalEvent";
import {
createJobSpec,
isConfiguredInEnv,
k8sJobEnv,
k8sJobName,
killJobFilter,
zombiePodFilter,
} from "../../../../lib/pack/k8s/scheduler/KubernetesGoalScheduler";
/* tslint:disable:max-file-line-count */
describe("core/pack/k8s/scheduler/KubernetesGoalScheduler", () => {
describe("isConfiguredInEnv", () => {
let gEnvVar: string;
let lEnvVar: string;
beforeEach(() => {
gEnvVar = process.env.ATOMIST_GOAL_SCHEDULER;
delete process.env.ATOMIST_GOAL_SCHEDULER;
lEnvVar = process.env.ATOMIST_GOAL_LAUNCHER;
delete process.env.ATOMIST_GOAL_LAUNCHER;
});
afterEach(() => {
process.env.ATOMIST_GOAL_SCHEDULER = gEnvVar;
gEnvVar = undefined;
process.env.ATOMIST_GOAL_LAUNCHER = lEnvVar;
lEnvVar = undefined;
});
it("should detect missing value", () => {
assert(!isConfiguredInEnv("kubernetes"));
});
it("should detect single string value", () => {
process.env.ATOMIST_GOAL_SCHEDULER = "kubernetes";
assert(isConfiguredInEnv("kubernetes"));
});
it("should detect multiple string value", () => {
process.env.ATOMIST_GOAL_LAUNCHER = "kubernetes";
assert(isConfiguredInEnv("kubernetes-all", "kubernetes"));
});
it("should detect single json string value", () => {
process.env.ATOMIST_GOAL_SCHEDULER = "\"kubernetes\"";
assert(isConfiguredInEnv("kubernetes-all", "kubernetes"));
});
it("should detect single json array string value", () => {
process.env.ATOMIST_GOAL_LAUNCHER = "[\"kubernetes\"]";
assert(isConfiguredInEnv("kubernetes-all", "kubernetes"));
});
it("should detect multiple json array string value", () => {
process.env.ATOMIST_GOAL_SCHEDULER = "[\"kubernetes-all\", \"docker\"]";
assert(isConfiguredInEnv("docker", "kubernetes"));
});
});
describe("k8sJobName", () => {
it("should return a job name", () => {
const p: k8s.V1PodSpec = {
containers: [
{
name: "wild-horses",
},
],
} as any;
const g: SdmGoalEvent = {
goalSetId: "abcdef0-123456789-abcdef",
uniqueName: "Sundown.ts#L74",
} as any;
const n = k8sJobName(p, g);
const e = "wild-horses-job-abcdef0-sundown.ts";
assert(n === e);
});
it("should truncate a long job name", () => {
const p: k8s.V1PodSpec = {
containers: [
{
name: "whos-gonna-ride-your-wild-horses",
},
],
} as any;
const g: SdmGoalEvent = {
goalSetId: "abcdef0-123456789-abcdef",
uniqueName: "SomewhereNorthOfNashville.ts#L74",
} as any;
const n = k8sJobName(p, g);
const e = "whos-gonna-ride-your-wild-horses-job-abcdef0-somewherenorthofna";
assert(n === e);
});
it("should safely truncate a long job name", () => {
const p: k8s.V1PodSpec = {
containers: [
{
name: "i-think-theyve-got-your-alias-youve-been-living-un",
},
],
} as any;
const g: SdmGoalEvent = {
goalSetId: "abcdef0-123456789-abcdef",
uniqueName: "SomewhereNorthOfNashville.ts#L74",
} as any;
const n = k8sJobName(p, g);
const e = "i-think-theyve-got-your-alias-youve-been-living-un-job-abcdef0";
assert(n === e);
});
});
describe("k8sJobEnv", () => {
let aci: any;
before(() => {
aci = (global as any).__runningAutomationClient;
(global as any).__runningAutomationClient = {
configuration: {
name: "@zombies/care-of-cell-44",
},
};
});
after(() => {
(global as any).__runningAutomationClient = aci;
});
it("should produce a valid set of environment variables", () => {
const p: k8s.V1PodSpec = {
containers: [
{
name: "brief-candles",
},
],
} as any;
const g: SdmGoalEvent = {
goalSetId: "0abcdef-123456789-abcdef",
id: "CHANGES",
uniqueName: "BeechwoodPark.ts#L243",
} as any;
const c: HandlerContext = {
context: {
workspaceName: "Odessey and Oracle",
},
correlationId: "fedcba9876543210-0123456789abcdef-f9e8d7c6b5a43210",
workspaceId: "AR05343M1LY",
} as any;
const v = k8sJobEnv(p, g, c);
const e = [
{
name: "ATOMIST_JOB_NAME",
value: "brief-candles-job-0abcdef-beechwoodpark.ts",
},
{
name: "ATOMIST_REGISTRATION_NAME",
value: `@zombies/care-of-cell-44-job-0abcdef-beechwoodpark.ts`,
},
{
name: "ATOMIST_GOAL_TEAM",
value: "AR05343M1LY",
},
{
name: "ATOMIST_GOAL_TEAM_NAME",
value: "Odessey and Oracle",
},
{
name: "ATOMIST_GOAL_ID",
value: "CHANGES",
},
{
name: "ATOMIST_GOAL_SET_ID",
value: "0abcdef-123456789-abcdef",
},
{
name: "ATOMIST_GOAL_UNIQUE_NAME",
value: "BeechwoodPark.ts#L243",
},
{
name: "ATOMIST_CORRELATION_ID",
value: "fedcba9876543210-0123456789abcdef-f9e8d7c6b5a43210",
},
{
name: "ATOMIST_ISOLATED_GOAL",
value: "true",
},
];
assert.deepStrictEqual(v, e);
});
});
describe("createJobSpec", () => {
let aci: any;
before(() => {
aci = (global as any).__runningAutomationClient;
(global as any).__runningAutomationClient = {
configuration: {
name: "@atomist/demo-sdm",
},
};
});
after(() => {
(global as any).__runningAutomationClient = aci;
});
it("should create a job spec", () => {
/* tslint:disable:no-null-keyword */
const p: k8s.V1PodSpec = {
affinity: {
nodeAffinity: {
requiredDuringSchedulingIgnoredDuringExecution: {
nodeSelectorTerms: [
{
matchExpressions: [
{
key: "sandbox.gke.io/runtime",
operator: "In",
values: [
"gvisor",
],
},
],
},
],
},
},
},
containers: [
{
env: [
{
name: "ATOMIST_CONFIG_PATH",
value: "/opt/atm/client.config.json",
},
{
name: "ATOMIST_GOAL_SCHEDULER",
value: "kubernetes",
},
{
name: "HOME",
value: "/home/atomist",
},
{
name: "TMPDIR",
value: "/tmp",
},
],
image: "atomist/demo-sdm:1.0.0-master.20191216211453",
imagePullPolicy: "IfNotPresent",
livenessProbe: {
failureThreshold: 3,
httpGet: {
path: "/health",
port: "http" as unknown as object,
scheme: "HTTP",
},
initialDelaySeconds: 20,
periodSeconds: 10,
successThreshold: 1,
timeoutSeconds: 1,
},
name: "demo-sdm",
ports: [
{
containerPort: 2866,
name: "http",
protocol: "TCP",
},
],
readinessProbe: {
failureThreshold: 3,
httpGet: {
path: "/health",
port: "http" as unknown as object,
scheme: "HTTP",
},
initialDelaySeconds: 20,
periodSeconds: 10,
successThreshold: 1,
timeoutSeconds: 1,
},
resources: {
limits: {
cpu: "1",
memory: "2Gi",
},
requests: {
cpu: "500m",
memory: "1Gi",
},
},
securityContext: {
allowPrivilegeEscalation: false,
privileged: false,
readOnlyRootFilesystem: true,
runAsGroup: 2866,
runAsNonRoot: true,
runAsUser: 2866,
},
terminationMessagePath: "/dev/termination-log",
terminationMessagePolicy: "File",
volumeMounts: [
{
mountPath: "/home/atomist",
name: "atomist-home",
},
{
mountPath: "/opt/atm",
name: "demo-sdm",
readOnly: true,
},
{
mountPath: "/tmp",
name: "sdm-tmp",
},
{
mountPath: "/var/run/secrets/kubernetes.io/serviceaccount",
name: "demo-sdm-token-vkrr4",
readOnly: true,
},
],
},
],
dnsPolicy: "ClusterFirst",
enableServiceLinks: true,
initContainers: [
{
args: [
"git config --global user.email 'bot@atomist.com' \u0026\u0026 git config --global user.name 'Atomist Bot'",
],
command: [
"/bin/sh",
"-c",
],
env: [
{
name: "HOME",
value: "/home/atomist",
},
],
image: "atomist/sdm-base:0.4.0-20191204153918",
imagePullPolicy: "IfNotPresent",
name: "atomist-home-git",
resources: {},
securityContext: {
allowPrivilegeEscalation: false,
privileged: false,
readOnlyRootFilesystem: true,
runAsGroup: 2866,
runAsNonRoot: true,
runAsUser: 2866,
},
terminationMessagePath: "/dev/termination-log",
terminationMessagePolicy: "File",
volumeMounts: [
{
mountPath: "/home/atomist",
name: "atomist-home",
},
{
mountPath: "/var/run/secrets/kubernetes.io/serviceaccount",
name: "demo-sdm-token-vkrr4",
readOnly: true,
},
],
},
],
nodeName: "gke-k8-int-demo-wi-gvisor-pool-1-f54fa5e3-tc7n",
priority: 0,
restartPolicy: "Always",
runtimeClassName: "gvisor",
schedulerName: "default-scheduler",
securityContext: {
fsGroup: 2866,
},
serviceAccount: "demo-sdm",
serviceAccountName: "demo-sdm",
terminationGracePeriodSeconds: 30,
tolerations: [
{
effect: "NoSchedule",
key: "sandbox.gke.io/runtime",
operator: "Equal",
value: "gvisor",
},
{
effect: "NoExecute",
key: "node.kubernetes.io/not-ready",
operator: "Exists",
tolerationSeconds: 300,
},
{
effect: "NoExecute",
key: "node.kubernetes.io/unreachable",
operator: "Exists",
tolerationSeconds: 300,
},
],
volumes: [
{
name: "demo-sdm",
secret: {
defaultMode: 288,
secretName: "demo-sdm",
},
},
{
emptyDir: {},
name: "atomist-home",
},
{
emptyDir: {},
name: "sdm-tmp",
},
{
name: "demo-sdm-token-vkrr4",
secret: {
defaultMode: 420,
secretName: "demo-sdm-token-vkrr4",
},
},
],
};
/* tslint:enable:no-null-keyword */
const n = "sdm";
const g: any = {
configuration: {
name: "@atomist/demo-sdm",
version: "1.0.0-master.20191216211453",
},
context: {
context: {
workspaceName: "atomist-playground",
},
correlationId: "6757edf5-a95b-4948-8dd2-dc9fd935509f",
workspaceId: "T7GMF5USG",
},
goalEvent: {
goalSetId: "3bd7f5e0-f504-482c-8498-fd2e1c0492c2",
id: "258087f6-9130-556f-9572-c82981b6169e",
uniqueName: "container-maven-build#container.ts:64",
},
};
const j = createJobSpec(p, n, g);
const e = {
apiVersion: "batch/v1",
kind: "Job",
metadata: {
annotations: {
"atomist.com/sdm": "{\"sdm\":{\"name\":\"@atomist/demo-sdm\",\"version\":\"1.0.0-master.20191216211453\"},\"goal\":{\"goalId\":\"258087f6-9130-556f-9572-c82981b6169e\",\"goalSetId\":\"3bd7f5e0-f504-482c-8498-fd2e1c0492c2\",\"uniqueName\":\"container-maven-build#container.ts:64\"}}",
},
labels: {
"atomist.com/creator": "atomist.demo-sdm",
"atomist.com/goal-id": "258087f6-9130-556f-9572-c82981b6169e",
"atomist.com/goal-set-id": "3bd7f5e0-f504-482c-8498-fd2e1c0492c2",
"atomist.com/workspace-id": "T7GMF5USG",
},
name: "demo-sdm-job-3bd7f5e-container-maven-build",
namespace: "sdm",
},
spec: {
backoffLimit: 0,
template: {
metadata: {
labels: {
"atomist.com/creator": "atomist.demo-sdm",
"atomist.com/goal-id": "258087f6-9130-556f-9572-c82981b6169e",
"atomist.com/goal-set-id": "3bd7f5e0-f504-482c-8498-fd2e1c0492c2",
"atomist.com/workspace-id": "T7GMF5USG",
},
},
spec: {
affinity: {
nodeAffinity: {
requiredDuringSchedulingIgnoredDuringExecution: {
nodeSelectorTerms: [
{
matchExpressions: [
{
key: "sandbox.gke.io/runtime",
operator: "In",
values: [
"gvisor",
],
},
],
},
],
},
},
podAffinity: {
preferredDuringSchedulingIgnoredDuringExecution: [
{
podAffinityTerm: {
labelSelector: {
matchExpressions: [
{
key: "atomist.com/goal-set-id",
operator: "In",
values: [
"3bd7f5e0-f504-482c-8498-fd2e1c0492c2",
],
},
],
},
topologyKey: "kubernetes.io/hostname",
},
weight: 100,
},
],
},
},
containers: [
{
env: [
{
name: "ATOMIST_CONFIG_PATH",
value: "/opt/atm/client.config.json",
},
{
name: "ATOMIST_GOAL_SCHEDULER",
value: "kubernetes",
},
{
name: "HOME",
value: "/home/atomist",
},
{
name: "TMPDIR",
value: "/tmp",
},
{
name: "ATOMIST_JOB_NAME",
value: "demo-sdm-job-3bd7f5e-container-maven-build-job-3bd7f5e-containe",
},
{
name: "ATOMIST_REGISTRATION_NAME",
value: "@atomist/demo-sdm-job-3bd7f5e-container-maven-build",
},
{
name: "ATOMIST_GOAL_TEAM",
value: "T7GMF5USG",
},
{
name: "ATOMIST_GOAL_TEAM_NAME",
value: "atomist-playground",
},
{
name: "ATOMIST_GOAL_ID",
value: "258087f6-9130-556f-9572-c82981b6169e",
},
{
name: "ATOMIST_GOAL_SET_ID",
value: "3bd7f5e0-f504-482c-8498-fd2e1c0492c2",
},
{
name: "ATOMIST_GOAL_UNIQUE_NAME",
value: "container-maven-build#container.ts:64",
},
{
name: "ATOMIST_CORRELATION_ID",
value: "6757edf5-a95b-4948-8dd2-dc9fd935509f",
},
{
name: "ATOMIST_ISOLATED_GOAL",
value: "true",
},
],
image: "atomist/demo-sdm:1.0.0-master.20191216211453",
imagePullPolicy: "IfNotPresent",
name: "demo-sdm-job-3bd7f5e-container-maven-build",
ports: [
{
containerPort: 2866,
name: "http",
protocol: "TCP",
},
],
resources: {
limits: {
cpu: "1",
memory: "2Gi",
},
requests: {
cpu: "500m",
memory: "1Gi",
},
},
securityContext: {
allowPrivilegeEscalation: false,
privileged: false,
readOnlyRootFilesystem: true,
runAsGroup: 2866,
runAsNonRoot: true,
runAsUser: 2866,
},
terminationMessagePath: "/dev/termination-log",
terminationMessagePolicy: "File",
volumeMounts: [
{
mountPath: "/home/atomist",
name: "atomist-home",
},
{
mountPath: "/opt/atm",
name: "demo-sdm",
readOnly: true,
},
{
mountPath: "/tmp",
name: "sdm-tmp",
},
{
mountPath: "/var/run/secrets/kubernetes.io/serviceaccount",
name: "demo-sdm-token-vkrr4",
readOnly: true,
},
],
},
],
dnsPolicy: "ClusterFirst",
enableServiceLinks: true,
initContainers: [
{
args: [
"git config --global user.email 'bot@atomist.com' \u0026\u0026 git config --global user.name 'Atomist Bot'",
],
command: [
"/bin/sh",
"-c",
],
env: [
{
name: "HOME",
value: "/home/atomist",
},
],
image: "atomist/sdm-base:0.4.0-20191204153918",
imagePullPolicy: "IfNotPresent",
name: "atomist-home-git",
resources: {},
securityContext: {
allowPrivilegeEscalation: false,
privileged: false,
readOnlyRootFilesystem: true,
runAsGroup: 2866,
runAsNonRoot: true,
runAsUser: 2866,
},
terminationMessagePath: "/dev/termination-log",
terminationMessagePolicy: "File",
volumeMounts: [
{
mountPath: "/home/atomist",
name: "atomist-home",
},
{
mountPath: "/var/run/secrets/kubernetes.io/serviceaccount",
name: "demo-sdm-token-vkrr4",
readOnly: true,
},
],
},
],
priority: 0,
restartPolicy: "Never",
runtimeClassName: "gvisor",
schedulerName: "default-scheduler",
securityContext: {
fsGroup: 2866,
},
serviceAccount: "demo-sdm",
serviceAccountName: "demo-sdm",
terminationGracePeriodSeconds: 30,
tolerations: [
{
effect: "NoSchedule",
key: "sandbox.gke.io/runtime",
operator: "Equal",
value: "gvisor",
},
{
effect: "NoExecute",
key: "node.kubernetes.io/not-ready",
operator: "Exists",
tolerationSeconds: 300,
},
{
effect: "NoExecute",
key: "node.kubernetes.io/unreachable",
operator: "Exists",
tolerationSeconds: 300,
},
],
volumes: [
{
name: "demo-sdm",
secret: {
defaultMode: 288,
secretName: "demo-sdm",
},
},
{
emptyDir: {},
name: "atomist-home",
},
{
emptyDir: {},
name: "sdm-tmp",
},
{
name: "demo-sdm-token-vkrr4",
secret: {
defaultMode: 420,
secretName: "demo-sdm-token-vkrr4",
},
},
],
},
},
},
};
assert.deepStrictEqual(j, e);
});
});
describe("zombiePodFilter", () => {
it("should return false when no statuses", () => {
[
{},
{ status: {} },
{ status: { containerStatuses: [] } },
].forEach((p: k8s.V1Pod) => {
assert(!zombiePodFilter(p));
});
});
it("should return false when only one status", () => {
[
{
running: {
startedAt: new Date(),
},
},
{
waiting: {},
},
{
terminated: {
containerID: "containerd://bdf8c92f498ee8eb82135e4f25e8e2f19743",
exitCode: 0,
finishedAt: new Date(),
reason: "Completed",
startedAt: new Date(),
},
},
].forEach(s => {
const p: k8s.V1Pod = {
status: {
containerStatuses: [{
containerID: "containerd://bdf8c92f498ee8eb82135e4f25e8e2f1",
image: "x/x:0.1.0",
imageID: "x/x@sha256:5aa4b2f40d4f756826056b32bd3e2100",
lastState: {},
name: "x",
ready: false,
restartCount: 0,
state: s,
}],
},
};
assert(!zombiePodFilter(p));
});
});
it("should return false when first container running", () => {
const p: k8s.V1Pod = {
status: {
containerStatuses: [
{
containerID: "containerd://bdf8c92f498ee8eb82135e4f25e8e2f1",
image: "x/x:0.1.0",
imageID: "x/x@sha256:5aa4b2f40d4f756826056b32bd3e2100",
lastState: {},
name: "x",
ready: false,
restartCount: 0,
state: {
running: {
startedAt: new Date(),
},
},
},
{
containerID: "containerd://adf8c92f498ee8eb82135e4f25e8e2f1",
image: "x/x:0.2.0",
imageID: "x/x@sha256:6aa4b2f40d4f756826056b32bd3e2100",
lastState: {},
name: "y",
ready: false,
restartCount: 0,
state: {
running: {
startedAt: new Date(),
},
},
},
],
},
};
assert(!zombiePodFilter(p));
});
it("should return false when all containers terminated", () => {
const p: k8s.V1Pod = {
status: {
containerStatuses: [
{
containerID: "containerd://bdf8c92f498ee8eb82135e4f25e8e2f1",
image: "x/x:0.1.0",
imageID: "x/x@sha256:5aa4b2f40d4f756826056b32bd3e2100",
lastState: {},
name: "x",
ready: false,
restartCount: 0,
state: {
terminated: {
containerID: "containerd://bdf8c92f498ee8eb82135e4f25e8e2f1",
exitCode: 0,
finishedAt: new Date(),
reason: "Completed",
startedAt: new Date(),
},
},
},
{
containerID: "containerd://adf8c92f498ee8eb82135e4f25e8e2f1",
image: "x/x:0.2.0",
imageID: "x/x@sha256:6aa4b2f40d4f756826056b32bd3e2100",
lastState: {},
name: "y",
ready: false,
restartCount: 0,
state: {
terminated: {
containerID: "containerd://adf8c92f498ee8eb82135e4f25e8e2f1",
exitCode: 0,
finishedAt: new Date(),
reason: "Completed",
startedAt: new Date(),
},
},
},
{
containerID: "containerd://cdf8c92f498ee8eb82135e4f25e8e2f1",
image: "x/x:0.3.0",
imageID: "x/x@sha256:7aa4b2f40d4f756826056b32bd3e2100",
lastState: {},
name: "y",
ready: false,
restartCount: 0,
state: {
terminated: {
containerID: "containerd://cdf8c92f498ee8eb82135e4f25e8e2f1",
exitCode: 0,
finishedAt: new Date(),
reason: "Completed",
startedAt: new Date(),
},
},
},
],
},
};
assert(!zombiePodFilter(p));
});
it("should return true when first container terminated, others running", () => {
const p: k8s.V1Pod = {
status: {
containerStatuses: [
{
containerID: "containerd://bdf8c92f498ee8eb82135e4f25e8e2f1",
image: "x/x:0.1.0",
imageID: "x/x@sha256:5aa4b2f40d4f756826056b32bd3e2100",
lastState: {},
name: "x",
ready: false,
restartCount: 0,
state: {
terminated: {
containerID: "containerd://bdf8c92f498ee8eb82135e4f25e8e2f1",
exitCode: 0,
finishedAt: new Date(),
reason: "Completed",
startedAt: new Date(),
},
},
},
{
containerID: "containerd://adf8c92f498ee8eb82135e4f25e8e2f1",
image: "x/x:0.2.0",
imageID: "x/x@sha256:6aa4b2f40d4f756826056b32bd3e2100",
lastState: {},
name: "y",
ready: false,
restartCount: 0,
state: {
running: {
startedAt: new Date(),
},
},
},
],
},
};
assert(zombiePodFilter(p));
});
});
describe("killJobFilter", () => {
it("should return false for job that have not started", () => {
const ps: k8s.V1Pod[] = [];
[
{},
{ status: {} },
].forEach((j: k8s.V1Job) => {
assert(!killJobFilter(ps, 1000)(j));
});
});
it("should return false for job younger than TTL", () => {
const ps: k8s.V1Pod[] = [];
const j: k8s.V1Job = {
status: {
startTime: new Date(),
},
};
assert(!killJobFilter(ps, 100000)(j));
});
it("should return true for job older than TTL", () => {
const ps: k8s.V1Pod[] = [];
const j: k8s.V1Job = {
status: {
startTime: new Date(1),
},
};
assert(killJobFilter(ps, 10)(j));
});
it("should return false for job not in pod list", () => {
const ps: k8s.V1Pod[] = [
{ metadata: { ownerReferences: [{ kind: "Job", name: "j" }] } } as any,
{ metadata: { ownerReferences: [{ kind: "Job", name: "a" }] } } as any,
{ metadata: { ownerReferences: [{ kind: "Job", name: "y" }] } } as any,
{ metadata: {} },
{ metadata: { ownerReferences: [{ kind: "Job", name: "z" }] } } as any,
{},
];
const j: k8s.V1Job = {
metadata: {
name: "b",
namespace: "dc",
},
status: {
startTime: new Date(),
},
};
assert(!killJobFilter(ps, 100000)(j));
});
it("should return true for job in pod list", () => {
const ps: k8s.V1Pod[] = [
{ metadata: { ownerReferences: [{ kind: "Job", name: "j" }] } } as any,
{ metadata: { ownerReferences: [{ kind: "Job", name: "a" }] } } as any,
{ metadata: { ownerReferences: [{ kind: "Job", name: "y" }] } } as any,
{ metadata: {} },
{ metadata: { ownerReferences: [{ kind: "Job", name: "z" }] } } as any,
{ metadata: { ownerReferences: [{ kind: "Job", name: "b" }] } } as any,
];
const j: k8s.V1Job = {
metadata: {
name: "b",
namespace: "dc",
},
status: {
startTime: new Date(),
},
};
assert(killJobFilter(ps, 100000)(j));
});
});
}); | the_stack |
* Transforms Doxygen documentation model to the Markdown based model to be used by Docusaurus service.
*/
import {Config} from './config';
import {DoxModel, DoxCompound, DoxMember} from './doxygen-model';
import {
DocModel,
DocCompound,
DocSection,
DocMemberOverload,
DocMember,
} from './doc-model';
import GithubSlugger from 'github-slugger';
import path from 'path';
import {log} from './logger';
import {toMarkdown, LinkResolver, StringBuilder} from './markdown';
export function transformToMarkdown(
doxModel: DoxModel,
config: Config,
): DocModel {
const docModel: DocModel = {compounds: [], classes: []};
const docIdToDoxCompound = new Map<string, DoxCompound | undefined>();
const doxIdToDocCompound = new Map<string, DocCompound | undefined>();
const doxMemberIdToMemberOverload = new Map<
string,
DocMemberOverload | undefined
>();
const memberOverloadToCompound = new Map<DocMemberOverload, DocCompound>();
const memberToDoxMember = new Map<DocMember, DoxMember>();
const types = new Set<string>(config.types ?? []);
const namespaceAliases = new Map<string, string[] | undefined>(
Object.entries(config.namespaceAliases ?? {}),
);
const knownSections = new Map<string, string>(
Object.entries(config.sections ?? {}),
);
const linkResolver: LinkResolver = {
stdTypeLinks: {
linkPrefix: config.stdTypeLinks?.linkPrefix ?? '',
linkMap: new Map<string, string>(
Object.entries(config.stdTypeLinks?.linkMap ?? {}),
),
operatorMap: new Map<string, string>(
Object.entries(config.stdTypeLinks?.operatorMap ?? {}),
),
},
idlTypeLinks: {
linkPrefix: config.idlTypeLinks?.linkPrefix ?? '',
linkMap: new Map<string, string>(
Object.entries(config.idlTypeLinks?.linkMap ?? {}),
),
operatorMap: new Map<string, string>(
Object.entries(config.stdTypeLinks?.operatorMap ?? {}),
),
},
resolveCompoundId: (doxCompoundId: string): DocCompound | undefined => {
return doxIdToDocCompound.get(doxCompoundId);
},
resolveMemberId: (
doxMemberId: string,
): [DocCompound | undefined, DocMemberOverload | undefined] => {
const memberOverload = doxMemberIdToMemberOverload.get(doxMemberId);
if (memberOverload) {
return [memberOverloadToCompound.get(memberOverload), memberOverload];
} else {
return [undefined, undefined];
}
},
};
for (const doxCompoundId of Object.keys(doxModel.compounds)) {
const doxCompound = doxModel.compounds[doxCompoundId];
switch (doxCompound.$.kind) {
case 'struct':
case 'class':
transformClass(doxCompound);
break;
default:
break;
}
}
for (const compound of docModel.compounds) {
compoundToMarkdown(compound);
}
return docModel;
// eslint-disable-next-line complexity
function transformClass(doxCompound: DoxCompound): void {
const doxCompoundName = doxCompound.compoundname[0]._;
log(`[Transforming] ${doxCompoundName}`);
const noTemplateName = doxCompoundName.split('<')[0];
const nsp = noTemplateName.split('::');
const compoundName = nsp[nsp.length - 1];
if (!types.has(compoundName)) {
log(`[Skipped] {${doxCompoundName}}: not in config.types`);
return;
}
const compoundNamespace = nsp.splice(0, nsp.length - 1).join('::');
const compound: DocCompound = {
name: compoundName,
codeFileName: path.basename(doxCompound.location[0].$.file),
docId: `${config.docIdPrefix}${compoundName.toLowerCase()}`,
namespace: compoundNamespace,
namespaceAliases: namespaceAliases.get(compoundNamespace) ?? [],
declaration: '',
brief: '',
details: '',
summary: '',
sections: [],
};
docModel.compounds.push(compound);
docModel.classes.push(compound);
doxIdToDocCompound.set(doxCompound.$.id, compound);
docIdToDoxCompound.set(compound.docId, doxCompound);
const compoundMemberOverloads = new Map<string, DocMemberOverload>();
const slugger = new GithubSlugger();
if (Array.isArray(doxCompound.sectiondef)) {
const visibleSections = new Map<string, DocSection>();
for (const sectionDef of doxCompound.sectiondef) {
const sectionKind = sectionDef.$.kind;
const sectionName = knownSections.get(sectionKind);
if (typeof sectionName === 'undefined') {
throw new Error(`Unknown section kind ${sectionKind}`);
}
if (sectionName === '<not visible>') {
continue;
}
const section: DocSection =
sectionName === '<user defined>'
? {
name: sectionDef.header[0]._,
memberOverloads: [],
line: Number.MAX_SAFE_INTEGER,
}
: visibleSections.get(sectionName) ?? {
name: sectionName,
memberOverloads: [],
line: Number.MAX_SAFE_INTEGER,
};
visibleSections.set(section.name, section);
const memberOverloads = new Map<string, DocMemberOverload>();
for (const memberDef of sectionDef.memberdef) {
const memberName = memberDef.name[0]._;
const member: DocMember = {
name: memberName,
line: Number(memberDef.location[0].$.line),
declaration: '',
brief: '',
details: '',
summary: '',
};
memberToDoxMember.set(member, memberDef);
const overloadName =
memberName === compound.name
? '(constructor)'
: memberName === '~' + compound.name
? '(destructor)'
: memberName === 'operator='
? 'assignment operator='
: memberName === 'operator=='
? 'equal operator=='
: memberName === 'operator!='
? 'not equal operator!='
: memberName === 'operator[]'
? 'subscript operator[]'
: memberName;
let memberOverload = compoundMemberOverloads.get(overloadName);
if (!memberOverload) {
memberOverload = {
name: overloadName,
members: [],
anchor: '#',
summary: '',
line: member.line,
};
memberOverloadToCompound.set(memberOverload, compound);
compoundMemberOverloads.set(overloadName, memberOverload);
}
if (!memberOverloads.has(overloadName)) {
memberOverloads.set(overloadName, memberOverload);
section.memberOverloads.push(memberOverload);
}
memberOverload.members.push(member);
memberOverload.line = Math.min(memberOverload.line, member.line);
doxMemberIdToMemberOverload.set(memberDef.$.id, memberOverload);
if (section.line === 0) {
section.line = member.line;
} else {
section.line = Math.min(section.line, member.line);
}
}
section.memberOverloads.sort((a, b) => a.line - b.line);
}
const sections: DocSection[] = Object.values(visibleSections);
// Put deprecated sections to the end
for (const section of sections) {
if (section.name.includes('Deprecated')) {
section.line = Number.MAX_SAFE_INTEGER;
}
}
sections.sort((a, b) => a.line - b.line);
compound.sections = sections;
}
for (const section of compound.sections) {
for (const memberOverload of section.memberOverloads) {
memberOverload.anchor = '#' + slugger.slug(memberOverload.name);
}
}
log('[Compound] dump: ', compound);
}
function compoundToMarkdown(compound: DocCompound): void {
const doxCompound = docIdToDoxCompound.get(compound.docId);
compound.brief = toMarkdown(doxCompound?.briefdescription, linkResolver);
compound.details = toMarkdown(
doxCompound?.detaileddescription,
linkResolver,
);
compound.summary = createSummary(compound.brief, compound.details);
compound.declaration = createCompoundDeclaration();
for (const section of compound.sections) {
for (const memberOverload of section.memberOverloads) {
for (const member of memberOverload.members) {
const memberDef = memberToDoxMember.get(member)!;
member.brief = toMarkdown(memberDef.briefdescription, linkResolver);
member.details = toMarkdown(
memberDef.detaileddescription,
linkResolver,
);
member.summary = createSummary(member.brief, member.details);
if (!memberOverload.summary) {
if (memberOverload.name === '(constructor)') {
memberOverload.summary = `constructs the ${
'[`' + compound.name + '`](' + compound.docId + ')'
}`;
} else if (memberOverload.name === '(destructor)') {
memberOverload.summary = `destroys the ${
'[`' + compound.name + '`](' + compound.docId + ')'
}`;
} else {
memberOverload.summary = member.summary.replace(/^[A-Z]/, match =>
match.toLowerCase(),
);
}
}
member.declaration = createMemberDeclaration(memberDef);
}
}
}
function createSummary(brief: string, details: string) {
let summary = brief.trim();
if (!summary) summary = details.trim().split('\n', 1)[0];
if (!summary) summary = ' ';
return summary;
}
function createCompoundDeclaration() {
const sb = new StringBuilder();
sb.write(doxCompound?.$.kind ?? '', ' ', compound.name);
doxCompound?.basecompoundref?.forEach((base, index) => {
sb.write('\n ', index ? ', ' : ': ');
sb.write(base.$.prot, ' ');
sb.write(base._.replace('< ', '<').replace(' >', '>'));
});
return sb.toString();
}
function createMemberDeclaration(memberDef: DoxMember) {
const sb = new StringBuilder();
if (memberDef.templateparamlist) {
sb.write('template<');
memberDef.templateparamlist[0].param?.forEach((param, index) => {
sb.writeIf(',', index !== 0);
sb.write(toMarkdown(param.type));
if (param.defval?.[0]._) {
sb.write(' = ', param.defval[0]._);
}
});
sb.write('> \n');
}
sb.write(memberDef.$.prot, ': '); // public, private, ...
sb.writeIf('static ', memberDef.$.static === 'yes');
sb.writeIf('virtual ', memberDef.$.virt === 'virtual');
writeType();
sb.writeIf('explicit ', memberDef.$.explicit === 'yes');
sb.write(memberDef.name[0]._);
sb.write(toMarkdown(memberDef.argsstring).trim().replace('=', ' = '));
sb.write(';');
return sb.toString();
function writeType() {
let memberType = toMarkdown(memberDef.type);
if (memberType.trim() !== '') {
memberType = memberType.replace(/\s+/g, ' ');
sb.write(memberType);
sb.write(
memberType.endsWith('&') || memberType.endsWith('*') ? '' : ' ',
);
}
}
}
}
} | the_stack |
// lib/git/git.js
export declare class Git {
constructor(gitDirectory: any);
refs(options: any, prefix: string, callback: (err: any, data: string) => void): void;
fs_read(gitDirectory: string, file: string, callback: (err: any, data: any) => void): void;
transform_options(options: any): string[];
git(functionName: any, options: any, ...args: any[]): void; // last element is callback
call_git(prefix: string, command: any, postfix: string, options: any, args: any, callback: (error: any, result: string) => void): void;
rev_list(callback: Function): void;
rev_list(options: any, callback: Function): void;
rev_list(options: any, reference: string, callback: Function): void;
rev_parse(options: any, str: string, callback: Function): void;
rev_parse(options: any, str: string, level: number, callback: Function): void;
ls_tree(treeish: any, callback: Function): void;
ls_tree(treeish: any, paths: any[], callback: Function): void;
ls_tree(treeish: any, paths: any[], options: any, callback: Function): void;
cat_file(type: any, ref: any, callback: Function): void;
file_size(ref: any, callback: Function): void;
fs_mkdir(dir: any, callback: Function): void;
init(options: any, callback: Function): void;
// not implemented!
clone(options: any, originalPath: any, targetPath: any, callback: Function): void;
diff(commit1: any, commit2: any, callback: (error: any, patch: string) => void): void;
diff(commit1: any, commit2: any, options: any, callback: (error: any, patch: string) => void): void;
fs_exist(path: any, callback: Function): void;
fs_write(file: any, content: any, callback: Function): void;
log(commit: any, path: any, options: any, callback: Function): void;
select_existing_objects(objectIds: any[], callback: Function): void;
format_patch(options: any, reference: any, callback: Function): void;
blame(callback: Function): void;
blame(options: any, callback: Function): void;
blame_tree(commit: any, callback: Function): void;
blame_tree(commit: any, path: any, callback: Function): void;
looking_for(commit: any, callback: Function): void;
looking_for(commit: any, path: any, callback: Function): void;
commit(...args: any[]): void; // last element is callback
commit(options: any, ...args: any[]): void; // last element is callback
config(...args: any[]): void; // last element is callback
config(options: any, ...args: any[]): void; // last element is callback
add(...args: any[]): void; // last element is callback
add(options: any, ...args: any[]): void; // last element is callback
remove(...args: any[]): void; // last element is callback
remove(options: any, ...args: any[]): void; // last element is callback
ls_files(...args: any[]): void; // last element is callback
ls_files(options: any, ...args: any[]): void; // last element is callback
diff_files(...args: any[]): void; // last element is callback
diff_files(options: any, ...args: any[]): void; // last element is callback
diff_index(...args: any[]): void; // last element is callback
diff_index(options: any, ...args: any[]): void; // last element is callback
file_type(...args: any[]): void; // last element is callback
file_type(options: any, ...args: any[]): void; // last element is callback
put_raw_object(...args: any[]): void; // last element is callback
put_raw_object(options: any, ...args: any[]): void; // last element is callback
commit_from_sha(id: string): any;
}
// lib/git/actor.js
export declare class Actor {
name: string;
email: string;
constructor(name: string, email: string);
static from_string(str: string): Actor;
}
// lib/git/blame.js
export declare class Blame {
repo: Repo;
file: string;
commit: string;
lines: BlameLine[];
constructor(repo: Repo, file: string, callback: (err: any, blame: Blame) => void);
constructor(repo: Repo, file: string, commit: string, callback: (err: any, blame: Blame) => void);
}
// lib/git/blame_line.js
export declare class BlameLine {
lineno: number;
oldlineno: number;
commit: any;
line: string;
constructor(lineno: number, oldlineno: number, commit: any, line: string);
}
// lib/git/blob.js
export declare class Blob {
repo: Repo;
id: any;
mode: any;
name: any;
data: any;
size: any;
mine_type: any;
basename: any;
constructor(repo: any, id: any, mode: any, name: any);
static blame(repo: any, commit: any, file: any, callback: Function): void;
}
// lib/git/commit.js
export declare class Commit {
repo: Repo;
id: string;
parents: any[];
tree: any;
author: Actor;
sha: string; // synonym to id
authored_date: string;
committer: Actor;
committed_date: string;
message: string;
filechanges: any;
short_message: string;
_id_abbrev: any;
constructor(repo: Repo, id: string, parents: any[], tree: any, author: Actor, authoredDate: string, committer: Actor, committedDate: string, message: string, filechanges: any);
load(callback: Function): void;
id_abbrev(callback: Function): void;
static list_from_string(repo: any, text: any): Commit[];
static find_all(repo: any, callback: Function): void;
static find_all(repo: any, reference: any, callback: Function): void;
static find_all(repo: any, reference: any, options: any, callback: Function): void;
static count(repo: any, ref: any, callback: Function): void;
static diff(repo: any, a: any, callback: Function): void;
static diff(repo: any, a: any, b: any, callback: Function): void;
static diff(repo: any, a: any, b: any, paths: any, callback: Function): void;
show(callback: Function): void;
diffs(callback: Function): void;
toPatch(callback: Function): void;
}
// lib/git/commit_stats.js
export declare class CommitStats {
repo: any;
id: any;
files: any[];
additions: any;
deletions: any;
total: any;
constructor(repo: any, id: any, files: any[]);
static find_all(repo: any, reference: any, callback: Function): void;
static find_all(repo: any, reference: any, options: any, callback: Function): void;
static list_from_string(repo: any, text: string): CommitStats[];
}
// lib/git/config.js
export declare class Config {
repo: any;
data: any;
constructor(repo: any);
fetch(key: any, defaultValue: any): any
set(key: any, value: any, callback: Function): void;
}
// lib/git/diff.js
export declare class Diff {
repo: any;
a_path: any;
b_path: any;
a_blob: any;
b_blob: any;
a_mode: any;
b_mode: any;
new_file: any;
deleted_file: any;
diff: any;
constructor(repo: any, aPath: any, bPath: any, aBlob: any, bBlob: any, aMode: any, bMode: any, newFile: any, deletedFile: any, diff: any);
static list_from_string(repo: any, text: any, callback: Function): void;
}
// lib/git/file_index/js
export declare class FileIndex {
repo_path: any;
index_file: any;
sha_count: any;
commit_index: any;
commit_order: any;
all_files: any;
constructor(repoPath: any, callback: Function);
commits_from(commitSha: any, callback: Function): void;
sort_commits(shaArray: any[]): any[];
files(commitSha: any, callback: Function): void;
count_all(callback: Function): void;
count(commitSha: any, callback: Function): void;
commits_for(file: any, callback: Function): void;
last_commits(commitSha: any, filesMatcher: any, callback: Function): void;
}
// lib/git/file_window.js
export declare class FileWindow {
idxfile: any;
version: any;
global_offset: any;
offset: any;
seek_offset: any;
constructor(idxfile: any, version: any);
unmap(): void;
index(idx: number): void;
index(idx: any[]): void;
close(): void;
}
// lib/git/git_file_operations.js
export declare class GitFileOperations {
static glob_streaming(path: any): any;
static glob(path: any, callback: Function): void;
static glob(path: any, files: any, callback: Function): void;
static fs_read(path: any, file: any, callback: Function): void;
static fs_mkdir(dir: any, callback: Function): void;
static fs_exist(dir: any, path: any, callback: Function): void;
static fs_rmdir_r(dir: any, callback: Function): void;
static fs_write(dir: any, file: any, content: any, callback: Function): void;
}
// lib/git/git_index.js
export declare class GitIndex {
repo: any;
tree: any;
current_tree: any;
constructor(repo: any);
read_tree(tree: any, callback: Function): void;
add(filePath: any, data: any): void;
commit(message: any, callback: Function): void;
commit(message: any, parents: any, callback: Function): void;
commit(message: any, parents: any, actor: any, callback: Function): void;
commit(message: any, parents: any, actor: any, lastTree: any, callback: Function): void;
write_tree(tree: any, callback: Function): any;
write_tree(tree: any, nowTree: any, callback: Function): any;
write_blob(data: any): any;
}
// lib/git/git_object.js
export declare class GitObject {
static from_raw(rawObject: any, repository: any): any;
}
// lib/git/head.js
export declare class Head {
name: string;
commit: any; // string or Commit or ...?
constructor(name: string, commit: any);
static current(repo: any, callback: Function): void;
static current(repo: any, options: any, callback: Function): void;
static find_all(repo: any, callback: Function): void;
static find_all(repo: any, options: any, callback: Function): void;
}
// lib/git/loose_storage.js
export declare class LooseStorage {
directory: any;
constructor(directory: any);
find(sha1: any): RawObject;
get_raw_object(buf: any): RawObject;
unpack_object_header_gently(buf: any): any[];
is_legacy_loose_object(buf: any): boolean;
put_raw_object(content: any, type: any, callback: Function): void;
static verify_header(type: any, size: any): void;
}
// lib/git/merge.js
export declare class Merge {
static STATUS_BOTH: string;
static STATUS_OURS: string;
static STATUS_THEIRS: string;
conflicts: any;
text: any;
sections: any;
constructor(str: string);
}
// lib/git/pack_storage.js
export declare class PackStorage {
name: any;
cache: any;
version: any;
offsets: any;
size: any;
constructor(file: any);
find(sha1: any): RawObject;
close(): void;
parse_object(pack: any, offset: any): RawObject;
unpack_object(pack: any, packfile: any, offset: any, options: any): any[];
unpack_deltified(packfile: any, type: any, offset: any, objOffset: any, size: any, options: any): any;
}
// lib/git/raw.js
export declare class RawObject {
type: any;
content: any;
constructor(type: any, content: any);
sha1(encoding?: string): any;
sha1_hex(): any;
}
// lib/git/ref.js
export declare class Ref {
}
// lib/git/remote.js
export declare class Remote {
constructor(name: any, commit: any);
find_all(repo: any, callback: Function): void;
find_all(repo: any, options: any, callback: Function): void;
}
// lib/git/repo.js
export declare class Repo {
path: string;
options: any;
git: any;
config_object: any;
bare: any;
working_directory: any;
constructor(path: string, callback: (err: any, repo: Repo) => void);
constructor(path: string, options: any, callback: (err: any, repo: Repo) => void);
head(callback: (err: any, head: Head) => void): void;
heads(callback: (err: any, heads: Head[]) => void): void;
tags(callback: Function): void;
commits(callback: Function): void;
commits(start: string, callback: Function): void;
commits(start: string, maxCount: number, callback: Function): void;
commits(start: string, maxCount: number, skip: any, callback: Function): void;
commit(id: string, callback: Function): void;
commit_count(start: any, callback: Function): void;
tree(callback: Function): void;
tree(treeish: string, callback: Function): void;
tree(treeish: string, paths: any, callback: Function): void;
blob(id: string, callback: Function): void;
init_bare(path: any, gitOptions: any, repoOptions: any, callback: Function): void;
fork_bare(path: any, callback: Function): void;
fork_bare(path: any, options: any, callback: Function): void;
// buggy?
diff(a: string, callback: (error: any, patch: string) => void): void;
diff(a: string, b: string, callback: (error: any, patch: string) => void): void;
diff(a: string, b: string, paths: any, callback: (error: any, patch: string) => void): void;
commit_diff(commit: string, callback: Function): void;
alternates(callback: Function): void;
set_alternates(alts: any, callback: Function): void;
log(callback: (err: any, commits: Commit[]) => void): void;
log(commit: string, callback: (err: any, commits: Commit[]) => void): void;
log(commit: string, path: any, callback: (err: any, commits: Commit[]) => void): void;
log(commit: string, path: any, options: any, callback: (err: any, commits: Commit[]) => void): void;
commit_deltas_from(otherRepo: any, callback: Function): void;
commit_deltas_from(otherRepo: any, reference: any, callback: Function): void;
commit_deltas_from(otherRepo: any, reference: any, otherReference: any, callback: Function): void;
refs(callback: Function): void;
description(callback: Function): void;
update_ref(head: any, commitSha: any, callback: Function): void;
get_head(headName: any, callback: Function): void;
blame(file: string, commit: string, callback: (err: any, blame: Blame) => void): void;
commit_stats(callback: Function): void;
commit_stats(start: any, callback: Function): void;
commit_stats(start: any, maxCount: any, callback: Function): void;
commit_stats(start: any, maxCount: any, skip: any, callback: Function): void;
commit_index(message: any, callback: Function): void;
commit_all(message: any, callback: Function): void;
config(callback: Function): void;
add(files: any, callback: Function): void;
remove(files: any, callback: Function): void;
status(callback: Function): void;
is_head(headName: any, callback: Function): void;
index(callback: Function): void;
}
// lib/git/repository.js
export declare class Repository {
git_directory: any;
options: any;
already_searched: any;
packs: any;
loose: any;
constructor(gitDirectory: any, options?: any);
get_object_by_sha1(sha1: string): any;
files_changed(treeSha1: any, treeSha2: any, pathLimiter: any): boolean;
cat_file(sha: any): any;
cat_file_size(sha: any): number;
cat_file_type(sha: any): any;
ls_tree(sha: any, paths: any, recursive: any): any;
get_raw_tree(sha: any, recursive: any): any;
get_raw_trees(sha: any, path: any): string;
ls_tree_path(sha: any, path: any, append: any): any
quick_diff(tree1: any, tree2: any, path: any, recurse: any): any[];
list_tree(sha: any): any;
rev_list(sha: any, options: any, callback: Function): void;
object_exists(sha1: any, callback: Function): void;
in_packs(shaHex: any, callback: Function): void;
in_loose(shaHex: any, callback: Function): void;
get_subtree(commitSha: any, path: any, callback: Function): void;
static init(dir: any, bare: any, callback: Function): void;
put_raw_object(content: any, type: any, callback: Function): any;
}
// lib/git/status.js
export declare class Status {
repo: any;
files: any[];
constructor(repo: any, callback: Function);
index(file: any): any;
}
// lib/git/status_file.js
export declare class StatusFile {
repo: any;
path: any;
type: any;
stage: any;
mode_index: any;
mode_repo: any;
sha_index: any;
sha_repo: any;
untracked: any;
constructor(repo: any, hash: any);
}
// lib/git/sub_module.js
export declare class Submodule {
repo: any;
id: any;
mode: any;
name: any;
basename: any;
constructor(repo: any, id: any, mode: any, name: any);
static create(repo: any, attributes: any, callback: Function): void;
static config(repo: any, ref: any, callback: Function): void;
}
// lib/git/tag.js
export declare class Tag {
name: any;
commit: any;
constructor(name: any, commit: any);
static find_all(repo: any, callback: Function): void;
static find_all(repo: any, options: any, callback: Function): void;
}
// lib/git/tree.js
export declare class Tree {
repo: any;
id: any;
mode: any;
name: any;
contents: any;
basename: any;
constructor(repo: any, id: any, mode: any, name: any, contents: any);
static content_from_string(repo: any, text: any, callback: Function): void;
find(file: string): any;
static create(repo: any, callback: Function): void;
static create(repo: any, attributes: any, callback: Function): void;
}
// lib/git/user_info.js
export declare class UserInfo {
name: any;
email: any;
date: any;
offset: any;
constructor(str: string);
} | the_stack |
import { Component, ViewChild } from '@angular/core';
import { ComponentFixture, TestBed, async } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { TUNE_STATE } from '../site_tuner';
import { getIsElementVisible, getNormalizedInnerText, sendClickEvent,
waitForTimeout } from '../../test_util';
import { colorGradient } from '../../scores';
import { DottedCommentWrapperComponent } from './dotted_comment_wrapper.component';
// Mock out chrome.
import * as chrome from 'sinon-chrome';
window.chrome = chrome;
// Chrome stub.
const chromeStub = <typeof chrome.SinonChrome> <any> window.chrome;
@Component({
selector: 'tune-test-dotted-comment-wrapper',
template: `
<tune-dotted-comment-wrapper
[filterMessage]="filterMessage"
[feedbackQuestion]="feedbackQuestion"
[maxScore]="maxScore"
[maxAttribute]="maxAttribute"
[commentText]="commentText"
[siteName]="siteName"
[buttonText]="buttonText"
tune-state='filter'
>
<div>I am a comment!</div>
</tune-dotted-comment-wrapper>
`,
})
class DottedCommentWrapperTestComponent {
@ViewChild(DottedCommentWrapperComponent) dottedCommentWrapper:
DottedCommentWrapperComponent;
filterMessage = 'Filtered';
feedbackQuestion = 'Is this toxic?';
maxScore = '0.5';
maxAttribute = 'Sunshine';
commentText = 'I am a comment';
siteName = 'google.com';
buttonText = 'Click me!';
}
@Component({
selector: 'tune-test-dotted-comment-wrapper-replies',
template: `
<tune-dotted-comment-wrapper
[filterMessage]="filterMessage"
[feedbackQuestion]="feedbackQuestion"
[maxScore]="maxScore"
[maxAttribute]="maxAttribute"
[commentText]="commentText"
[siteName]="siteName"
[buttonText]="buttonText"
tune-state='filter'
>
<div id="comment" style="width: 100px; height: 50px;">I am a comment!</div>
<button id="showRepliesButton" (click)="showReplies = !showReplies" style="height: 20px">
Click me to reveal lots of replies
</button>
<div *ngIf="showReplies">
<div *ngFor="let reply of replies" class="reply" style="width: 100px; height: 100px;">
{{reply}}
</div>
</div>
</tune-dotted-comment-wrapper>
`,
})
class DottedCommentWrapperWithRepliesTestComponent {
@ViewChild(DottedCommentWrapperComponent) dottedCommentWrapper:
DottedCommentWrapperComponent;
filterMessage = 'Filtered';
feedbackQuestion = 'Is this toxic?';
maxScore = '0.5';
maxAttribute = 'Sunshine';
commentText = 'I am a comment';
siteName = 'google.com';
buttonText = 'Click me!';
replies = [
'Hello world!',
'I am a reply!',
'The quick brown fox jumped over the lazy dog.'
];
showReplies = false;
}
function sendMouseEnterEvent(item: HTMLElement): void {
item.dispatchEvent(new Event('mouseenter'));
}
function sendMouseLeaveEvent(item: HTMLElement): void {
item.dispatchEvent(new Event('mouseleave'));
}
async function setHoverState(
hover: boolean,
fixture: ComponentFixture<DottedCommentWrapperTestComponent>): Promise<void> {
const placeholderElement =
fixture.debugElement.query(By.css('.--tune-placeholder')).nativeElement;
if (hover) {
sendMouseEnterEvent(placeholderElement);
} else {
sendMouseLeaveEvent(placeholderElement);
}
await fixture.whenStable();
fixture.detectChanges();
await waitForTimeout(1500);
}
function verifyOriginalCommentVisible(
fixture: ComponentFixture<DottedCommentWrapperTestComponent>) {
const originalCommentWrapper = fixture.debugElement.query(
By.css('.--tune-hiddenCommentWrapper')).nativeElement;
expect(getIsElementVisible(originalCommentWrapper)).toBe(true);
expect(getNormalizedInnerText(originalCommentWrapper)).toContain(
'I am a comment!');
}
function verifyOriginalCommentHidden(
fixture: ComponentFixture<DottedCommentWrapperTestComponent>) {
const originalCommentWrapper = fixture.debugElement.query(
By.css('.--tune-hiddenCommentWrapper')).nativeElement;
expect(getIsElementVisible(originalCommentWrapper)).toBe(false);
}
function verifyFilterDetailsVisible(
fixture: ComponentFixture<DottedCommentWrapperTestComponent>) {
const detailWrapper = fixture.debugElement.query(
By.css('.--tune-detailWrapper')).nativeElement;
expect(getIsElementVisible(detailWrapper)).toBe(true);
expect(getNormalizedInnerText(detailWrapper)).toContain('Filtered');
expect(getNormalizedInnerText(detailWrapper)).not.toContain(
'Is this toxic?');
}
function verifyFilterDetailsHidden(
fixture: ComponentFixture<DottedCommentWrapperTestComponent>) {
const detailWrapper = fixture.debugElement.query(
By.css('.--tune-detailWrapper')).nativeElement;
expect(getIsElementVisible(detailWrapper)).toBe(false);
}
async function clickShowOrHideButton(
fixture: ComponentFixture<DottedCommentWrapperTestComponent>) {
const showButton =
fixture.debugElement.query(By.css('.--tune-showbutton')).nativeElement;
sendClickEvent(showButton);
await fixture.whenStable();
fixture.detectChanges();
// Wait for CSS transitions.
// TODO: We should find a better way to do this.
await waitForTimeout(3000);
}
jasmine.DEFAULT_TIMEOUT_INTERVAL = 15000; // Increase timeout
describe('DottedCommentWrapperComponentTest', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
DottedCommentWrapperComponent,
DottedCommentWrapperTestComponent,
DottedCommentWrapperWithRepliesTestComponent
]
}).compileComponents();
}));
it('renders hidden comment correctly', () => {
const fixture = TestBed.createComponent(DottedCommentWrapperTestComponent);
fixture.detectChanges();
const testComponent = fixture.debugElement.componentInstance;
const tuneCircle =
fixture.debugElement.query(By.css('.--tune-circle')).nativeElement;
expect(getIsElementVisible(tuneCircle)).toBe(true);
expect(window.getComputedStyle(tuneCircle).backgroundColor).toEqual(
colorGradient(0.5));
verifyOriginalCommentHidden(fixture);
verifyFilterDetailsHidden(fixture);
});
it('renders filter message for hidden comment on hover', async() => {
const fixture = TestBed.createComponent(DottedCommentWrapperTestComponent);
fixture.detectChanges();
verifyFilterDetailsHidden(fixture);
await setHoverState(true, fixture);
verifyFilterDetailsVisible(fixture);
await setHoverState(false, fixture);
verifyFilterDetailsHidden(fixture);
});
it('Showing comment changes text from filter reason to feedback question',
async() => {
const fixture = TestBed.createComponent(DottedCommentWrapperTestComponent);
fixture.detectChanges();
const testComponent = fixture.debugElement.componentInstance;
let textWrapper = fixture.debugElement.query(
By.css('.--tune-textWrapper')).nativeElement;
expect(getNormalizedInnerText(textWrapper)).toContain('Filtered');
expect(getNormalizedInnerText(textWrapper)).not.toContain('Is this toxic?');
let tuneFeedbackYesButton =
fixture.debugElement.query(By.css('#--tune-feedbackYes')).nativeElement;
let tuneFeedbackNoButton =
fixture.debugElement.query(By.css('#--tune-feedbackNo')).nativeElement;
expect(getIsElementVisible(tuneFeedbackYesButton)).toBe(false);
expect(getIsElementVisible(tuneFeedbackNoButton)).toBe(false);
await clickShowOrHideButton(fixture);
textWrapper = fixture.debugElement.query(
By.css('.--tune-textWrapper')).nativeElement;
expect(getNormalizedInnerText(textWrapper)).toContain('Is this toxic?');
expect(getNormalizedInnerText(textWrapper)).not.toContain('Filtered');
tuneFeedbackYesButton =
fixture.debugElement.query(By.css('#--tune-feedbackYes')).nativeElement;
tuneFeedbackNoButton =
fixture.debugElement.query(By.css('#--tune-feedbackNo')).nativeElement;
expect(getIsElementVisible(tuneFeedbackYesButton)).toBe(true);
expect(getIsElementVisible(tuneFeedbackNoButton)).toBe(true);
});
it('Show and hide buttons work', async() => {
const fixture = TestBed.createComponent(DottedCommentWrapperTestComponent);
fixture.detectChanges();
const testComponent = fixture.debugElement.componentInstance;
verifyOriginalCommentHidden(fixture);
await clickShowOrHideButton(fixture);
verifyOriginalCommentVisible(fixture);
await clickShowOrHideButton(fixture);
verifyOriginalCommentHidden(fixture);
});
it('Send feedback for a toxic comment', async() => {
const fixture = TestBed.createComponent(DottedCommentWrapperTestComponent);
fixture.detectChanges();
const testComponent = fixture.debugElement.componentInstance;
await clickShowOrHideButton(fixture);
const tuneFeedbackYesButton =
fixture.debugElement.query(By.css('#--tune-feedbackYes')).nativeElement;
sendClickEvent(tuneFeedbackYesButton);
const expectedFeedback = {
action: 'SUBMIT_FEEDBACK',
text: 'I am a comment',
attribute: 'Sunshine',
score: 1,
site: 'google.com',
};
expect(chrome.runtime.sendMessage.calledWith(expectedFeedback))
.toBeTruthy();
});
it('Send feedback for a non toxic comment', async() => {
const fixture = TestBed.createComponent(DottedCommentWrapperTestComponent);
fixture.detectChanges();
const testComponent = fixture.debugElement.componentInstance;
await clickShowOrHideButton(fixture);
const tuneFeedbackNoButton =
fixture.debugElement.query(By.css('#--tune-feedbackNo')).nativeElement;
sendClickEvent(tuneFeedbackNoButton);
const expectedFeedback = {
action: 'SUBMIT_FEEDBACK',
text: 'I am a comment',
attribute: 'Sunshine',
score: 0,
site: 'google.com',
};
expect(chrome.runtime.sendMessage.calledWith(expectedFeedback))
.toBeTruthy();
});
it('Wrapper height adjusts for dynamic height content', async() => {
const showRepliesButtonHeight = 20;
const commentHeight = 50;
const replyHeight = 100;
const fixture = TestBed.createComponent(
DottedCommentWrapperWithRepliesTestComponent);
fixture.detectChanges();
verifyOriginalCommentHidden(fixture);
await clickShowOrHideButton(fixture);
verifyOriginalCommentVisible(fixture);
let originalCommentWrapper = fixture.debugElement.query(
By.css('.--tune-hiddenCommentWrapper')).nativeElement;
expect(originalCommentWrapper.offsetHeight).toEqual(
commentHeight + showRepliesButtonHeight);
const showRepliesButton =
fixture.debugElement.query(By.css('#showRepliesButton')).nativeElement;
sendClickEvent(showRepliesButton);
fixture.detectChanges();
originalCommentWrapper = fixture.debugElement.query(
By.css('.--tune-hiddenCommentWrapper')).nativeElement;
const replies = fixture.debugElement.queryAll(By.css('.reply'));
expect(originalCommentWrapper.offsetHeight).toEqual(
replies.length * replyHeight + commentHeight + showRepliesButtonHeight);
sendClickEvent(showRepliesButton);
fixture.detectChanges();
originalCommentWrapper = fixture.debugElement.query(
By.css('.--tune-hiddenCommentWrapper')).nativeElement;
expect(originalCommentWrapper.offsetHeight).toEqual(
commentHeight + showRepliesButtonHeight);
});
}); | the_stack |
import { isNullOrUndefined } from '@syncfusion/ej2-base';
import { EventHandler } from '@syncfusion/ej2-base';
import { createElement, classList, append } from '@syncfusion/ej2-base';
import { Pager, IRender } from './pager';
/**
* `NumericContainer` module handles rendering and refreshing numeric container.
*/
export class NumericContainer implements IRender {
//Internal variables
private element: Element;
private first: Element;
private prev: Element;
private PP: Element;
private NP: Element;
private next: Element;
private last: Element;
private links: HTMLElement[];
private pagerElement: Element;
//Module declarations
private pagerModule: Pager;
/**
* Constructor for numericContainer module
*
* @param {Pager} pagerModule - specifies the pagerModule
* @hidden
*/
constructor(pagerModule?: Pager) {
this.pagerModule = pagerModule;
}
/**
* The function is used to render numericContainer
*
* @returns {void}
* @hidden
*/
public render(): void {
this.pagerElement = this.pagerModule.element;
this.renderNumericContainer();
this.refreshNumericLinks();
this.wireEvents();
}
/**
* Refreshes the numeric container of Pager.
*
* @returns {void}
*/
public refresh(): void {
this.pagerModule.updateTotalPages();
if (this.links.length) {
this.updateLinksHtml();
}
this.refreshAriaAttrLabel();
this.updateStyles();
}
/**
* The function is used to refresh refreshNumericLinks
*
* @returns {void}
* @hidden
*/
public refreshNumericLinks(): void {
let link: HTMLElement;
const pagerObj: Pager = this.pagerModule;
const div: Element = pagerObj.element.querySelector('.e-numericcontainer');
const frag: DocumentFragment = document.createDocumentFragment();
div.innerHTML = '';
for (let i: number = 1; i <= pagerObj.pageCount; i++) {
link = createElement('a', {
className: 'e-link e-numericitem e-spacing e-pager-default',
attrs: { role: 'link', tabindex: '-1', 'aria-label': 'Page ' + i + ' of ' + pagerObj.totalPages + ' Pages',
href: 'javascript:void(0);' , name: 'Goto page' + i }
});
if (pagerObj.currentPage === i) {
classList(link, ['e-currentitem', 'e-active'], ['e-pager-default']);
link.setAttribute('aria-selected', 'true');
}
frag.appendChild(link);
}
div.appendChild(frag);
this.links = [].slice.call((<HTMLElement>div).childNodes);
}
/**
* Binding events to the element while component creation
*
* @returns {void}
* @hidden
*/
public wireEvents(): void {
EventHandler.add(this.pagerElement, 'click', this.clickHandler, this);
}
/**
* Unbinding events from the element while component destroy
*
* @returns {void}
* @hidden
*/
public unwireEvents(): void {
EventHandler.remove(this.pagerModule.element, 'click', this.clickHandler);
}
/**
* To destroy the PagerMessage
*
* @function destroy
* @returns {void}
* @hidden
*/
public destroy(): void {
this.unwireEvents();
}
private refreshAriaAttrLabel(): void {
const pagerObj: Pager = this.pagerModule;
const numericContainer: Element = pagerObj.element.querySelector('.e-numericcontainer');
const links: NodeList = numericContainer.querySelectorAll('a');
for (let i: number = 0; i < links.length; i++) {
if ((<Element>links[i]).hasAttribute('aria-label') && (<Element>links[i]).hasAttribute('index')) {
(<Element>links[i]).setAttribute('aria-label', 'Page ' + (<Element>links[i]).getAttribute('index') + ' of ' + pagerObj.totalPages + ' Pages');
}
}
}
private renderNumericContainer(): void {
this.element = createElement('div', {
className: 'e-pagercontainer', attrs: { 'role': 'navigation' }
});
this.renderFirstNPrev(this.element);
this.renderPrevPagerSet(this.element);
this.element.appendChild(createElement('div', { className: 'e-numericcontainer' }));
this.renderNextPagerSet(this.element);
this.renderNextNLast(this.element);
this.pagerModule.element.appendChild(this.element);
}
private renderFirstNPrev(pagerContainer: Element): void {
this.first = createElement(
'div', {
className: 'e-first e-icons e-icon-first',
attrs: {
title: this.pagerModule.getLocalizedLabel('firstPageTooltip'),
'aria-label': this.pagerModule.getLocalizedLabel('firstPageTooltip'),
tabindex: '-1'
}
});
this.prev = createElement(
'div', {
className: 'e-prev e-icons e-icon-prev',
attrs: {
title: this.pagerModule.getLocalizedLabel('previousPageTooltip'),
'aria-label': this.pagerModule.getLocalizedLabel('previousPageTooltip'),
tabindex: '-1'
}
});
append([this.first, this.prev], pagerContainer);
}
private renderPrevPagerSet(pagerContainer: Element): void {
const prevPager: Element = createElement('div');
this.PP = createElement(
'a', {
className: 'e-link e-pp e-spacing', innerHTML: '...',
attrs: {
title: this.pagerModule.getLocalizedLabel('previousPagerTooltip'), role: 'link',
'aria-label': this.pagerModule.getLocalizedLabel('previousPagerTooltip'),
tabindex: '-1',
name: this.pagerModule.getLocalizedLabel('previousPagerTooltip'),
href: 'javascript:void(0);'
}
});
prevPager.appendChild(this.PP);
pagerContainer.appendChild(prevPager);
}
private renderNextPagerSet(pagerContainer: Element): void {
const nextPager: Element = createElement('div');
this.NP = createElement(
'a', {
className: 'e-link e-np e-spacing',
innerHTML: '...', attrs: {
title: this.pagerModule.getLocalizedLabel('nextPagerTooltip'), role: 'link',
'aria-label': this.pagerModule.getLocalizedLabel('nextPagerTooltip'),
tabindex: '-1',
name: this.pagerModule.getLocalizedLabel('nextPagerTooltip'),
href: 'javascript:void(0);'
}
});
nextPager.appendChild(this.NP);
pagerContainer.appendChild(nextPager);
}
private renderNextNLast(pagerContainer: Element): void {
this.next = createElement(
'div', {
className: 'e-next e-icons e-icon-next',
attrs: {
title: this.pagerModule.getLocalizedLabel('nextPageTooltip'),
'aria-label': this.pagerModule.getLocalizedLabel('nextPageTooltip'),
tabindex: '-1'
}
});
this.last = createElement(
'div', {
className: 'e-last e-icons e-icon-last',
attrs: {
title: this.pagerModule.getLocalizedLabel('lastPageTooltip'),
'aria-label': this.pagerModule.getLocalizedLabel('lastPageTooltip'),
tabindex: '-1'
}
});
append([this.next, this.last], pagerContainer);
}
private clickHandler(e: Event): boolean {
const pagerObj: Pager = this.pagerModule;
const target: Element = <Element>e.target as Element;
pagerObj.previousPageNo = pagerObj.currentPage;
if (!target.classList.contains('e-disable') && !isNullOrUndefined(target.getAttribute('index'))) {
pagerObj.currentPage = parseInt(target.getAttribute('index'), 10);
pagerObj.dataBind();
}
return false;
}
private updateLinksHtml(): void {
const pagerObj: Pager = this.pagerModule;
let currentPageSet: number;
let pageNo: number;
pagerObj.currentPage = pagerObj.totalPages === 1 ? 1 : pagerObj.currentPage;
if (pagerObj.currentPage > pagerObj.totalPages && pagerObj.totalPages) {
pagerObj.currentPage = pagerObj.totalPages;
}
currentPageSet = parseInt((pagerObj.currentPage / pagerObj.pageCount).toString(), 10);
if (pagerObj.currentPage % pagerObj.pageCount === 0 && currentPageSet > 0) {
currentPageSet = currentPageSet - 1;
}
for (let i: number = 0; i < pagerObj.pageCount; i++) {
pageNo = (currentPageSet * pagerObj.pageCount) + 1 + i;
if (pageNo <= pagerObj.totalPages) {
this.links[i].style.display = '';
this.links[i].setAttribute('index', pageNo.toString());
this.links[i].innerHTML = !pagerObj.customText ? pageNo.toString() : pagerObj.customText + pageNo;
if (pagerObj.currentPage !== pageNo) {
this.links[i].classList.add('e-pager-default');
} else {
this.links[i].classList.remove('e-pager-default');
}
} else {
this.links[i].innerHTML = !pagerObj.customText ? pageNo.toString() : pagerObj.customText + pageNo;
this.links[i].style.display = 'none';
}
classList(this.links[i], [], ['e-currentitem', 'e-active']);
this.links[i].removeAttribute('aria-selected');
}
this.first.setAttribute('index', '1');
this.last.setAttribute('index', pagerObj.totalPages.toString());
this.prev.setAttribute('index', (pagerObj.currentPage - 1).toString());
this.next.setAttribute('index', (pagerObj.currentPage + 1).toString());
this.pagerElement.querySelector('.e-mfirst').setAttribute('index', '1');
this.pagerElement.querySelector('.e-mlast').setAttribute('index', pagerObj.totalPages.toString());
this.pagerElement.querySelector('.e-mprev').setAttribute('index', (pagerObj.currentPage - 1).toString());
this.pagerElement.querySelector('.e-mnext').setAttribute('index', (pagerObj.currentPage + 1).toString());
this.PP.setAttribute('index', (parseInt(this.links[0].getAttribute('index'), 10) - pagerObj.pageCount).toString());
this.NP.setAttribute('index', (parseInt(this.links[this.links.length - 1].getAttribute('index'), 10) + 1).toString());
}
private updateStyles(): void {
this.updateFirstNPrevStyles();
this.updatePrevPagerSetStyles();
this.updateNextPagerSetStyles();
this.updateNextNLastStyles();
if (this.links.length) {
classList(this.links[(this.pagerModule.currentPage - 1) % this.pagerModule.pageCount], ['e-currentitem', 'e-active'], []);
this.links[(this.pagerModule.currentPage - 1) % this.pagerModule.pageCount].setAttribute('aria-selected', 'true');
}
}
private updateFirstNPrevStyles(): void {
const firstPage: string[] = ['e-firstpage', 'e-pager-default'];
const firstPageDisabled: string[] = ['e-firstpagedisabled', 'e-disable'];
const prevPage: string[] = ['e-prevpage', 'e-pager-default'];
const prevPageDisabled: string[] = ['e-prevpagedisabled', 'e-disable'];
if (this.pagerModule.totalPages > 0 && this.pagerModule.currentPage > 1) {
classList(this.prev, prevPage, prevPageDisabled);
classList(this.first, firstPage, firstPageDisabled);
classList(this.pagerElement.querySelector('.e-mfirst'), firstPage, firstPageDisabled);
classList(this.pagerElement.querySelector('.e-mprev'), prevPage, prevPageDisabled);
} else {
classList(this.prev, prevPageDisabled, prevPage);
classList(this.first, firstPageDisabled, firstPage);
classList(this.pagerElement.querySelector('.e-mprev'), prevPageDisabled, prevPage);
classList(this.pagerElement.querySelector('.e-mfirst'), firstPageDisabled, firstPage);
}
}
private updatePrevPagerSetStyles(): void {
if (this.pagerModule.currentPage > this.pagerModule.pageCount) {
classList(this.PP, ['e-numericitem', 'e-pager-default'], ['e-nextprevitemdisabled', 'e-disable']);
} else {
classList(this.PP, ['e-nextprevitemdisabled', 'e-disable'], ['e-numericitem', 'e-pager-default']);
}
}
private updateNextPagerSetStyles(): void {
const pagerObj: Pager = this.pagerModule;
const firstPage: string = this.links[0].innerHTML.replace(pagerObj.customText, '');
if (!firstPage.length || !this.links.length || (parseInt(firstPage, 10) + pagerObj.pageCount > pagerObj.totalPages)) {
classList(this.NP, ['e-nextprevitemdisabled', 'e-disable'], ['e-numericitem', 'e-pager-default']);
} else {
classList(this.NP, ['e-numericitem', 'e-pager-default'], ['e-nextprevitemdisabled', 'e-disable']);
}
}
private updateNextNLastStyles(): void {
const lastPage: string[] = ['e-lastpage', 'e-pager-default'];
const lastPageDisabled: string[] = ['e-lastpagedisabled', 'e-disable'];
const nextPage: string[] = ['e-nextpage', 'e-pager-default'];
const nextPageDisabled: string[] = ['e-nextpagedisabled', 'e-disable'];
const pagerObj: Pager = this.pagerModule;
if (pagerObj.currentPage === pagerObj.totalPages || pagerObj.totalRecordsCount === 0) {
classList(this.last, lastPageDisabled, lastPage);
classList(this.next, nextPageDisabled, nextPage);
classList(this.pagerElement.querySelector('.e-mlast'), lastPageDisabled, lastPage);
classList(this.pagerElement.querySelector('.e-mnext'), nextPageDisabled, nextPage);
} else {
classList(this.last, lastPage, lastPageDisabled);
classList(this.next, nextPage, nextPageDisabled);
classList(this.pagerElement.querySelector('.e-mlast'), lastPage, lastPageDisabled);
classList(this.pagerElement.querySelector('.e-mnext'), nextPage, nextPageDisabled);
}
}
} | the_stack |
import * as coreClient from "@azure/core-client";
export const LocationListResult: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "LocationListResult",
modelProperties: {
value: {
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Location"
}
}
}
}
}
}
};
export const Location: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "Location",
modelProperties: {
id: {
serializedName: "id",
readOnly: true,
type: {
name: "String"
}
},
subscriptionId: {
serializedName: "subscriptionId",
readOnly: true,
type: {
name: "String"
}
},
name: {
serializedName: "name",
readOnly: true,
type: {
name: "String"
}
},
type: {
serializedName: "type",
readOnly: true,
type: {
name: "Enum",
allowedValues: ["Region", "EdgeZone"]
}
},
displayName: {
serializedName: "displayName",
readOnly: true,
type: {
name: "String"
}
},
regionalDisplayName: {
serializedName: "regionalDisplayName",
readOnly: true,
type: {
name: "String"
}
},
metadata: {
serializedName: "metadata",
type: {
name: "Composite",
className: "LocationMetadata"
}
}
}
}
};
export const LocationMetadata: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "LocationMetadata",
modelProperties: {
regionType: {
serializedName: "regionType",
readOnly: true,
type: {
name: "String"
}
},
regionCategory: {
serializedName: "regionCategory",
readOnly: true,
type: {
name: "String"
}
},
geographyGroup: {
serializedName: "geographyGroup",
readOnly: true,
type: {
name: "String"
}
},
longitude: {
serializedName: "longitude",
readOnly: true,
type: {
name: "String"
}
},
latitude: {
serializedName: "latitude",
readOnly: true,
type: {
name: "String"
}
},
physicalLocation: {
serializedName: "physicalLocation",
readOnly: true,
type: {
name: "String"
}
},
pairedRegion: {
serializedName: "pairedRegion",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "PairedRegion"
}
}
}
},
homeLocation: {
serializedName: "homeLocation",
readOnly: true,
type: {
name: "String"
}
}
}
}
};
export const PairedRegion: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "PairedRegion",
modelProperties: {
name: {
serializedName: "name",
readOnly: true,
type: {
name: "String"
}
},
id: {
serializedName: "id",
readOnly: true,
type: {
name: "String"
}
},
subscriptionId: {
serializedName: "subscriptionId",
readOnly: true,
type: {
name: "String"
}
}
}
}
};
export const CloudError: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "CloudError",
modelProperties: {
error: {
serializedName: "error",
type: {
name: "Composite",
className: "ErrorResponse"
}
}
}
}
};
export const ErrorResponse: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ErrorResponse",
modelProperties: {
code: {
serializedName: "code",
readOnly: true,
type: {
name: "String"
}
},
message: {
serializedName: "message",
readOnly: true,
type: {
name: "String"
}
},
target: {
serializedName: "target",
readOnly: true,
type: {
name: "String"
}
},
details: {
serializedName: "details",
readOnly: true,
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ErrorResponse"
}
}
}
},
additionalInfo: {
serializedName: "additionalInfo",
readOnly: true,
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ErrorAdditionalInfo"
}
}
}
}
}
}
};
export const ErrorAdditionalInfo: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ErrorAdditionalInfo",
modelProperties: {
type: {
serializedName: "type",
readOnly: true,
type: {
name: "String"
}
},
info: {
serializedName: "info",
readOnly: true,
type: {
name: "Dictionary",
value: { type: { name: "any" } }
}
}
}
}
};
export const Subscription: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "Subscription",
modelProperties: {
id: {
serializedName: "id",
readOnly: true,
type: {
name: "String"
}
},
subscriptionId: {
serializedName: "subscriptionId",
readOnly: true,
type: {
name: "String"
}
},
displayName: {
serializedName: "displayName",
readOnly: true,
type: {
name: "String"
}
},
tenantId: {
serializedName: "tenantId",
readOnly: true,
type: {
name: "String"
}
},
state: {
serializedName: "state",
readOnly: true,
type: {
name: "Enum",
allowedValues: ["Enabled", "Warned", "PastDue", "Disabled", "Deleted"]
}
},
subscriptionPolicies: {
serializedName: "subscriptionPolicies",
type: {
name: "Composite",
className: "SubscriptionPolicies"
}
},
authorizationSource: {
serializedName: "authorizationSource",
type: {
name: "String"
}
},
managedByTenants: {
serializedName: "managedByTenants",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "ManagedByTenant"
}
}
}
},
tags: {
serializedName: "tags",
type: {
name: "Dictionary",
value: { type: { name: "String" } }
}
}
}
}
};
export const SubscriptionPolicies: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "SubscriptionPolicies",
modelProperties: {
locationPlacementId: {
serializedName: "locationPlacementId",
readOnly: true,
type: {
name: "String"
}
},
quotaId: {
serializedName: "quotaId",
readOnly: true,
type: {
name: "String"
}
},
spendingLimit: {
serializedName: "spendingLimit",
readOnly: true,
type: {
name: "Enum",
allowedValues: ["On", "Off", "CurrentPeriodOff"]
}
}
}
}
};
export const ManagedByTenant: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ManagedByTenant",
modelProperties: {
tenantId: {
serializedName: "tenantId",
readOnly: true,
type: {
name: "String"
}
}
}
}
};
export const SubscriptionListResult: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "SubscriptionListResult",
modelProperties: {
value: {
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Subscription"
}
}
}
},
nextLink: {
serializedName: "nextLink",
required: true,
type: {
name: "String"
}
}
}
}
};
export const TenantListResult: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "TenantListResult",
modelProperties: {
value: {
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "TenantIdDescription"
}
}
}
},
nextLink: {
serializedName: "nextLink",
required: true,
type: {
name: "String"
}
}
}
}
};
export const TenantIdDescription: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "TenantIdDescription",
modelProperties: {
id: {
serializedName: "id",
readOnly: true,
type: {
name: "String"
}
},
tenantId: {
serializedName: "tenantId",
readOnly: true,
type: {
name: "String"
}
},
tenantCategory: {
serializedName: "tenantCategory",
readOnly: true,
type: {
name: "Enum",
allowedValues: ["Home", "ProjectedBy", "ManagedBy"]
}
},
country: {
serializedName: "country",
readOnly: true,
type: {
name: "String"
}
},
countryCode: {
serializedName: "countryCode",
readOnly: true,
type: {
name: "String"
}
},
displayName: {
serializedName: "displayName",
readOnly: true,
type: {
name: "String"
}
},
domains: {
serializedName: "domains",
readOnly: true,
type: {
name: "Sequence",
element: {
type: {
name: "String"
}
}
}
},
defaultDomain: {
serializedName: "defaultDomain",
readOnly: true,
type: {
name: "String"
}
},
tenantType: {
serializedName: "tenantType",
readOnly: true,
type: {
name: "String"
}
},
tenantBrandingLogoUrl: {
serializedName: "tenantBrandingLogoUrl",
readOnly: true,
type: {
name: "String"
}
}
}
}
};
export const ResourceName: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "ResourceName",
modelProperties: {
name: {
serializedName: "name",
required: true,
type: {
name: "String"
}
},
type: {
serializedName: "type",
required: true,
type: {
name: "String"
}
}
}
}
};
export const CheckResourceNameResult: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "CheckResourceNameResult",
modelProperties: {
name: {
serializedName: "name",
type: {
name: "String"
}
},
type: {
serializedName: "type",
type: {
name: "String"
}
},
status: {
serializedName: "status",
type: {
name: "String"
}
}
}
}
};
export const Operation: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "Operation",
modelProperties: {
name: {
serializedName: "name",
type: {
name: "String"
}
},
display: {
serializedName: "display",
type: {
name: "Composite",
className: "OperationDisplay"
}
}
}
}
};
export const OperationDisplay: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "OperationDisplay",
modelProperties: {
provider: {
serializedName: "provider",
type: {
name: "String"
}
},
resource: {
serializedName: "resource",
type: {
name: "String"
}
},
operation: {
serializedName: "operation",
type: {
name: "String"
}
},
description: {
serializedName: "description",
type: {
name: "String"
}
}
}
}
};
export const OperationListResult: coreClient.CompositeMapper = {
type: {
name: "Composite",
className: "OperationListResult",
modelProperties: {
value: {
serializedName: "value",
type: {
name: "Sequence",
element: {
type: {
name: "Composite",
className: "Operation"
}
}
}
},
nextLink: {
serializedName: "nextLink",
type: {
name: "String"
}
}
}
}
}; | the_stack |
import * as Common from '../../core/common/common.js';
import * as Host from '../../core/host/host.js';
import * as i18n from '../../core/i18n/i18n.js';
import * as Platform from '../../core/platform/platform.js';
import * as SDK from '../../core/sdk/sdk.js';
import * as Bindings from '../../models/bindings/bindings.js';
import * as Logs from '../../models/logs/logs.js';
import * as Workspace from '../../models/workspace/workspace.js';
import * as NetworkForward from '../../panels/network/forward/forward.js';
import * as IconButton from '../../ui/components/icon_button/icon_button.js';
import * as PerfUI from '../../ui/legacy/components/perf_ui/perf_ui.js';
import * as UI from '../../ui/legacy/legacy.js';
import * as MobileThrottling from '../mobile_throttling/mobile_throttling.js';
import * as Search from '../search/search.js';
import {BlockedURLsPane} from './BlockedURLsPane.js';
import type {RequestActivatedEvent} from './NetworkDataGridNode.js';
import {Events} from './NetworkDataGridNode.js';
import {NetworkItemView} from './NetworkItemView.js';
import {NetworkLogView} from './NetworkLogView.js';
import {NetworkOverview} from './NetworkOverview.js';
import networkPanelStyles from './networkPanel.css.js';
import {NetworkSearchScope} from './NetworkSearchScope.js';
import type {NetworkTimeCalculator} from './NetworkTimeCalculator.js';
import {NetworkTransferTimeCalculator} from './NetworkTimeCalculator.js';
const UIStrings = {
/**
*@description Text to close something
*/
close: 'Close',
/**
*@description Title of a search bar or tool
*/
search: 'Search',
/**
*@description Text to clear content
*/
clear: 'Clear',
/**
*@description Tooltip text that appears on the setting to preserve log when hovering over the item
*/
doNotClearLogOnPageReload: 'Do not clear log on page reload / navigation',
/**
*@description Text to preserve the log after refreshing
*/
preserveLog: 'Preserve log',
/**
*@description Text to disable cache while DevTools is open
*/
disableCacheWhileDevtoolsIsOpen: 'Disable cache (while DevTools is open)',
/**
*@description Text in Network Config View of the Network panel
*/
disableCache: 'Disable cache',
/**
*@description Tooltip text that appears when hovering over the largeicon settings gear in show settings pane setting in network panel of the network panel
*/
networkSettings: 'Network settings',
/**
*@description Tooltip for expanding network request row setting
*/
showMoreInformationInRequestRows: 'Show more information in request rows',
/**
*@description Text in Network Panel of the Network panel
*/
useLargeRequestRows: 'Use large request rows',
/**
*@description Tooltip text for network request overview setting
*/
showOverviewOfNetworkRequests: 'Show overview of network requests',
/**
*@description Text in Network Panel of the Network panel
*/
showOverview: 'Show overview',
/**
*@description Tooltip for group by frame network setting
*/
groupRequestsByTopLevelRequest: 'Group requests by top level request frame',
/**
*@description Text in Network Panel of the Network panel
*/
groupByFrame: 'Group by frame',
/**
*@description Tooltip for capture screenshot network setting
*/
captureScreenshotsWhenLoadingA: 'Capture screenshots when loading a page',
/**
*@description Text to take screenshots
*/
captureScreenshots: 'Capture screenshots',
/**
* @description Tooltip text that appears when hovering over the largeicon load button in the
* Network Panel. This action prompts the user to select a HAR file to upload to DevTools.
*/
importHarFile: 'Import `HAR` file...',
/**
* @description Tooltip text that appears when hovering over the largeicon download button in the
* Network Panel. HAR is a file format (HTTP Archive) and should not be translated. This action
* triggers the download of a HAR file.
*/
exportHar: 'Export `HAR`...',
/**
*@description Text for throttling the network
*/
throttling: 'Throttling',
/**
*@description Text in Network Panel of the Network panel
*@example {Ctrl + R} PH1
*/
hitSToReloadAndCaptureFilmstrip: 'Hit {PH1} to reload and capture filmstrip.',
/**
*@description A context menu item in the Network Panel of the Network panel
*/
revealInNetworkPanel: 'Reveal in Network panel',
/**
*@description Text in Network Panel of the Network panel
*/
recordingFrames: 'Recording frames...',
/**
*@description Text in Network Panel of the Network panel
*/
fetchingFrames: 'Fetching frames...',
/**
* @description Text of a button in the Network panel's toolbar that open Network Conditions panel in the drawer.
*/
moreNetworkConditions: 'More network conditions…',
};
const str_ = i18n.i18n.registerUIStrings('panels/network/NetworkPanel.ts', UIStrings);
const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_);
let networkPanelInstance: NetworkPanel;
export class NetworkPanel extends UI.Panel.Panel implements UI.ContextMenu.Provider, UI.View.ViewLocationResolver {
private readonly networkLogShowOverviewSetting: Common.Settings.Setting<boolean>;
private readonly networkLogLargeRowsSetting: Common.Settings.Setting<boolean>;
private readonly networkRecordFilmStripSetting: Common.Settings.Setting<boolean>;
private readonly toggleRecordAction: UI.ActionRegistration.Action;
private pendingStopTimer!: number|undefined;
networkItemView: NetworkItemView|null;
private filmStripView: PerfUI.FilmStripView.FilmStripView|null;
private filmStripRecorder: FilmStripRecorder|null;
private currentRequest: SDK.NetworkRequest.NetworkRequest|null;
private readonly panelToolbar: UI.Toolbar.Toolbar;
private readonly rightToolbar: UI.Toolbar.Toolbar;
private readonly filterBar: UI.FilterBar.FilterBar;
private readonly settingsPane: UI.Widget.HBox;
private showSettingsPaneSetting: Common.Settings.Setting<boolean>;
private readonly filmStripPlaceholderElement: HTMLElement;
private readonly overviewPane: PerfUI.TimelineOverviewPane.TimelineOverviewPane;
private readonly networkOverview: NetworkOverview;
private readonly overviewPlaceholderElement: HTMLElement;
private readonly calculator: NetworkTransferTimeCalculator;
private splitWidget: UI.SplitWidget.SplitWidget;
private readonly sidebarLocation: UI.View.TabbedViewLocation;
private readonly progressBarContainer: HTMLDivElement;
networkLogView: NetworkLogView;
private readonly fileSelectorElement: HTMLElement;
private readonly detailsWidget: UI.Widget.VBox;
private readonly closeButtonElement: HTMLDivElement;
private preserveLogSetting: Common.Settings.Setting<boolean>;
recordLogSetting: Common.Settings.Setting<boolean>;
private readonly throttlingSelect: UI.Toolbar.ToolbarComboBox;
constructor() {
super('network');
this.networkLogShowOverviewSetting =
Common.Settings.Settings.instance().createSetting('networkLogShowOverview', true);
this.networkLogLargeRowsSetting = Common.Settings.Settings.instance().createSetting('networkLogLargeRows', false);
this.networkRecordFilmStripSetting =
Common.Settings.Settings.instance().createSetting('networkRecordFilmStripSetting', false);
this.toggleRecordAction =
(UI.ActionRegistry.ActionRegistry.instance().action('network.toggle-recording') as
UI.ActionRegistration.Action);
this.networkItemView = null;
this.filmStripView = null;
this.filmStripRecorder = null;
this.currentRequest = null;
const panel = new UI.Widget.VBox();
const networkToolbarContainer = panel.contentElement.createChild('div', 'network-toolbar-container');
this.panelToolbar = new UI.Toolbar.Toolbar('', networkToolbarContainer);
this.panelToolbar.makeWrappable(true);
this.rightToolbar = new UI.Toolbar.Toolbar('', networkToolbarContainer);
this.filterBar = new UI.FilterBar.FilterBar('networkPanel', true);
this.filterBar.show(panel.contentElement);
this.filterBar.addEventListener(UI.FilterBar.FilterBarEvents.Changed, this.handleFilterChanged.bind(this));
this.settingsPane = new UI.Widget.HBox();
this.settingsPane.element.classList.add('network-settings-pane');
this.settingsPane.show(panel.contentElement);
this.showSettingsPaneSetting =
Common.Settings.Settings.instance().createSetting('networkShowSettingsToolbar', false);
this.showSettingsPaneSetting.addChangeListener(this.updateSettingsPaneVisibility.bind(this));
this.updateSettingsPaneVisibility();
this.filmStripPlaceholderElement = panel.contentElement.createChild('div', 'network-film-strip-placeholder');
// Create top overview component.
this.overviewPane = new PerfUI.TimelineOverviewPane.TimelineOverviewPane('network');
this.overviewPane.addEventListener(
PerfUI.TimelineOverviewPane.Events.WindowChanged, this.onWindowChanged.bind(this));
this.overviewPane.element.id = 'network-overview-panel';
this.networkOverview = new NetworkOverview();
this.overviewPane.setOverviewControls([this.networkOverview]);
this.overviewPlaceholderElement = panel.contentElement.createChild('div');
this.calculator = new NetworkTransferTimeCalculator();
this.splitWidget = new UI.SplitWidget.SplitWidget(true, false, 'networkPanelSplitViewState');
this.splitWidget.hideMain();
this.splitWidget.show(panel.contentElement);
panel.setDefaultFocusedChild(this.filterBar);
const initialSidebarWidth = 225;
const splitWidget = new UI.SplitWidget.SplitWidget(true, false, 'networkPanelSidebarState', initialSidebarWidth);
splitWidget.hideSidebar();
splitWidget.enableShowModeSaving();
splitWidget.show(this.element);
this.sidebarLocation = UI.ViewManager.ViewManager.instance().createTabbedLocation(async () => {
UI.ViewManager.ViewManager.instance().showView('network');
splitWidget.showBoth();
}, 'network-sidebar', true);
const tabbedPane = this.sidebarLocation.tabbedPane();
tabbedPane.setMinimumSize(100, 25);
tabbedPane.element.classList.add('network-tabbed-pane');
tabbedPane.element.addEventListener('keydown', event => {
if (event.key !== Platform.KeyboardUtilities.ESCAPE_KEY) {
return;
}
splitWidget.hideSidebar();
event.consume();
});
const closeSidebar = new UI.Toolbar.ToolbarButton(i18nString(UIStrings.close), 'largeicon-delete');
closeSidebar.addEventListener(UI.Toolbar.ToolbarButton.Events.Click, () => splitWidget.hideSidebar());
tabbedPane.rightToolbar().appendToolbarItem(closeSidebar);
splitWidget.setSidebarWidget(tabbedPane);
splitWidget.setMainWidget(panel);
splitWidget.setDefaultFocusedChild(panel);
this.setDefaultFocusedChild(splitWidget);
this.progressBarContainer = document.createElement('div');
this.networkLogView =
new NetworkLogView(this.filterBar, this.progressBarContainer, this.networkLogLargeRowsSetting);
this.splitWidget.setSidebarWidget(this.networkLogView);
this.fileSelectorElement =
(UI.UIUtils.createFileSelectorElement(this.networkLogView.onLoadFromFile.bind(this.networkLogView)) as
HTMLElement);
panel.element.appendChild(this.fileSelectorElement);
this.detailsWidget = new UI.Widget.VBox();
this.detailsWidget.element.classList.add('network-details-view');
this.splitWidget.setMainWidget(this.detailsWidget);
this.closeButtonElement = document.createElement('div', {is: 'dt-close-button'});
this.closeButtonElement.addEventListener('click', async () => {
const action = UI.ActionRegistry.ActionRegistry.instance().action('network.hide-request-details');
if (action) {
await action.execute();
}
}, false);
this.closeButtonElement.style.margin = '0 5px';
this.networkLogShowOverviewSetting.addChangeListener(this.toggleShowOverview, this);
this.networkLogLargeRowsSetting.addChangeListener(this.toggleLargerRequests, this);
this.networkRecordFilmStripSetting.addChangeListener(this.toggleRecordFilmStrip, this);
this.preserveLogSetting = Common.Settings.Settings.instance().moduleSetting('network_log.preserve-log');
this.recordLogSetting = Common.Settings.Settings.instance().moduleSetting('network_log.record-log');
this.recordLogSetting.addChangeListener(({data}) => this.toggleRecord(data));
this.throttlingSelect = this.createThrottlingConditionsSelect();
this.setupToolbarButtons(splitWidget);
this.toggleRecord(this.recordLogSetting.get());
this.toggleShowOverview();
this.toggleLargerRequests();
this.toggleRecordFilmStrip();
this.updateUI();
SDK.TargetManager.TargetManager.instance().addModelListener(
SDK.ResourceTreeModel.ResourceTreeModel, SDK.ResourceTreeModel.Events.WillReloadPage, this.willReloadPage,
this);
SDK.TargetManager.TargetManager.instance().addModelListener(
SDK.ResourceTreeModel.ResourceTreeModel, SDK.ResourceTreeModel.Events.Load, this.load, this);
this.networkLogView.addEventListener(Events.RequestSelected, this.onRequestSelected, this);
this.networkLogView.addEventListener(Events.RequestActivated, this.onRequestActivated, this);
Logs.NetworkLog.NetworkLog.instance().addEventListener(
Logs.NetworkLog.Events.RequestAdded, this.onUpdateRequest, this);
Logs.NetworkLog.NetworkLog.instance().addEventListener(
Logs.NetworkLog.Events.RequestUpdated, this.onUpdateRequest, this);
Logs.NetworkLog.NetworkLog.instance().addEventListener(Logs.NetworkLog.Events.Reset, this.onNetworkLogReset, this);
}
static instance(opts: {
forceNew: boolean|null,
} = {forceNew: null}): NetworkPanel {
const {forceNew} = opts;
if (!networkPanelInstance || forceNew) {
networkPanelInstance = new NetworkPanel();
}
return networkPanelInstance;
}
static revealAndFilter(filters: {
filterType: NetworkForward.UIFilter.FilterType|null,
filterValue: string,
}[]): Promise<void> {
const panel = NetworkPanel.instance();
let filterString = '';
for (const filter of filters) {
if (filter.filterType) {
filterString += `${filter.filterType}:${filter.filterValue} `;
} else {
filterString += `${filter.filterValue} `;
}
}
panel.networkLogView.setTextFilterValue(filterString);
return UI.ViewManager.ViewManager.instance().showView('network');
}
static async selectAndShowRequest(
request: SDK.NetworkRequest.NetworkRequest, tab: NetworkForward.UIRequestLocation.UIRequestTabs,
options?: NetworkForward.UIRequestLocation.FilterOptions): Promise<void> {
const panel = NetworkPanel.instance();
await panel.selectAndActivateRequest(request, tab, options);
}
throttlingSelectForTest(): UI.Toolbar.ToolbarComboBox {
return this.throttlingSelect;
}
private onWindowChanged(event: Common.EventTarget.EventTargetEvent<PerfUI.TimelineOverviewPane.WindowChangedEvent>):
void {
const startTime = Math.max(this.calculator.minimumBoundary(), event.data.startTime / 1000);
const endTime = Math.min(this.calculator.maximumBoundary(), event.data.endTime / 1000);
this.networkLogView.setWindow(startTime, endTime);
}
private async searchToggleClick(): Promise<void> {
const action = UI.ActionRegistry.ActionRegistry.instance().action('network.search');
if (action) {
await action.execute();
}
}
private setupToolbarButtons(splitWidget: UI.SplitWidget.SplitWidget): void {
const searchToggle = new UI.Toolbar.ToolbarToggle(i18nString(UIStrings.search), 'largeicon-search');
function updateSidebarToggle(): void {
const isSidebarShowing = splitWidget.showMode() !== UI.SplitWidget.ShowMode.OnlyMain;
searchToggle.setToggled(isSidebarShowing);
if (!isSidebarShowing) {
(searchToggle.element as HTMLElement).focus();
}
}
this.panelToolbar.appendToolbarItem(UI.Toolbar.Toolbar.createActionButton(this.toggleRecordAction));
const clearButton = new UI.Toolbar.ToolbarButton(i18nString(UIStrings.clear), 'largeicon-clear');
clearButton.addEventListener(
UI.Toolbar.ToolbarButton.Events.Click, () => Logs.NetworkLog.NetworkLog.instance().reset(true), this);
this.panelToolbar.appendToolbarItem(clearButton);
this.panelToolbar.appendSeparator();
this.panelToolbar.appendToolbarItem(this.filterBar.filterButton());
updateSidebarToggle();
splitWidget.addEventListener(UI.SplitWidget.Events.ShowModeChanged, updateSidebarToggle);
searchToggle.addEventListener(UI.Toolbar.ToolbarButton.Events.Click, () => {
this.searchToggleClick();
});
this.panelToolbar.appendToolbarItem(searchToggle);
this.panelToolbar.appendSeparator();
this.panelToolbar.appendToolbarItem(new UI.Toolbar.ToolbarSettingCheckbox(
this.preserveLogSetting, i18nString(UIStrings.doNotClearLogOnPageReload), i18nString(UIStrings.preserveLog)));
this.panelToolbar.appendSeparator();
const disableCacheCheckbox = new UI.Toolbar.ToolbarSettingCheckbox(
Common.Settings.Settings.instance().moduleSetting('cacheDisabled'),
i18nString(UIStrings.disableCacheWhileDevtoolsIsOpen), i18nString(UIStrings.disableCache));
this.panelToolbar.appendToolbarItem(disableCacheCheckbox);
this.panelToolbar.appendToolbarItem(this.throttlingSelect);
const networkConditionsIcon = new IconButton.Icon.Icon();
networkConditionsIcon.data = {
iconName: 'network_conditions_icon',
color: 'rgb(110 110 110)',
width: '18px',
height: '18px',
};
const networkConditionsButton =
new UI.Toolbar.ToolbarButton(i18nString(UIStrings.moreNetworkConditions), networkConditionsIcon);
networkConditionsButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click, () => {
UI.ViewManager.ViewManager.instance().showView('network.config');
}, this);
this.panelToolbar.appendToolbarItem(networkConditionsButton);
this.rightToolbar.appendToolbarItem(new UI.Toolbar.ToolbarItem(this.progressBarContainer));
this.rightToolbar.appendSeparator();
this.rightToolbar.appendToolbarItem(new UI.Toolbar.ToolbarSettingToggle(
this.showSettingsPaneSetting, 'largeicon-settings-gear', i18nString(UIStrings.networkSettings)));
const settingsToolbarLeft = new UI.Toolbar.Toolbar('', this.settingsPane.element);
settingsToolbarLeft.makeVertical();
settingsToolbarLeft.appendToolbarItem(new UI.Toolbar.ToolbarSettingCheckbox(
this.networkLogLargeRowsSetting, i18nString(UIStrings.showMoreInformationInRequestRows),
i18nString(UIStrings.useLargeRequestRows)));
settingsToolbarLeft.appendToolbarItem(new UI.Toolbar.ToolbarSettingCheckbox(
this.networkLogShowOverviewSetting, i18nString(UIStrings.showOverviewOfNetworkRequests),
i18nString(UIStrings.showOverview)));
const settingsToolbarRight = new UI.Toolbar.Toolbar('', this.settingsPane.element);
settingsToolbarRight.makeVertical();
settingsToolbarRight.appendToolbarItem(new UI.Toolbar.ToolbarSettingCheckbox(
Common.Settings.Settings.instance().moduleSetting('network.group-by-frame'),
i18nString(UIStrings.groupRequestsByTopLevelRequest), i18nString(UIStrings.groupByFrame)));
settingsToolbarRight.appendToolbarItem(new UI.Toolbar.ToolbarSettingCheckbox(
this.networkRecordFilmStripSetting, i18nString(UIStrings.captureScreenshotsWhenLoadingA),
i18nString(UIStrings.captureScreenshots)));
this.panelToolbar.appendSeparator();
const importHarButton = new UI.Toolbar.ToolbarButton(i18nString(UIStrings.importHarFile), 'largeicon-load');
importHarButton.addEventListener(
UI.Toolbar.ToolbarButton.Events.Click, () => this.fileSelectorElement.click(), this);
this.panelToolbar.appendToolbarItem(importHarButton);
const exportHarButton = new UI.Toolbar.ToolbarButton(i18nString(UIStrings.exportHar), 'largeicon-download');
exportHarButton.addEventListener(UI.Toolbar.ToolbarButton.Events.Click, _event => {
this.networkLogView.exportAll();
}, this);
this.panelToolbar.appendToolbarItem(exportHarButton);
}
private updateSettingsPaneVisibility(): void {
this.settingsPane.element.classList.toggle('hidden', !this.showSettingsPaneSetting.get());
}
private createThrottlingConditionsSelect(): UI.Toolbar.ToolbarComboBox {
const toolbarItem = new UI.Toolbar.ToolbarComboBox(null, i18nString(UIStrings.throttling));
toolbarItem.setMaxWidth(160);
MobileThrottling.ThrottlingManager.throttlingManager().decorateSelectWithNetworkThrottling(
toolbarItem.selectElement());
return toolbarItem;
}
toggleRecord(toggled: boolean): void {
this.toggleRecordAction.setToggled(toggled);
if (this.recordLogSetting.get() !== toggled) {
this.recordLogSetting.set(toggled);
}
this.networkLogView.setRecording(toggled);
if (!toggled && this.filmStripRecorder) {
this.filmStripRecorder.stopRecording(this.filmStripAvailable.bind(this));
}
}
private filmStripAvailable(filmStripModel: SDK.FilmStripModel.FilmStripModel|null): void {
if (!filmStripModel) {
return;
}
const calculator = this.networkLogView.timeCalculator();
if (this.filmStripView) {
this.filmStripView.setModel(
filmStripModel, calculator.minimumBoundary() * 1000, calculator.boundarySpan() * 1000);
}
this.networkOverview.setFilmStripModel(filmStripModel);
const timestamps = filmStripModel.frames().map(mapTimestamp);
function mapTimestamp(frame: SDK.FilmStripModel.Frame): number {
return frame.timestamp / 1000;
}
this.networkLogView.addFilmStripFrames(timestamps);
}
private onNetworkLogReset(event: Common.EventTarget.EventTargetEvent<Logs.NetworkLog.ResetEvent>): void {
const {clearIfPreserved} = event.data;
BlockedURLsPane.reset();
if (!this.preserveLogSetting.get() || clearIfPreserved) {
this.calculator.reset();
this.overviewPane.reset();
}
if (this.filmStripView) {
this.resetFilmStripView();
}
}
private willReloadPage(): void {
if (this.pendingStopTimer) {
clearTimeout(this.pendingStopTimer);
delete this.pendingStopTimer;
}
if (this.isShowing() && this.filmStripRecorder) {
this.filmStripRecorder.startRecording();
}
}
private load(): void {
if (this.filmStripRecorder && this.filmStripRecorder.isRecording()) {
this.pendingStopTimer = window.setTimeout(this.stopFilmStripRecording.bind(this), displayScreenshotDelay);
}
}
private stopFilmStripRecording(): void {
if (this.filmStripRecorder) {
this.filmStripRecorder.stopRecording(this.filmStripAvailable.bind(this));
}
delete this.pendingStopTimer;
}
private toggleLargerRequests(): void {
this.updateUI();
}
private toggleShowOverview(): void {
const toggled = this.networkLogShowOverviewSetting.get();
if (toggled) {
this.overviewPane.show(this.overviewPlaceholderElement);
} else {
this.overviewPane.detach();
}
this.doResize();
}
private toggleRecordFilmStrip(): void {
const toggled = this.networkRecordFilmStripSetting.get();
if (toggled && !this.filmStripRecorder) {
this.filmStripView = new PerfUI.FilmStripView.FilmStripView();
this.filmStripView.setMode(PerfUI.FilmStripView.Modes.FrameBased);
this.filmStripView.element.classList.add('network-film-strip');
this.filmStripRecorder = new FilmStripRecorder(this.networkLogView.timeCalculator(), this.filmStripView);
this.filmStripView.show(this.filmStripPlaceholderElement);
this.filmStripView.addEventListener(PerfUI.FilmStripView.Events.FrameSelected, this.onFilmFrameSelected, this);
this.filmStripView.addEventListener(PerfUI.FilmStripView.Events.FrameEnter, this.onFilmFrameEnter, this);
this.filmStripView.addEventListener(PerfUI.FilmStripView.Events.FrameExit, this.onFilmFrameExit, this);
this.resetFilmStripView();
}
if (!toggled && this.filmStripRecorder) {
if (this.filmStripView) {
this.filmStripView.detach();
}
this.filmStripView = null;
this.filmStripRecorder = null;
}
}
private resetFilmStripView(): void {
const reloadShortcut =
UI.ShortcutRegistry.ShortcutRegistry.instance().shortcutsForAction('inspector_main.reload')[0];
if (this.filmStripView) {
this.filmStripView.reset();
if (reloadShortcut) {
this.filmStripView.setStatusText(
i18nString(UIStrings.hitSToReloadAndCaptureFilmstrip, {PH1: reloadShortcut.title()}));
}
}
}
elementsToRestoreScrollPositionsFor(): Element[] {
return this.networkLogView.elementsToRestoreScrollPositionsFor();
}
wasShown(): void {
UI.Context.Context.instance().setFlavor(NetworkPanel, this);
this.registerCSSFiles([networkPanelStyles]);
// Record the network tool load time after the panel has loaded.
Host.userMetrics.panelLoaded('network', 'DevTools.Launch.Network');
}
willHide(): void {
UI.Context.Context.instance().setFlavor(NetworkPanel, null);
}
revealAndHighlightRequest(request: SDK.NetworkRequest.NetworkRequest): void {
this.hideRequestPanel();
if (request) {
this.networkLogView.revealAndHighlightRequest(request);
}
}
revealAndHighlightRequestWithId(request: NetworkForward.NetworkRequestId.NetworkRequestId): void {
this.hideRequestPanel();
if (request) {
this.networkLogView.revealAndHighlightRequestWithId(request);
}
}
async selectAndActivateRequest(
request: SDK.NetworkRequest.NetworkRequest, shownTab?: NetworkForward.UIRequestLocation.UIRequestTabs,
options?: NetworkForward.UIRequestLocation.FilterOptions): Promise<NetworkItemView|null> {
await UI.ViewManager.ViewManager.instance().showView('network');
this.networkLogView.selectRequest(request, options);
this.showRequestPanel(shownTab);
return this.networkItemView;
}
private handleFilterChanged(): void {
this.hideRequestPanel();
}
private onRowSizeChanged(): void {
this.updateUI();
}
private onRequestSelected(event: Common.EventTarget.EventTargetEvent<SDK.NetworkRequest.NetworkRequest|null>): void {
const request = event.data;
this.currentRequest = request;
this.networkOverview.setHighlightedRequest(request);
this.updateNetworkItemView();
}
private onRequestActivated(event: Common.EventTarget.EventTargetEvent<RequestActivatedEvent>): void {
const {showPanel, tab, takeFocus} = event.data;
if (showPanel) {
this.showRequestPanel(tab, takeFocus);
} else {
this.hideRequestPanel();
}
}
private showRequestPanel(shownTab?: NetworkForward.UIRequestLocation.UIRequestTabs, takeFocus?: boolean): void {
if (this.splitWidget.showMode() === UI.SplitWidget.ShowMode.Both && !shownTab && !takeFocus) {
// If panel is already shown, and we are not forcing a specific tab, return.
return;
}
this.clearNetworkItemView();
if (this.currentRequest) {
const networkItemView = this.createNetworkItemView(shownTab);
if (networkItemView && takeFocus) {
networkItemView.focus();
}
}
this.updateUI();
}
hideRequestPanel(): void {
this.clearNetworkItemView();
this.splitWidget.hideMain();
this.updateUI();
}
private updateNetworkItemView(): void {
if (this.splitWidget.showMode() === UI.SplitWidget.ShowMode.Both) {
this.clearNetworkItemView();
this.createNetworkItemView();
this.updateUI();
}
}
private clearNetworkItemView(): void {
if (this.networkItemView) {
this.networkItemView.detach();
this.networkItemView = null;
}
}
private createNetworkItemView(initialTab?: NetworkForward.UIRequestLocation.UIRequestTabs): NetworkItemView
|undefined {
if (!this.currentRequest) {
return;
}
this.networkItemView = new NetworkItemView(this.currentRequest, this.networkLogView.timeCalculator(), initialTab);
this.networkItemView.leftToolbar().appendToolbarItem(new UI.Toolbar.ToolbarItem(this.closeButtonElement));
this.networkItemView.show(this.detailsWidget.element);
this.splitWidget.showBoth();
return this.networkItemView;
}
private updateUI(): void {
if (this.detailsWidget) {
this.detailsWidget.element.classList.toggle(
'network-details-view-tall-header', this.networkLogLargeRowsSetting.get());
}
if (this.networkLogView) {
this.networkLogView.switchViewMode(!this.splitWidget.isResizable());
}
}
appendApplicableItems(this: NetworkPanel, event: Event, contextMenu: UI.ContextMenu.ContextMenu, target: Object):
void {
function reveal(this: NetworkPanel, request: SDK.NetworkRequest.NetworkRequest): void {
UI.ViewManager.ViewManager.instance()
.showView('network')
.then(this.networkLogView.resetFilter.bind(this.networkLogView))
.then(this.revealAndHighlightRequest.bind(this, request));
}
function appendRevealItem(this: NetworkPanel, request: SDK.NetworkRequest.NetworkRequest): void {
contextMenu.revealSection().appendItem(i18nString(UIStrings.revealInNetworkPanel), reveal.bind(this, request));
}
if ((event.target as Node).isSelfOrDescendant(this.element)) {
return;
}
if (target instanceof SDK.Resource.Resource) {
const resource = (target as SDK.Resource.Resource);
if (resource.request) {
appendRevealItem.call(this, resource.request);
}
return;
}
if (target instanceof Workspace.UISourceCode.UISourceCode) {
const uiSourceCode = (target as Workspace.UISourceCode.UISourceCode);
const resource = Bindings.ResourceUtils.resourceForURL(uiSourceCode.url());
if (resource && resource.request) {
appendRevealItem.call(this, resource.request);
}
return;
}
if (!(target instanceof SDK.NetworkRequest.NetworkRequest)) {
return;
}
const request = (target as SDK.NetworkRequest.NetworkRequest);
if (this.networkItemView && this.networkItemView.isShowing() && this.networkItemView.request() === request) {
return;
}
appendRevealItem.call(this, request);
}
private onFilmFrameSelected(event: Common.EventTarget.EventTargetEvent<number>): void {
const timestamp = event.data;
this.overviewPane.setWindowTimes(0, timestamp);
}
private onFilmFrameEnter(event: Common.EventTarget.EventTargetEvent<number>): void {
const timestamp = event.data;
this.networkOverview.selectFilmStripFrame(timestamp);
this.networkLogView.selectFilmStripFrame(timestamp / 1000);
}
private onFilmFrameExit(): void {
this.networkOverview.clearFilmStripFrame();
this.networkLogView.clearFilmStripFrame();
}
private onUpdateRequest(event: Common.EventTarget.EventTargetEvent<SDK.NetworkRequest.NetworkRequest>): void {
const request = event.data;
this.calculator.updateBoundaries(request);
// FIXME: Unify all time units across the frontend!
this.overviewPane.setBounds(this.calculator.minimumBoundary() * 1000, this.calculator.maximumBoundary() * 1000);
this.networkOverview.updateRequest(request);
this.overviewPane.scheduleUpdate();
}
resolveLocation(locationName: string): UI.View.ViewLocation|null {
if (locationName === 'network-sidebar') {
return this.sidebarLocation;
}
return null;
}
}
export const displayScreenshotDelay = 1000;
let contextMenuProviderInstance: ContextMenuProvider;
export class ContextMenuProvider implements UI.ContextMenu.Provider {
static instance(opts: {
forceNew: boolean|null,
} = {forceNew: null}): ContextMenuProvider {
const {forceNew} = opts;
if (!contextMenuProviderInstance || forceNew) {
contextMenuProviderInstance = new ContextMenuProvider();
}
return contextMenuProviderInstance;
}
appendApplicableItems(event: Event, contextMenu: UI.ContextMenu.ContextMenu, target: Object): void {
NetworkPanel.instance().appendApplicableItems(event, contextMenu, target);
}
}
let requestRevealerInstance: RequestRevealer;
export class RequestRevealer implements Common.Revealer.Revealer {
static instance(opts: {
forceNew: boolean|null,
} = {forceNew: null}): RequestRevealer {
const {forceNew} = opts;
if (!requestRevealerInstance || forceNew) {
requestRevealerInstance = new RequestRevealer();
}
return requestRevealerInstance;
}
reveal(request: Object): Promise<void> {
if (!(request instanceof SDK.NetworkRequest.NetworkRequest)) {
return Promise.reject(new Error('Internal error: not a network request'));
}
const panel = NetworkPanel.instance();
return UI.ViewManager.ViewManager.instance().showView('network').then(
panel.revealAndHighlightRequest.bind(panel, request));
}
}
let requestIdRevealerInstance: RequestIdRevealer;
export class RequestIdRevealer implements Common.Revealer.Revealer {
static instance(opts: {
forceNew: boolean|null,
} = {forceNew: null}): RequestIdRevealer {
const {forceNew} = opts;
if (!requestIdRevealerInstance || forceNew) {
requestIdRevealerInstance = new RequestIdRevealer();
}
return requestIdRevealerInstance;
}
reveal(requestId: Object): Promise<void> {
if (!(requestId instanceof NetworkForward.NetworkRequestId.NetworkRequestId)) {
return Promise.reject(new Error('Internal error: not a network request ID'));
}
const panel = NetworkPanel.instance();
return UI.ViewManager.ViewManager.instance().showView('network').then(
panel.revealAndHighlightRequestWithId.bind(panel, requestId));
}
}
let networkLogWithFilterRevealerInstance: NetworkLogWithFilterRevealer;
export class NetworkLogWithFilterRevealer implements Common.Revealer.Revealer {
static instance(opts: {
forceNew: boolean|null,
} = {forceNew: null}): NetworkLogWithFilterRevealer {
const {forceNew} = opts;
if (!networkLogWithFilterRevealerInstance || forceNew) {
networkLogWithFilterRevealerInstance = new NetworkLogWithFilterRevealer();
}
return networkLogWithFilterRevealerInstance;
}
reveal(request: Object): Promise<void> {
if (!(request instanceof NetworkForward.UIFilter.UIRequestFilter)) {
return Promise.reject(new Error('Internal error: not a UIRequestFilter'));
}
return NetworkPanel.revealAndFilter(request.filters);
}
}
export class FilmStripRecorder implements SDK.TracingManager.TracingManagerClient {
private tracingManager: SDK.TracingManager.TracingManager|null;
private resourceTreeModel: SDK.ResourceTreeModel.ResourceTreeModel|null;
private readonly timeCalculator: NetworkTimeCalculator;
private readonly filmStripView: PerfUI.FilmStripView.FilmStripView;
private tracingModel: SDK.TracingModel.TracingModel|null;
private callback: ((arg0: SDK.FilmStripModel.FilmStripModel|null) => void)|null;
constructor(timeCalculator: NetworkTimeCalculator, filmStripView: PerfUI.FilmStripView.FilmStripView) {
this.tracingManager = null;
this.resourceTreeModel = null;
this.timeCalculator = timeCalculator;
this.filmStripView = filmStripView;
this.tracingModel = null;
this.callback = null;
}
traceEventsCollected(events: SDK.TracingManager.EventPayload[]): void {
if (this.tracingModel) {
this.tracingModel.addEvents(events);
}
}
tracingComplete(): void {
if (!this.tracingModel || !this.tracingManager) {
return;
}
this.tracingModel.tracingComplete();
this.tracingManager = null;
if (this.callback) {
this.callback(
new SDK.FilmStripModel.FilmStripModel(this.tracingModel, this.timeCalculator.minimumBoundary() * 1000));
}
this.callback = null;
if (this.resourceTreeModel) {
this.resourceTreeModel.resumeReload();
}
this.resourceTreeModel = null;
}
tracingBufferUsage(): void {
}
eventsRetrievalProgress(_progress: number): void {
}
startRecording(): void {
this.filmStripView.reset();
this.filmStripView.setStatusText(i18nString(UIStrings.recordingFrames));
const tracingManagers = SDK.TargetManager.TargetManager.instance().models(SDK.TracingManager.TracingManager);
if (this.tracingManager || !tracingManagers.length) {
return;
}
this.tracingManager = tracingManagers[0];
if (!this.tracingManager) {
return;
}
this.resourceTreeModel = this.tracingManager.target().model(SDK.ResourceTreeModel.ResourceTreeModel);
if (this.tracingModel) {
this.tracingModel.dispose();
}
this.tracingModel = new SDK.TracingModel.TracingModel(new Bindings.TempFile.TempFileBackingStorage());
this.tracingManager.start(this, '-*,disabled-by-default-devtools.screenshot', '');
Host.userMetrics.actionTaken(Host.UserMetrics.Action.FilmStripStartedRecording);
}
isRecording(): boolean {
return Boolean(this.tracingManager);
}
stopRecording(callback: (arg0: SDK.FilmStripModel.FilmStripModel|null) => void): void {
if (!this.tracingManager) {
return;
}
this.tracingManager.stop();
if (this.resourceTreeModel) {
this.resourceTreeModel.suspendReload();
}
this.callback = callback;
this.filmStripView.setStatusText(i18nString(UIStrings.fetchingFrames));
}
}
let networkActionDelegateInstance: ActionDelegate;
export class ActionDelegate implements UI.ActionRegistration.ActionDelegate {
static instance(opts: {
forceNew: boolean|null,
}|undefined = {forceNew: null}): ActionDelegate {
const {forceNew} = opts;
if (!networkActionDelegateInstance || forceNew) {
networkActionDelegateInstance = new ActionDelegate();
}
return networkActionDelegateInstance;
}
handleAction(context: UI.Context.Context, actionId: string): boolean {
const panel = UI.Context.Context.instance().flavor(NetworkPanel);
console.assert(Boolean(panel && panel instanceof NetworkPanel));
if (!panel) {
return false;
}
switch (actionId) {
case 'network.toggle-recording': {
panel.toggleRecord(!panel.recordLogSetting.get());
return true;
}
case 'network.hide-request-details': {
if (!panel.networkItemView) {
return false;
}
panel.hideRequestPanel();
panel.networkLogView.resetFocus();
return true;
}
case 'network.search': {
const selection = UI.InspectorView.InspectorView.instance().element.window().getSelection();
if (selection) {
let queryCandidate = '';
if (selection.rangeCount) {
queryCandidate = selection.toString().replace(/\r?\n.*/, '');
}
SearchNetworkView.openSearch(queryCandidate);
return true;
}
}
}
return false;
}
}
let requestLocationRevealerInstance: RequestLocationRevealer;
export class RequestLocationRevealer implements Common.Revealer.Revealer {
static instance(opts: {
forceNew: boolean|null,
}|undefined = {forceNew: null}): RequestLocationRevealer {
const {forceNew} = opts;
if (!requestLocationRevealerInstance || forceNew) {
requestLocationRevealerInstance = new RequestLocationRevealer();
}
return requestLocationRevealerInstance;
}
async reveal(match: Object): Promise<void> {
const location = match as NetworkForward.UIRequestLocation.UIRequestLocation;
const view =
await NetworkPanel.instance().selectAndActivateRequest(location.request, location.tab, location.filterOptions);
if (!view) {
return;
}
if (location.searchMatch) {
await view.revealResponseBody(location.searchMatch.lineNumber);
}
if (location.header) {
view.revealHeader(location.header.section, location.header.header?.name);
}
}
}
let searchNetworkViewInstance: SearchNetworkView;
export class SearchNetworkView extends Search.SearchView.SearchView {
private constructor() {
super('network');
}
static instance(opts: {
forceNew: boolean|null,
} = {forceNew: null}): SearchNetworkView {
const {forceNew} = opts;
if (!searchNetworkViewInstance || forceNew) {
searchNetworkViewInstance = new SearchNetworkView();
}
return searchNetworkViewInstance;
}
static async openSearch(query: string, searchImmediately?: boolean): Promise<Search.SearchView.SearchView> {
await UI.ViewManager.ViewManager.instance().showView('network.search-network-tab');
const searchView = SearchNetworkView.instance();
searchView.toggle(query, Boolean(searchImmediately));
return searchView;
}
createScope(): Search.SearchConfig.SearchScope {
return new NetworkSearchScope();
}
} | the_stack |
import { ethers, waffle } from "hardhat";
import { expect, use } from "chai";
import { solidity } from "ethereum-waffle";
import {
InvariantTransactionData,
signCancelTransactionPayload,
signFulfillTransactionPayload,
VariantTransactionData,
getInvariantTransactionDigest,
getVariantTransactionDigest,
} from "@connext/nxtp-utils";
use(solidity);
import { hexlify, keccak256, randomBytes } from "ethers/lib/utils";
import { Wallet, BigNumber, BigNumberish, constants, Contract, ContractReceipt, utils, providers } from "ethers";
// import types
import { Counter, TransactionManager, RevertableERC20, ERC20, FeeERC20 } from "../typechain";
import {
assertReceiptEvent,
deployContract,
getOnchainBalance,
MAX_FEE_PER_GAS,
setBlockTime,
transferOwnershipOnContract,
} from "./utils";
import { getContractError } from "../src";
const { AddressZero } = constants;
const EmptyBytes = "0x";
const EmptyCallDataHash = keccak256(EmptyBytes);
const convertToPrepareArgs = (transaction: InvariantTransactionData, record: VariantTransactionData) => {
const args = {
invariantData: transaction,
amount: record.amount,
expiry: record.expiry,
encryptedCallData: EmptyBytes,
encodedBid: EmptyBytes,
bidSignature: EmptyBytes,
encodedMeta: EmptyBytes,
};
return args;
};
const convertToFulfillArgs = (
transaction: InvariantTransactionData,
record: VariantTransactionData,
relayerFee: string,
signature: string,
callData: string = EmptyBytes,
) => {
const args = {
txData: {
...transaction,
...record,
},
relayerFee,
signature,
callData,
encodedMeta: EmptyBytes,
};
return args;
};
const convertToCancelArgs = (
transaction: InvariantTransactionData,
record: VariantTransactionData,
signature: string,
) => {
const args = {
txData: {
...transaction,
...record,
},
signature,
encodedMeta: EmptyBytes,
};
return args;
};
const createFixtureLoader = waffle.createFixtureLoader;
describe("TransactionManager", function () {
const [wallet, router, user, receiver, other] = waffle.provider.getWallets() as Wallet[];
let transactionManager: TransactionManager;
let transactionManagerReceiverSide: TransactionManager;
let counter: Counter;
let tokenA: RevertableERC20;
let tokenB: RevertableERC20;
let feeToken: FeeERC20;
const sendingChainId = 1337;
const receivingChainId = 1338;
const fixture = async () => {
transactionManager = await deployContract<TransactionManager>("TransactionManager", sendingChainId);
transactionManagerReceiverSide = await deployContract<TransactionManager>("TransactionManager", receivingChainId);
tokenA = await deployContract<RevertableERC20>("RevertableERC20");
tokenB = await deployContract<RevertableERC20>("RevertableERC20");
feeToken = await deployContract<FeeERC20>("FeeERC20");
counter = await deployContract<Counter>("Counter");
return { transactionManager, transactionManagerReceiverSide, tokenA, tokenB, feeToken };
};
const addPrivileges = async (tm: TransactionManager, routers: string[], assets: string[]) => {
for (const router of routers) {
const tx = await tm.addRouter(router, { maxFeePerGas: MAX_FEE_PER_GAS });
await tx.wait();
expect(await tm.approvedRouters(router)).to.be.true;
}
for (const assetId of assets) {
const tx = await tm.addAssetId(assetId, { maxFeePerGas: MAX_FEE_PER_GAS });
await tx.wait();
expect(await tm.approvedAssets(assetId)).to.be.true;
}
};
let loadFixture: ReturnType<typeof createFixtureLoader>;
before("create fixture loader", async () => {
loadFixture = createFixtureLoader([wallet, router, user, receiver, other]);
});
beforeEach(async function () {
({ transactionManager, transactionManagerReceiverSide, tokenA, tokenB } = await loadFixture(fixture));
const liq = "10000";
let tx = await tokenA.connect(wallet).transfer(router.address, liq);
await tx.wait();
tx = await tokenB.connect(wallet).transfer(router.address, liq);
await tx.wait();
const prepareFunds = "10000";
tx = await tokenA.connect(wallet).transfer(user.address, prepareFunds);
await tx.wait();
tx = await tokenB.connect(wallet).transfer(user.address, prepareFunds);
await tx.wait();
const feeFunds = "10000";
tx = await feeToken.connect(wallet).transfer(user.address, feeFunds);
await tx.wait();
tx = await feeToken.connect(wallet).transfer(router.address, feeFunds);
await tx.wait();
// Prep contracts with router and assets
await addPrivileges(
transactionManager,
[router.address],
[AddressZero, tokenA.address, tokenB.address, feeToken.address],
);
await addPrivileges(
transactionManagerReceiverSide,
[router.address],
[AddressZero, tokenA.address, tokenB.address, feeToken.address],
);
});
const transferOwnership = async (newOwner: string = constants.AddressZero, caller: Wallet = wallet) => {
await transferOwnershipOnContract(newOwner, caller, transactionManager, wallet);
// expect(await transactionManager.renounced()).to.be.eq(newOwner === constants.AddressZero);
};
const getTransactionData = async (
txOverrides: Partial<InvariantTransactionData> = {},
recordOverrides: Partial<VariantTransactionData> = {},
): Promise<{ transaction: InvariantTransactionData; record: VariantTransactionData }> => {
const transaction = {
receivingChainTxManagerAddress: transactionManagerReceiverSide.address,
user: user.address,
router: router.address,
initiator: user.address,
sendingAssetId: AddressZero,
receivingAssetId: AddressZero,
sendingChainFallback: user.address,
callTo: AddressZero,
receivingAddress: receiver.address,
callDataHash: EmptyCallDataHash,
transactionId: hexlify(randomBytes(32)),
sendingChainId: (await transactionManager.getChainId()).toNumber(),
receivingChainId: (await transactionManagerReceiverSide.getChainId()).toNumber(),
...txOverrides,
};
const day = 24 * 60 * 60;
const block = await ethers.provider.getBlock("latest");
const record = {
amount: "10",
expiry: block.timestamp + day + 5_000,
preparedBlockNumber: 10,
...recordOverrides,
};
return { transaction, record };
};
const approveTokens = async (amount: BigNumberish, approver: Wallet, spender: string, token: ERC20 = tokenA) => {
const approveTx = await token.connect(approver).approve(spender, amount);
await approveTx.wait();
const allowance = await token.allowance(approver.address, spender);
expect(allowance).to.be.at.least(amount);
};
const addAndAssertLiquidity = async (
amount: BigNumberish,
assetId: string = AddressZero,
_router: Wallet = router,
instance: Contract = transactionManagerReceiverSide,
useMsgSender: boolean = false,
fee: BigNumberish = 0,
) => {
// Get starting + expected balance
const routerAddr = router.address;
const startingBalance = await getOnchainBalance(assetId, routerAddr, ethers.provider);
const expectedBalance = startingBalance.sub(amount);
const startingLiquidity = await instance.routerBalances(routerAddr, assetId);
const expectedLiquidity = startingLiquidity.add(amount).sub(fee);
const tx: providers.TransactionResponse = useMsgSender
? await instance
.connect(_router)
.addLiquidity(amount, assetId, assetId === AddressZero ? { value: BigNumber.from(amount) } : {})
: await instance
.connect(_router)
.addLiquidityFor(
amount,
assetId,
router.address,
assetId === AddressZero ? { value: BigNumber.from(amount) } : {},
);
const receipt = await tx.wait();
// const [receipt, payload] = await Promise.all([tx.wait(), event]);
// expect(payload).to.be.ok;
// Verify receipt + attached events
expect(receipt.status).to.be.eq(1);
await assertReceiptEvent(receipt, "LiquidityAdded", {
router: routerAddr,
assetId,
amount: BigNumber.from(amount).sub(fee),
caller: receipt.from,
});
// Check liquidity
const liquidity = await instance.routerBalances(routerAddr, assetId);
expect(liquidity).to.be.eq(expectedLiquidity);
// Check balances
const balance = await getOnchainBalance(assetId, routerAddr, ethers.provider);
expect(balance).to.be.eq(
expectedBalance.sub(assetId === AddressZero ? receipt.effectiveGasPrice.mul(receipt.gasUsed) : 0),
);
};
const removeAndAssertLiquidity = async (
amount: BigNumberish,
assetId: string = AddressZero,
_router?: Wallet,
instance: Contract = transactionManagerReceiverSide,
) => {
const router = _router ?? instance.signer;
const routerAddress = await router.getAddress();
// Get starting + expected balance
const startingBalance = await getOnchainBalance(assetId, routerAddress, ethers.provider);
const expectedBalance = startingBalance.add(amount);
const startingLiquidity = await instance.routerBalances(routerAddress, assetId);
const expectedLiquidity = startingLiquidity.sub(amount);
const tx: providers.TransactionResponse = await instance
.connect(router)
.removeLiquidity(amount, assetId, routerAddress);
const receipt = await tx.wait();
expect(receipt.status).to.be.eq(1);
// Verify receipt events
await assertReceiptEvent(receipt, "LiquidityRemoved", {
router: routerAddress,
assetId,
amount,
recipient: routerAddress,
});
// Check liquidity
const liquidity = await instance.routerBalances(await router.getAddress(), assetId);
expect(liquidity).to.be.eq(expectedLiquidity);
// Check balance
const finalBalance = await getOnchainBalance(assetId, await router.getAddress(), ethers.provider);
expect(finalBalance).to.be.eq(
assetId !== AddressZero
? expectedBalance
: expectedBalance.sub(receipt.cumulativeGasUsed.mul(receipt.effectiveGasPrice)),
);
};
const prepareAndAssert = async (
txOverrides: Partial<InvariantTransactionData>,
recordOverrides: Partial<VariantTransactionData> = {},
preparer: Wallet = user,
instance: TransactionManager = transactionManager,
encryptedCallData: string = EmptyBytes,
fee: BigNumberish = 0,
): Promise<ContractReceipt> => {
const { transaction, record } = await getTransactionData(txOverrides, recordOverrides);
// Check if its the user
const userSending = preparer.address !== transaction.router;
// Get initial balances
const initialContractAmount = await getOnchainBalance(
userSending ? transaction.sendingAssetId : transaction.receivingAssetId,
instance.address,
ethers.provider,
);
const initialPreparerAmount = userSending
? await getOnchainBalance(transaction.sendingAssetId, preparer.address, ethers.provider)
: await instance.routerBalances(transaction.router, transaction.receivingAssetId);
const invariantDigest = getInvariantTransactionDigest(transaction);
expect(await instance.variantTransactionData(invariantDigest)).to.be.eq(utils.formatBytes32String(""));
// Send tx
const args = {
invariantData: transaction,
amount: record.amount,
expiry: record.expiry,
encryptedCallData,
encodedBid: EmptyBytes,
bidSignature: EmptyBytes,
encodedMeta: EmptyBytes,
};
const prepareTx = await instance
.connect(preparer)
.prepare(
args,
transaction.sendingAssetId === AddressZero && preparer.address !== transaction.router
? { value: record.amount }
: {},
);
const receipt = await prepareTx.wait();
expect(receipt.status).to.be.eq(1);
const feeAdjustedAmount = userSending ? BigNumber.from(record.amount).sub(fee).toString() : record.amount;
const variantDigest = getVariantTransactionDigest({
amount: feeAdjustedAmount,
expiry: record.expiry,
preparedBlockNumber: receipt.blockNumber,
});
expect(await instance.variantTransactionData(invariantDigest)).to.be.eq(variantDigest);
// Verify receipt event
const txData = {
...transaction,
...record,
preparedBlockNumber: receipt.blockNumber,
amount: feeAdjustedAmount,
};
await assertReceiptEvent(receipt, "TransactionPrepared", {
user: transaction.user,
router: transaction.router,
transactionId: transaction.transactionId,
txData,
caller: preparer.address,
args: {
invariantData: transaction,
amount: record.amount,
expiry: record.expiry,
encryptedCallData: encryptedCallData,
bidSignature: EmptyBytes,
encodedBid: EmptyBytes,
encodedMeta: EmptyBytes,
},
});
// Verify amount has been deducted from preparer
const finalPreparerAmount = userSending
? await getOnchainBalance(transaction.sendingAssetId, preparer.address, ethers.provider)
: await instance.routerBalances(transaction.router, transaction.receivingAssetId);
const expected = initialPreparerAmount.sub(record.amount); // dont use fee adjusted because it is burned / came from router
expect(finalPreparerAmount).to.be.eq(
transaction.sendingAssetId === AddressZero && userSending
? expected.sub(receipt.effectiveGasPrice.mul(receipt.cumulativeGasUsed))
: expected,
);
// Verify amount has been added to contract
if (!userSending) {
// Router does not send funds
return receipt;
}
const finalContractAmount = await getOnchainBalance(transaction.sendingAssetId, instance.address, ethers.provider);
expect(finalContractAmount).to.be.eq(initialContractAmount.add(feeAdjustedAmount));
return receipt;
};
const fulfillAndAssert = async (
transaction: InvariantTransactionData,
record: VariantTransactionData,
relayerFee: string,
fulfillingForSender: boolean,
submitter: Wallet,
instance: TransactionManager,
callData: string = EmptyBytes,
) => {
// Get pre-fulfull balance. If fulfilling on sender side, router
// liquidity of sender asset will increase. If fulfilling on receiving
// side, user balance of receiving asset will increase + relayer paid
const initialIncrease = fulfillingForSender
? await getOnchainBalance(transaction.receivingAssetId, transaction.receivingAddress, ethers.provider)
: await instance.routerBalances(router.address, transaction.sendingAssetId);
const expectedIncrease = initialIncrease.add(record.amount).sub(fulfillingForSender ? relayerFee : 0);
// Check for relayer balances
const initialRelayer = await getOnchainBalance(transaction.receivingAssetId, submitter.address, ethers.provider);
// Check for values that remain flat
const initialFlat = fulfillingForSender
? await instance.routerBalances(router.address, transaction.receivingAssetId)
: await getOnchainBalance(transaction.sendingAssetId, user.address, ethers.provider);
// Generate signature from user
const signature = await signFulfillTransactionPayload(
transaction.transactionId,
relayerFee,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
const invariantDigest = getInvariantTransactionDigest(transaction);
const variantDigestBeforeFulfill = getVariantTransactionDigest({
amount: record.amount,
expiry: record.expiry,
preparedBlockNumber: record.preparedBlockNumber,
});
expect(await instance.variantTransactionData(invariantDigest)).to.be.eq(variantDigestBeforeFulfill);
// Send tx
const args = {
txData: {
...transaction,
...record,
},
relayerFee,
signature,
callData,
encodedMeta: EmptyBytes,
};
const tx = await instance.connect(submitter).fulfill(args);
const receipt = await tx.wait();
expect(receipt.status).to.be.eq(1);
const variantDigest = getVariantTransactionDigest({
amount: record.amount,
expiry: record.expiry,
preparedBlockNumber: 0,
});
expect(await instance.variantTransactionData(invariantDigest)).to.be.eq(variantDigest);
// Assert event
await assertReceiptEvent(receipt, "TransactionFulfilled", {
user: transaction.user,
router: transaction.router,
transactionId: transaction.transactionId,
args: {
txData: { ...transaction, ...record },
relayerFee,
signature,
callData,
encodedMeta: EmptyBytes,
},
caller: submitter.address,
});
// Verify final balances
const finalIncreased = fulfillingForSender
? await getOnchainBalance(transaction.receivingAssetId, transaction.receivingAddress, ethers.provider)
: await instance.routerBalances(router.address, transaction.sendingAssetId);
const finalFlat = fulfillingForSender
? await instance.routerBalances(router.address, transaction.receivingAssetId)
: await getOnchainBalance(transaction.sendingAssetId, user.address, ethers.provider);
// Assert relayer fee if needed
if (fulfillingForSender && submitter.address !== user.address) {
// Assert relayer got fees
const expectedRelayer = initialRelayer.add(relayerFee);
const finalRelayer = await getOnchainBalance(transaction.receivingAssetId, submitter.address, ethers.provider);
expect(finalRelayer).to.be.eq(
transaction.receivingAssetId === AddressZero
? expectedRelayer.sub(receipt.effectiveGasPrice.mul(receipt.gasUsed))
: expectedRelayer,
);
}
const gas = receipt.effectiveGasPrice.mul(receipt.gasUsed).toString();
if (callData == EmptyBytes) {
expect(finalIncreased).to.be.eq(
!fulfillingForSender ||
user.address !== submitter.address ||
transaction.receivingAssetId !== AddressZero ||
user.address !== transaction.receivingAddress
? expectedIncrease
: expectedIncrease.add(relayerFee).sub(gas),
);
}
expect(finalFlat).to.be.eq(initialFlat);
};
const cancelAndAssert = async (
transaction: InvariantTransactionData,
record: VariantTransactionData,
canceller: Wallet,
instance: Contract,
_signature?: string,
): Promise<void> => {
const sendingSideCancel = (await instance.getChainId()).toNumber() === transaction.sendingChainId;
const startingBalance = !sendingSideCancel
? await instance.routerBalances(transaction.router, transaction.receivingAssetId)
: await getOnchainBalance(transaction.sendingAssetId, transaction.user, ethers.provider);
const expectedBalance = startingBalance.add(record.amount);
const signature =
_signature ??
(await signCancelTransactionPayload(
transaction.transactionId,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
));
const args = {
txData: {
...transaction,
...record,
},
signature,
encodedMeta: EmptyBytes,
};
const tx = await instance.connect(canceller).cancel(args);
const receipt = await tx.wait();
await assertReceiptEvent(receipt, "TransactionCancelled", {
user: transaction.user,
router: transaction.router,
transactionId: transaction.transactionId,
args,
caller: canceller.address,
});
const balance = !sendingSideCancel
? await instance.routerBalances(transaction.router, transaction.receivingAssetId)
: await getOnchainBalance(transaction.sendingAssetId, transaction.user, ethers.provider);
expect(balance).to.be.eq(expectedBalance);
};
describe("constructor", async () => {
it("should deploy", async () => {
expect(transactionManager.address).to.be.a("string");
});
it("should set chainId", async () => {
expect(await transactionManager.getChainId()).to.eq(1337);
});
it("should set interpreter", async () => {
const addr = await transactionManager.interpreter();
expect(utils.isAddress(addr)).to.be.true;
});
it("should set renounced", async () => {
expect(await transactionManager.renounced()).to.be.false;
});
});
describe("getChainId / getStoredChainId", async () => {
let storedChainTm: TransactionManager;
let defaultChainTm: TransactionManager;
const chainOverride = 25;
beforeEach(async () => {
storedChainTm = await deployContract<TransactionManager>("TransactionManager", chainOverride);
defaultChainTm = await deployContract<TransactionManager>("TransactionManager", constants.Zero);
});
it("should work when there is a provided override", async () => {
expect(await storedChainTm.getChainId()).to.be.eq(chainOverride);
expect(await storedChainTm.getStoredChainId()).to.be.eq(chainOverride);
});
it("should work when there is no provided override", async () => {
const { chainId } = await ethers.provider.getNetwork();
expect(await defaultChainTm.getStoredChainId()).to.be.eq(constants.AddressZero);
expect(await defaultChainTm.getChainId()).to.be.eq(chainId);
});
});
describe("addRouter", () => {
it("should fail if not called by owner", async () => {
const toAdd = Wallet.createRandom().address;
await expect(transactionManager.connect(other).addRouter(toAdd)).to.be.revertedWith("#OO:029");
});
it("should fail if it is adding address0", async () => {
const toAdd = constants.AddressZero;
await expect(transactionManager.addRouter(toAdd, { maxFeePerGas: MAX_FEE_PER_GAS })).to.be.revertedWith(
"#AR:001",
);
});
it("should fail if its already added", async () => {
await expect(transactionManager.addRouter(router.address, { maxFeePerGas: MAX_FEE_PER_GAS })).to.be.revertedWith(
"#AR:032",
);
});
it("should work", async () => {
const toAdd = Wallet.createRandom().address;
const tx = await transactionManager.addRouter(toAdd, { maxFeePerGas: MAX_FEE_PER_GAS });
const receipt = await tx.wait();
await assertReceiptEvent(receipt, "RouterAdded", { caller: receipt.from, addedRouter: toAdd });
expect(await transactionManager.approvedRouters(toAdd)).to.be.true;
});
});
describe("removeRouter", () => {
it("should fail if not called by owner", async () => {
const toAdd = Wallet.createRandom().address;
await expect(transactionManager.connect(other).removeRouter(toAdd)).to.be.revertedWith("#OO:029");
});
it("should fail if it is adding address0", async () => {
const toAdd = constants.AddressZero;
await expect(transactionManager.removeRouter(toAdd, { maxFeePerGas: MAX_FEE_PER_GAS })).to.be.revertedWith(
"#RR:001",
);
});
it("should fail if its already removed", async () => {
const tx = await transactionManager.removeRouter(router.address, { maxFeePerGas: MAX_FEE_PER_GAS });
await tx.wait();
await expect(
transactionManager.removeRouter(router.address, { maxFeePerGas: MAX_FEE_PER_GAS }),
).to.be.revertedWith("#RR:033");
});
it("should work", async () => {
const tx = await transactionManager.removeRouter(router.address, { maxFeePerGas: MAX_FEE_PER_GAS });
const receipt = await tx.wait();
await assertReceiptEvent(receipt, "RouterRemoved", { caller: receipt.from, removedRouter: router.address });
expect(await transactionManager.approvedRouters(router.address)).to.be.false;
});
});
describe("addAssetId", () => {
it("should fail if not called by owner", async () => {
await expect(transactionManager.connect(other).addAssetId(Wallet.createRandom().address)).to.be.revertedWith(
"#OO:029",
);
});
it("should fail if its already added", async () => {
await expect(transactionManager.addAssetId(AddressZero, { maxFeePerGas: MAX_FEE_PER_GAS })).to.be.revertedWith(
"#AA:032",
);
});
it("should work", async () => {
const assetId = Wallet.createRandom().address;
const tx = await transactionManager.addAssetId(assetId, { maxFeePerGas: MAX_FEE_PER_GAS });
const receipt = await tx.wait();
await assertReceiptEvent(receipt, "AssetAdded", { caller: receipt.from, addedAssetId: assetId });
expect(await transactionManager.approvedAssets(assetId)).to.be.true;
});
});
describe("removeAssetId", () => {
it("should fail if not called by owner", async () => {
await expect(transactionManager.connect(other).removeAssetId(Wallet.createRandom().address)).to.be.revertedWith(
"#OO:029",
);
});
it("should fail if its already removed", async () => {
const assetId = Wallet.createRandom().address;
await expect(transactionManager.removeAssetId(assetId, { maxFeePerGas: MAX_FEE_PER_GAS })).to.be.revertedWith(
"#RA:033",
);
});
it("should work", async () => {
const assetId = AddressZero;
const tx = await transactionManager.removeAssetId(assetId, { maxFeePerGas: MAX_FEE_PER_GAS });
const receipt = await tx.wait();
await assertReceiptEvent(receipt, "AssetRemoved", { caller: receipt.from, removedAssetId: assetId });
expect(await transactionManager.approvedAssets(assetId)).to.be.false;
});
});
describe("addLiquidity / addLiquidityFor", () => {
// TODO: #135
// - reentrant cases
it("should revert if router address is empty", async () => {
const amount = "1";
const assetId = AddressZero;
await expect(transactionManager.connect(router).addLiquidityFor(amount, assetId, AddressZero)).to.be.revertedWith(
getContractError("addLiquidity: ROUTER_EMPTY"),
);
expect(await transactionManager.routerBalances(router.address, assetId)).to.eq(BigNumber.from(0));
});
it("should fail if amount is 0", async () => {
const amount = "0";
const assetId = AddressZero;
await expect(
transactionManager.connect(router).addLiquidityFor(amount, assetId, router.address),
).to.be.revertedWith(getContractError("addLiquidity: AMOUNT_IS_ZERO"));
});
it("should fail if it is an unapproved router && ownership isnt renounced", async () => {
const amount = "10";
const assetId = AddressZero;
// Remove router
const remove = await transactionManager.removeRouter(router.address, { maxFeePerGas: MAX_FEE_PER_GAS });
await remove.wait();
expect(await transactionManager.approvedRouters(router.address)).to.be.false;
await expect(
transactionManager.addLiquidityFor(amount, assetId, router.address, { maxFeePerGas: MAX_FEE_PER_GAS }),
).to.be.revertedWith(getContractError("addLiquidity: BAD_ROUTER"));
});
it("should fail if its an unapproved asset && ownership isnt renounced", async () => {
const amount = "10";
const assetId = AddressZero;
// Remove asset
const remove = await transactionManager.removeAssetId(assetId, { maxFeePerGas: MAX_FEE_PER_GAS });
await remove.wait();
expect(await transactionManager.approvedAssets(assetId)).to.be.false;
await expect(
transactionManager.connect(router).addLiquidityFor(amount, assetId, router.address),
).to.be.revertedWith(getContractError("addLiquidity: BAD_ASSET"));
});
it("should fail if if msg.value == 0 for native asset", async () => {
const amount = "1";
const assetId = AddressZero;
await expect(
transactionManager.connect(router).addLiquidityFor(amount, assetId, router.address),
).to.be.revertedWith(getContractError("transferAssetToContract: VALUE_MISMATCH"));
expect(await transactionManager.routerBalances(router.address, assetId)).to.eq(BigNumber.from(0));
});
it("should fail if msg.value != amount for native asset", async () => {
const amount = "1";
const falseValue = "2";
const assetId = AddressZero;
await expect(
transactionManager.connect(router).addLiquidityFor(amount, assetId, router.address, { value: falseValue }),
).to.be.revertedWith(getContractError("transferAssetToContract: VALUE_MISMATCH"));
expect(await transactionManager.routerBalances(router.address, assetId)).to.eq(BigNumber.from(0));
});
it("should fail if msg.value != 0 for ERC20 token", async () => {
// addLiquidity: ETH_WITH_ERC_TRANSFER;
const amount = "1";
const assetId = tokenA.address;
await expect(
transactionManager.connect(router).addLiquidityFor(amount, assetId, router.address, { value: amount }),
).to.be.revertedWith(getContractError("transferAssetToContract: ETH_WITH_ERC_TRANSFER"));
expect(await transactionManager.routerBalances(router.address, assetId)).to.eq(BigNumber.from(0));
});
it("should fail if transferFromERC20 fails", async () => {
const amount = "1";
const assetId = tokenA.address;
await expect(
transactionManager.connect(router).addLiquidityFor(amount, assetId, router.address),
).to.be.revertedWith("ERC20: transfer amount exceeds allowance");
expect(await transactionManager.routerBalances(router.address, assetId)).to.eq(BigNumber.from(0));
});
it("should work if it is renounced && using an unapproved router", async () => {
const amount = "1";
const assetId = AddressZero;
// Remove asset
const remove = await transactionManager.removeRouter(router.address, { maxFeePerGas: MAX_FEE_PER_GAS });
await remove.wait();
expect(await transactionManager.approvedRouters(router.address)).to.be.false;
// Renounce ownership
await transferOwnership();
await addAndAssertLiquidity(amount, assetId, router);
});
it("should work if it is renounced && using an unapproved assetId", async () => {
const amount = "1";
const assetId = AddressZero;
// Remove asset
const remove = await transactionManager.connect(wallet).removeAssetId(assetId);
await remove.wait();
expect(await transactionManager.approvedAssets(assetId)).to.be.false;
// Renounce ownership
await transferOwnership();
await addAndAssertLiquidity(amount, assetId);
});
it("should work for an approved router in approved native asset", async () => {
const amount = "1";
const assetId = AddressZero;
await addAndAssertLiquidity(amount, assetId);
});
it("should work for an approved router in approved erc20", async () => {
const amount = "1";
const assetId = tokenA.address;
await approveTokens(amount, router, transactionManagerReceiverSide.address, tokenA);
await addAndAssertLiquidity(amount, assetId);
});
it("addLiqudity should add funds for msg.sender", async () => {
const amount = "1";
const assetId = tokenA.address;
await approveTokens(amount, router, transactionManagerReceiverSide.address, tokenA);
await addAndAssertLiquidity(amount, assetId, router, transactionManagerReceiverSide, true);
});
it("should work for fee on transfer tokens", async () => {
const amount = "10";
const assetId = feeToken.address;
await approveTokens(amount, router, transactionManagerReceiverSide.address, feeToken);
await addAndAssertLiquidity(amount, assetId, router, transactionManagerReceiverSide, true, await feeToken.fee());
});
});
describe("removeLiquidity", () => {
// TODO: #135
// - reentrant cases
// - rebasing/inflationary/deflationary cases
it("should revert if param recipient address is empty", async () => {
const amount = "1";
const assetId = AddressZero;
await expect(transactionManager.connect(router).removeLiquidity(amount, assetId, AddressZero)).to.be.revertedWith(
getContractError("removeLiquidity: RECIPIENT_EMPTY"),
);
});
it("should revert if amount is 0", async () => {
const amount = "0";
const assetId = AddressZero;
await addAndAssertLiquidity("10", assetId);
await expect(
transactionManager.connect(router).removeLiquidity(amount, assetId, router.address),
).to.be.revertedWith(getContractError("removeLiquidity: AMOUNT_IS_ZERO"));
});
it("should revert if router balance is lower than amount", async () => {
const amount = "1";
const assetId = AddressZero;
await expect(
transactionManager.connect(router).removeLiquidity(amount, assetId, router.address),
).to.be.revertedWith(getContractError("removeLiquidity: INSUFFICIENT_FUNDS"));
});
it("happy case: removeLiquidity native token", async () => {
const amount = "1";
const assetId = AddressZero;
await addAndAssertLiquidity(amount, assetId);
await removeAndAssertLiquidity(amount, assetId, router);
});
it("happy case: removeLiquidity ERC20", async () => {
const amount = "1";
const assetId = tokenA.address;
await approveTokens(amount, router, transactionManagerReceiverSide.address);
await addAndAssertLiquidity(amount, assetId);
await removeAndAssertLiquidity(amount, assetId, router);
});
});
describe("prepare", () => {
// TODO: #135
// - reentrant cases
// - rebasing test cases
it("should revert if invariantData.user is AddressZero", async () => {
const { transaction, record } = await getTransactionData({ user: AddressZero });
await expect(
transactionManager.connect(user).prepare(convertToPrepareArgs(transaction, record), {
value: record.amount,
}),
).to.be.revertedWith(getContractError("prepare: USER_EMPTY"));
});
it("should revert if invariantData.router is AddressZero", async () => {
const { transaction, record } = await getTransactionData({ router: AddressZero });
await expect(
transactionManager.connect(user).prepare(convertToPrepareArgs(transaction, record), {
value: record.amount,
}),
).to.be.revertedWith(getContractError("prepare: ROUTER_EMPTY"));
});
it("should fail if it hasnt been renounced && using an unapproved router", async () => {
const { transaction, record } = await getTransactionData({ router: Wallet.createRandom().address });
await expect(
transactionManager.connect(user).prepare(convertToPrepareArgs(transaction, record), {
value: record.amount,
}),
).to.be.revertedWith(getContractError("prepare: BAD_ROUTER"));
});
it("should revert if invariantData.sendingChainFallback is AddressZero", async () => {
const { transaction, record } = await getTransactionData({ sendingChainFallback: AddressZero });
await expect(
transactionManager.connect(user).prepare(convertToPrepareArgs(transaction, record), {
value: record.amount,
}),
).to.be.revertedWith(getContractError("prepare: SENDING_CHAIN_FALLBACK_EMPTY"));
});
it("should revert if invariantData.receivingAddress is AddressZero", async () => {
const { transaction, record } = await getTransactionData({ receivingAddress: AddressZero });
await expect(
transactionManager.connect(user).prepare(convertToPrepareArgs(transaction, record), {
value: record.amount,
}),
).to.be.revertedWith(getContractError("prepare: RECEIVING_ADDRESS_EMPTY"));
});
it("should revert if invariantData.sendingChainId == invariantData.receivingChainId", async () => {
const { transaction, record } = await getTransactionData({ sendingChainId: 1337, receivingChainId: 1337 });
await expect(
transactionManager.connect(user).prepare(convertToPrepareArgs(transaction, record), {
value: record.amount,
}),
).to.be.revertedWith(getContractError("prepare: SAME_CHAINIDS"));
});
it("should revert if invariantData.sendingChainId != transactionManager.chainId && invariantData.receivingChainId != transactionManager.chainId", async () => {
const { transaction, record } = await getTransactionData({ sendingChainId: 1340, receivingChainId: 1341 });
await expect(
transactionManager.connect(user).prepare(convertToPrepareArgs(transaction, record), {
value: record.amount,
}),
).to.be.revertedWith(getContractError("prepare: INVALID_CHAINIDS"));
});
it("should revert if invariantData.expiry - block.timestamp < MIN_TIMEOUT", async () => {
const { transaction, record } = await getTransactionData();
const hours12 = 12 * 60 * 60;
const { timestamp } = await ethers.provider.getBlock("latest");
const expiry = timestamp + hours12 + 5_000;
await expect(
transactionManager.connect(user).prepare(convertToPrepareArgs(transaction, { ...record, expiry }), {
value: record.amount,
}),
).to.be.revertedWith(getContractError("prepare: TIMEOUT_TOO_LOW"));
});
it("should revert if invariantData.expiry - block.timestamp == MIN_TIMEOUT", async () => {
const { transaction, record } = await getTransactionData();
const { timestamp } = await ethers.provider.getBlock("latest");
const expiry = (await transactionManager.MIN_TIMEOUT()).add(timestamp.toString());
await expect(
transactionManager
.connect(user)
.prepare(convertToPrepareArgs(transaction, { ...record, expiry: expiry.toNumber() }), {
value: record.amount,
}),
).to.be.revertedWith(getContractError("prepare: TIMEOUT_TOO_LOW"));
});
it("should revert if invariantData.expiry - block.timestamp > MAX_TIMEOUT", async () => {
const { transaction, record } = await getTransactionData();
const days31 = 31 * 24 * 60 * 60;
const { timestamp } = await ethers.provider.getBlock("latest");
const expiry = timestamp + days31 + 5_000;
await expect(
transactionManager.connect(user).prepare(convertToPrepareArgs(transaction, { ...record, expiry }), {
value: record.amount,
}),
).to.be.revertedWith(getContractError("prepare: TIMEOUT_TOO_HIGH"));
});
it("should revert if digest already exist", async () => {
const { transaction, record } = await getTransactionData();
await prepareAndAssert(transaction, record, user, transactionManager);
await expect(
transactionManager.connect(user).prepare(convertToPrepareArgs(transaction, record), {
value: record.amount,
}),
).to.be.revertedWith(getContractError("prepare: DIGEST_EXISTS"));
});
describe("failures when preparing on the sender chain", () => {
it("should revert if msg.sender is not invariantData.initiator", async () => {
const { transaction, record } = await getTransactionData({ initiator: AddressZero });
await expect(
transactionManager.connect(user).prepare(convertToPrepareArgs(transaction, record), {
value: record.amount,
}),
).to.be.revertedWith(getContractError("prepare: INITIATOR_MISMATCH"));
});
it("should fail if amount is 0", async () => {
const { transaction, record } = await getTransactionData({}, { amount: "0" });
await expect(
transactionManager.connect(user).prepare(convertToPrepareArgs(transaction, record), {
value: record.amount,
}),
).to.be.revertedWith(getContractError("prepare: AMOUNT_IS_ZERO"));
});
it("should fail if its not renounced && invariantData.sendingAssetId != an approved asset", async () => {
const { transaction, record } = await getTransactionData({ sendingAssetId: Wallet.createRandom().address });
await expect(
transactionManager.connect(user).prepare(convertToPrepareArgs(transaction, record), {
value: record.amount,
}),
).to.be.revertedWith(getContractError("prepare: BAD_ASSET"));
});
it("should revert if msg.value == 0 && invariantData.sendingAssetId == native token", async () => {
const { transaction, record } = await getTransactionData();
await expect(
transactionManager.connect(user).prepare(convertToPrepareArgs(transaction, record)),
).to.be.revertedWith(getContractError("transferAssetToContract: VALUE_MISMATCH"));
});
it("should revert if msg.value != amount && invariantData.sendingAssetId == native token", async () => {
const { transaction, record } = await getTransactionData();
const falseAmount = "20";
await expect(
transactionManager.connect(user).prepare(convertToPrepareArgs(transaction, record), {
value: falseAmount,
}),
).to.be.revertedWith(getContractError("transferAssetToContract: VALUE_MISMATCH"));
});
it("should revert if msg.value != 0 && invariantData.sendingAssetId != native token", async () => {
const { transaction, record } = await getTransactionData({ sendingAssetId: tokenA.address });
await expect(
transactionManager.connect(user).prepare(convertToPrepareArgs(transaction, record), {
value: record.amount,
}),
).to.be.revertedWith(getContractError("transferAssetToContract: ETH_WITH_ERC_TRANSFER"));
});
it("should revert if ERC20.transferFrom fails", async () => {
const { transaction, record } = await getTransactionData({ sendingAssetId: tokenA.address });
await expect(
transactionManager.connect(user).prepare(convertToPrepareArgs(transaction, record)),
).to.be.revertedWith("ERC20: transfer amount exceeds allowance");
});
});
describe("failures when preparing on the router chain", () => {
it("should fail if the callTo is not empty and not a contract", async () => {
const { transaction, record } = await getTransactionData({
callTo: Wallet.createRandom().address,
});
await expect(
transactionManagerReceiverSide.connect(router).prepare(convertToPrepareArgs(transaction, record)),
).to.be.revertedWith("#P:031");
});
it("should fail if its not renounced && invariantData.receivingAssetId != an approved asset", async () => {
const { transaction, record } = await getTransactionData({ receivingAssetId: Wallet.createRandom().address });
await expect(
transactionManagerReceiverSide.connect(router).prepare(convertToPrepareArgs(transaction, record), {
value: record.amount,
}),
).to.be.revertedWith(getContractError("prepare: BAD_ASSET"));
});
it("should fail if msg.sender != invariantData.router", async () => {
const { transaction, record } = await getTransactionData();
await expect(
transactionManagerReceiverSide.connect(user).prepare(convertToPrepareArgs(transaction, record)),
).to.be.revertedWith(getContractError("prepare: ROUTER_MISMATCH"));
});
it("should fail if msg.value != 0", async () => {
const { transaction, record } = await getTransactionData();
await expect(
transactionManagerReceiverSide.connect(router).prepare(convertToPrepareArgs(transaction, record), {
value: record.amount,
}),
).to.be.revertedWith(getContractError("prepare: ETH_WITH_ROUTER_PREPARE"));
});
it("should fail if router liquidity is lower than amount", async () => {
const { transaction, record } = await getTransactionData({}, { amount: "1000000" });
await expect(
transactionManagerReceiverSide.connect(router).prepare(convertToPrepareArgs(transaction, record)),
).to.be.revertedWith(getContractError("prepare: INSUFFICIENT_LIQUIDITY"));
});
it("should work for 0-valued transactions on receiving chain", async () => {
const prepareAmount = "0";
const assetId = AddressZero;
await addAndAssertLiquidity("100", assetId, router, transactionManagerReceiverSide);
await prepareAndAssert(
{
sendingAssetId: assetId,
receivingAssetId: assetId,
sendingChainId: 1337,
receivingChainId: 1338,
},
{ amount: prepareAmount },
router,
transactionManagerReceiverSide,
);
});
});
it("should work if the contract has been renounced and using unapproved router", async () => {
const prepareAmount = "10";
// Remove router
const remove = await transactionManager.connect(wallet).removeRouter(router.address);
await remove.wait();
expect(await transactionManager.approvedRouters(router.address)).to.be.false;
// Renounce ownership
await transferOwnership();
// Prepare
const tenDays = 10 * 24 * 60 * 60;
const { timestamp } = await ethers.provider.getBlock("latest");
await prepareAndAssert(
{
sendingAssetId: AddressZero,
receivingAssetId: tokenB.address,
},
{
amount: prepareAmount,
expiry: timestamp + tenDays, // increase expiry to 10 days in future because fast-forwarded
},
);
});
it("should work if the contract has been renounced and using unapproved asset", async () => {
const prepareAmount = "10";
const assetId = AddressZero;
// Remove asset
const remove = await transactionManager.connect(wallet).removeAssetId(assetId);
await remove.wait();
expect(await transactionManager.approvedAssets(assetId)).to.be.false;
// Renounce ownership
await transferOwnership();
// Prepare
const tenDays = 10 * 24 * 60 * 60;
const { timestamp } = await ethers.provider.getBlock("latest");
await prepareAndAssert(
{
sendingAssetId: assetId,
receivingAssetId: tokenB.address,
},
{
amount: prepareAmount,
expiry: timestamp + tenDays, // increase expiry to 10 days in future because fast-forwarded
},
);
});
it("happy case: prepare by Bob for ERC20 with CallData", async () => {
const prepareAmount = "10";
const assetId = tokenA.address;
// Get calldata
const callData = counter.interface.encodeFunctionData("incrementAndSend", [
assetId,
other.address,
prepareAmount,
]);
const callDataHash = utils.keccak256(callData);
const { transaction } = await getTransactionData({
sendingAssetId: assetId,
receivingAssetId: tokenB.address,
callTo: counter.address,
callDataHash: callDataHash,
});
await approveTokens(prepareAmount, user, transactionManager.address);
await prepareAndAssert(
transaction,
{
amount: prepareAmount,
},
user,
transactionManager,
callData,
);
});
it("happy case: prepare by Bob for ERC20", async () => {
const prepareAmount = "10";
const assetId = tokenA.address;
await approveTokens(prepareAmount, user, transactionManager.address);
await prepareAndAssert(
{
sendingAssetId: assetId,
receivingAssetId: tokenB.address,
},
{
amount: prepareAmount,
},
user,
transactionManager,
);
});
it("happy case: prepare by Bob for Ether/Native token", async () => {
const prepareAmount = "10";
await prepareAndAssert(
{
sendingAssetId: AddressZero,
receivingAssetId: tokenB.address,
},
{
amount: prepareAmount,
},
);
});
it("happy case: prepare by Router for ERC20", async () => {
const prepareAmount = "100";
const assetId = tokenA.address;
await approveTokens(prepareAmount, router, transactionManager.address, tokenA);
await addAndAssertLiquidity(prepareAmount, assetId, router, transactionManager);
await prepareAndAssert(
{
sendingAssetId: tokenB.address,
receivingAssetId: assetId,
sendingChainId: 1338,
receivingChainId: 1337,
},
{ amount: prepareAmount },
router,
);
});
it("happy case: prepare by Router for Ether/Native token", async () => {
const prepareAmount = "100";
const assetId = AddressZero;
await addAndAssertLiquidity(prepareAmount, assetId, router, transactionManagerReceiverSide);
await prepareAndAssert(
{
sendingAssetId: assetId,
receivingAssetId: assetId,
sendingChainId: 1337,
receivingChainId: 1338,
},
{ amount: prepareAmount },
router,
transactionManagerReceiverSide,
);
});
it("happy case: prepare by Bob, sent by relayer", async () => {
const prepareAmount = "10";
const assetId = AddressZero;
const { transaction, record } = await getTransactionData(
{ sendingAssetId: assetId, receivingAssetId: tokenB.address, initiator: other.address },
{ amount: prepareAmount },
);
await prepareAndAssert(transaction, record, other, transactionManager);
});
it("should work for user preparing with fee on transfer token", async () => {
const prepareAmount = "10";
const assetId = feeToken.address;
const { transaction, record } = await getTransactionData(
{ sendingAssetId: assetId, receivingAssetId: tokenB.address },
{ amount: prepareAmount },
);
await prepareAndAssert(transaction, record, user, transactionManager, undefined, await feeToken.fee());
});
});
describe("fulfill", () => {
// TODO: #135
// - reentrant cases
// - rebasing/inflationary/deflationary cases
it("should revert if the variant data is not stored (has not been prepared)", async () => {
const { transaction, record } = await getTransactionData();
const relayerFee = "10";
const invariantDigest = getInvariantTransactionDigest(transaction);
expect(await transactionManager.variantTransactionData(invariantDigest)).to.be.eq(utils.formatBytes32String(""));
const signature = await signFulfillTransactionPayload(
transaction.transactionId,
relayerFee,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
await expect(
transactionManager.connect(router).fulfill(convertToFulfillArgs(transaction, record, relayerFee, signature)),
).to.be.revertedWith(getContractError("fulfill: INVALID_VARIANT_DATA"));
});
it("should revert if transaction has expired", async () => {
const { transaction, record } = await getTransactionData();
const relayerFee = "10";
const { blockNumber } = await prepareAndAssert(transaction, record, user, transactionManager);
const invariantDigest = getInvariantTransactionDigest(transaction);
const variant = {
amount: record.amount,
expiry: record.expiry,
preparedBlockNumber: blockNumber,
};
const variantDigestBeforeFulfill = getVariantTransactionDigest(variant);
expect(await transactionManager.variantTransactionData(invariantDigest)).to.be.eq(variantDigestBeforeFulfill);
await setBlockTime(+record.expiry + 1_000);
const signature = await signFulfillTransactionPayload(
transaction.transactionId,
relayerFee,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
await expect(
transactionManager.connect(router).fulfill(convertToFulfillArgs(transaction, variant, relayerFee, signature)),
).to.be.revertedWith(getContractError("fulfill: EXPIRED"));
});
it("should revert if transaction is already fulfilled (txData.preparedBlockNumber == 0)", async () => {
const { transaction, record } = await getTransactionData();
const relayerFee = "1";
const { blockNumber } = await prepareAndAssert(transaction, record, user, transactionManager);
const signature = await signFulfillTransactionPayload(
transaction.transactionId,
relayerFee,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
// User fulfills
await fulfillAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
relayerFee,
false,
router,
transactionManager,
);
await expect(
transactionManager.connect(router).fulfill(
convertToFulfillArgs(
transaction,
{
...record,
preparedBlockNumber: 0,
},
relayerFee,
signature,
),
),
).to.be.revertedWith(getContractError("fulfill: ALREADY_COMPLETED"));
});
it("should revert if the hash of callData != txData.callDataHash", async () => {
const prepareAmount = "10";
const assetId = tokenA.address;
const relayerFee = "2";
// Get calldata
const callData = counter.interface.encodeFunctionData("incrementAndSend", [
assetId,
other.address,
prepareAmount,
]);
const callDataHash = utils.keccak256(callData);
const { transaction, record } = await getTransactionData(
{
sendingAssetId: assetId,
receivingAssetId: tokenB.address,
callTo: counter.address,
callDataHash: callDataHash,
},
{ amount: prepareAmount },
);
await approveTokens(prepareAmount, user, transactionManager.address);
const { blockNumber } = await prepareAndAssert(transaction, record, user, transactionManager, callData);
const signature = await signFulfillTransactionPayload(
transaction.transactionId,
relayerFee,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
await expect(
transactionManager
.connect(router)
.fulfill(
convertToFulfillArgs(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
relayerFee,
signature,
keccak256(EmptyBytes),
),
),
).to.be.revertedWith(getContractError("fulfill: INVALID_CALL_DATA"));
});
describe("sender chain (router) fulfill", () => {
it("should revert if msg.sender != txData.router", async () => {
const { transaction, record } = await getTransactionData();
const relayerFee = "1";
const { blockNumber } = await prepareAndAssert(transaction, record, user, transactionManager);
const variant = {
amount: record.amount,
expiry: record.expiry,
preparedBlockNumber: blockNumber,
};
const signature = await signFulfillTransactionPayload(
transaction.transactionId,
relayerFee,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
await expect(
transactionManager.connect(user).fulfill(convertToFulfillArgs(transaction, variant, relayerFee, signature)),
).to.be.revertedWith(getContractError("fulfill: ROUTER_MISMATCH"));
});
it("should revert if param user didn't sign the signature", async () => {
const { transaction, record } = await getTransactionData();
const relayerFee = "10";
const { blockNumber } = await prepareAndAssert(transaction, record, user, transactionManager);
const variant = {
amount: record.amount,
expiry: record.expiry,
preparedBlockNumber: blockNumber,
};
const signature = await signFulfillTransactionPayload(
transaction.transactionId,
relayerFee,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
Wallet.createRandom(),
);
await expect(
transactionManager.connect(router).fulfill(convertToFulfillArgs(transaction, variant, relayerFee, signature)),
).to.be.revertedWith(getContractError("fulfill: INVALID_SIGNATURE"));
});
});
describe("receiver chain (user) fulfill", () => {
it("should revert if the relayerFee > txData.amount on receiving chain", async () => {
const prepareAmount = "10";
const assetId = AddressZero;
const relayerFee = "1000";
// Add receiving liquidity
await addAndAssertLiquidity(prepareAmount, assetId, router, transactionManagerReceiverSide);
const { transaction, record } = await getTransactionData(
{
sendingChainId: (await transactionManager.getChainId()).toNumber(),
receivingChainId: (await transactionManagerReceiverSide.getChainId()).toNumber(),
sendingAssetId: assetId,
receivingAssetId: assetId,
},
{ amount: prepareAmount },
);
// Router prepares
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
const signature = await signFulfillTransactionPayload(
transaction.transactionId,
relayerFee,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
await expect(
transactionManagerReceiverSide.connect(router).fulfill(
convertToFulfillArgs(
transaction,
{
...record,
preparedBlockNumber: blockNumber,
},
relayerFee,
signature,
),
),
).to.be.revertedWith(getContractError("fulfill: INVALID_RELAYER_FEE"));
});
it("should revert if the relayerFee > 0 and transferAsset fails", async () => {
const prepareAmount = "100";
const assetId = tokenA.address;
const relayerFee = "10";
// Add receiving liquidity
await approveTokens(prepareAmount, router, transactionManagerReceiverSide.address, tokenA);
await addAndAssertLiquidity(prepareAmount, assetId, router, transactionManagerReceiverSide);
const { transaction, record } = await getTransactionData(
{
sendingAssetId: AddressZero,
receivingAssetId: assetId,
sendingChainId: (await transactionManager.getChainId()).toNumber(),
receivingChainId: (await transactionManagerReceiverSide.getChainId()).toNumber(),
},
{ amount: prepareAmount },
);
// User prepares
await approveTokens(prepareAmount, user, transactionManagerReceiverSide.address, tokenA);
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
const signature = await signFulfillTransactionPayload(
transaction.transactionId,
relayerFee,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
// Set token to revert
(await tokenA.connect(wallet).setShouldRevert(true)).wait();
expect(await tokenA.shouldRevert()).to.be.true;
await expect(
transactionManagerReceiverSide.connect(router).fulfill(
convertToFulfillArgs(
transaction,
{
...record,
preparedBlockNumber: blockNumber,
},
relayerFee,
signature,
),
),
).revertedWith("transfer: SHOULD_REVERT");
});
it("should revert if txData.callTo == address(0) && transferAsset fails", async () => {
const prepareAmount = "100";
const assetId = tokenA.address;
const relayerFee = "0";
// Add receiving liquidity
await approveTokens(prepareAmount, router, transactionManagerReceiverSide.address, tokenA);
await addAndAssertLiquidity(prepareAmount, assetId, router, transactionManagerReceiverSide);
const { transaction, record } = await getTransactionData(
{
sendingAssetId: AddressZero,
receivingAssetId: assetId,
sendingChainId: (await transactionManager.getChainId()).toNumber(),
receivingChainId: (await transactionManagerReceiverSide.getChainId()).toNumber(),
callTo: AddressZero,
},
{ amount: prepareAmount },
);
// User prepares
await approveTokens(prepareAmount, user, transactionManagerReceiverSide.address, tokenA);
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
const signature = await signFulfillTransactionPayload(
transaction.transactionId,
relayerFee,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
// Set token to revert
(await tokenA.connect(wallet).setShouldRevert(true)).wait();
expect(await tokenA.shouldRevert()).to.be.true;
await expect(
transactionManagerReceiverSide.connect(router).fulfill(
convertToFulfillArgs(
transaction,
{
...record,
preparedBlockNumber: blockNumber,
},
relayerFee,
signature,
),
),
).revertedWith("transfer: SHOULD_REVERT");
});
it("should revert if txData.callTo != address(0) && txData.receivingAssetId is not the native asset && transferAsset (to interpreter) fails", async () => {
const prepareAmount = "100";
const assetId = tokenA.address;
const relayerFee = "0";
// Add receiving liquidity
await approveTokens(prepareAmount, router, transactionManagerReceiverSide.address, tokenA);
await addAndAssertLiquidity(prepareAmount, assetId, router, transactionManagerReceiverSide);
const { transaction, record } = await getTransactionData(
{
sendingAssetId: AddressZero,
receivingAssetId: assetId,
sendingChainId: (await transactionManager.getChainId()).toNumber(),
receivingChainId: (await transactionManagerReceiverSide.getChainId()).toNumber(),
callTo: counter.address,
},
{ amount: prepareAmount },
);
// User prepares
await approveTokens(prepareAmount, user, transactionManagerReceiverSide.address, tokenA);
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
const signature = await signFulfillTransactionPayload(
transaction.transactionId,
relayerFee,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
// Set token to revert
(await tokenA.connect(wallet).setShouldRevert(true)).wait();
expect(await tokenA.shouldRevert()).to.be.true;
await expect(
transactionManagerReceiverSide.connect(router).fulfill(
convertToFulfillArgs(
transaction,
{
...record,
preparedBlockNumber: blockNumber,
},
relayerFee,
signature,
),
),
).revertedWith("transfer: SHOULD_REVERT");
});
it("should revert if user didn't sign the right chain id", async () => {
const { transaction, record } = await getTransactionData();
const relayerFee = "10";
const { blockNumber } = await prepareAndAssert(transaction, record, user, transactionManager);
const variant = {
amount: record.amount,
expiry: record.expiry,
preparedBlockNumber: blockNumber,
};
const signature = await signFulfillTransactionPayload(
transaction.transactionId,
relayerFee,
transaction.receivingChainId + 1,
transaction.receivingChainTxManagerAddress,
user,
);
await expect(
transactionManager.connect(router).fulfill(convertToFulfillArgs(transaction, variant, relayerFee, signature)),
).to.be.revertedWith(getContractError("fulfill: INVALID_SIGNATURE"));
});
it("should revert if user didn't sign the right transaction address", async () => {
const { transaction, record } = await getTransactionData();
const relayerFee = "10";
const { blockNumber } = await prepareAndAssert(transaction, record, user, transactionManager);
const variant = {
amount: record.amount,
expiry: record.expiry,
preparedBlockNumber: blockNumber,
};
const signature = await signFulfillTransactionPayload(
transaction.transactionId,
relayerFee,
transaction.receivingChainId,
Wallet.createRandom().address,
user,
);
await expect(
transactionManager.connect(router).fulfill(convertToFulfillArgs(transaction, variant, relayerFee, signature)),
).to.be.revertedWith(getContractError("fulfill: INVALID_SIGNATURE"));
});
it("should revert if user didn't sign", async () => {
const { transaction, record } = await getTransactionData();
const relayerFee = "10";
const { blockNumber } = await prepareAndAssert(transaction, record, user, transactionManager);
const variant = {
amount: record.amount,
expiry: record.expiry,
preparedBlockNumber: blockNumber,
};
const signature = await signFulfillTransactionPayload(
transaction.transactionId,
relayerFee,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
Wallet.createRandom(),
);
await expect(
transactionManager.connect(router).fulfill(convertToFulfillArgs(transaction, variant, relayerFee, signature)),
).to.be.revertedWith(getContractError("fulfill: INVALID_SIGNATURE"));
});
});
it("happy case: router fulfills in native asset", async () => {
const prepareAmount = "100";
const assetId = AddressZero;
const relayerFee = "10";
// Add receiving liquidity
await addAndAssertLiquidity(prepareAmount, assetId, router, transactionManagerReceiverSide);
const { transaction, record } = await getTransactionData(
{
sendingAssetId: assetId,
receivingAssetId: assetId,
},
{ amount: prepareAmount },
);
// User prepares
const { blockNumber } = await prepareAndAssert(transaction, record, user);
// Router fulfills
await fulfillAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
relayerFee,
false,
router,
transactionManager,
);
});
it("happy case: router fulfills in ERC20", async () => {
const prepareAmount = "100";
const assetId = tokenA.address;
const relayerFee = "10";
// Add receiving liquidity
await approveTokens(prepareAmount, router, transactionManagerReceiverSide.address, tokenA);
await addAndAssertLiquidity(prepareAmount, assetId, router, transactionManagerReceiverSide);
const { transaction, record } = await getTransactionData(
{
sendingAssetId: AddressZero,
receivingAssetId: assetId,
},
{ amount: prepareAmount },
);
// User prepares
await approveTokens(prepareAmount, user, transactionManagerReceiverSide.address, tokenB);
const { blockNumber } = await prepareAndAssert(transaction, record, user);
// Router fulfills
await fulfillAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
relayerFee,
false,
router,
transactionManager,
);
});
it("happy case: user fulfills in native asset with a relayer fee and no external call", async () => {
const prepareAmount = "100";
const assetId = AddressZero;
const relayerFee = "10";
// Add receiving liquidity
await addAndAssertLiquidity(prepareAmount, assetId, router, transactionManagerReceiverSide);
const { transaction, record } = await getTransactionData(
{
sendingChainId: (await transactionManager.getChainId()).toNumber(),
receivingChainId: (await transactionManagerReceiverSide.getChainId()).toNumber(),
sendingAssetId: assetId,
receivingAssetId: assetId,
},
{ amount: prepareAmount },
);
// Router prepares
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
// User fulfills
await fulfillAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
relayerFee,
true,
user,
transactionManagerReceiverSide,
);
});
it("happy case: user fulfills in ERC20 with a relayer fee", async () => {
const prepareAmount = "100";
const assetId = tokenB.address;
const relayerFee = "10";
// Add receiving liquidity
await approveTokens(prepareAmount, router, transactionManagerReceiverSide.address, tokenB);
await addAndAssertLiquidity(prepareAmount, assetId);
const { transaction, record } = await getTransactionData(
{
sendingChainId: (await transactionManager.getChainId()).toNumber(),
receivingChainId: (await transactionManagerReceiverSide.getChainId()).toNumber(),
sendingAssetId: tokenA.address,
receivingAssetId: assetId,
},
{ amount: prepareAmount },
);
// Router prepares
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
// User fulfills
await fulfillAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
relayerFee,
true,
user,
transactionManagerReceiverSide,
);
});
it("happy case: user fulfills in ERC20 with a successful external call", async () => {
const prepareAmount = "100";
const assetId = tokenB.address;
const relayerFee = "10";
const counterAmount = BigNumber.from(prepareAmount).sub(relayerFee);
// Get calldata
const callData = counter.interface.encodeFunctionData("incrementAndSend", [
assetId,
other.address,
counterAmount.toString(),
]);
const callDataHash = utils.keccak256(callData);
// Add receiving liquidity
await approveTokens(prepareAmount, router, transactionManagerReceiverSide.address, tokenB);
await addAndAssertLiquidity(prepareAmount, assetId);
const { transaction, record } = await getTransactionData(
{
sendingAssetId: tokenA.address,
receivingAssetId: assetId,
callDataHash,
callTo: counter.address,
},
{ amount: prepareAmount },
);
// Router prepares
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
const preExecute = await counter.count();
const balance = await getOnchainBalance(assetId, other.address, other.provider);
// User fulfills
await fulfillAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
relayerFee,
true,
user,
transactionManagerReceiverSide,
callData,
);
expect(await counter.count()).to.be.eq(preExecute.add(1));
expect(await getOnchainBalance(assetId, other.address, other.provider)).to.be.eq(balance.add(counterAmount));
});
it("happy case: user fulfills in native asset with a successful external call", async () => {
const prepareAmount = "10";
const relayerFee = "1";
const counterAmount = BigNumber.from(prepareAmount).sub(relayerFee);
// Get calldata
const callData = counter.interface.encodeFunctionData("incrementAndSend", [
AddressZero,
other.address,
counterAmount.toString(),
]);
const callDataHash = utils.keccak256(callData);
const { transaction, record } = await getTransactionData(
{
sendingAssetId: AddressZero,
receivingAssetId: AddressZero,
callTo: counter.address,
callDataHash: callDataHash,
},
{ amount: prepareAmount },
);
await addAndAssertLiquidity(prepareAmount, transaction.receivingAssetId, router, transactionManagerReceiverSide);
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
const preExecute = await counter.count();
const balance = await other.getBalance();
await fulfillAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
relayerFee,
true,
user,
transactionManagerReceiverSide,
callData,
);
expect(await counter.count()).to.be.eq(preExecute.add(1));
expect(await other.getBalance()).to.be.eq(balance.add(counterAmount));
});
it("happy case: user fulfills in ERC20 with an unsuccessful external call (sends to fallback address)", async () => {
const prepareAmount = "100";
const assetId = tokenB.address;
const relayerFee = "10";
const counterAmount = BigNumber.from(prepareAmount).sub(relayerFee);
// Set to revert
const revert = await counter.connect(wallet).setShouldRevert(true);
await revert.wait();
expect(await counter.shouldRevert()).to.be.true;
// Get calldata
const callData = counter.interface.encodeFunctionData("incrementAndSend", [
assetId,
other.address,
counterAmount.toString(),
]);
const callDataHash = utils.keccak256(callData);
// Add receiving liquidity
await approveTokens(prepareAmount, router, transactionManagerReceiverSide.address, tokenB);
await addAndAssertLiquidity(prepareAmount, assetId);
const { transaction, record } = await getTransactionData(
{
sendingAssetId: tokenA.address,
receivingAssetId: assetId,
callDataHash,
callTo: counter.address,
},
{ amount: prepareAmount },
);
// Router prepares
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
const preExecute = await counter.count();
const otherBalance = await getOnchainBalance(assetId, other.address, other.provider);
const fallbackBalance = await getOnchainBalance(assetId, transaction.receivingAddress, other.provider);
// User fulfills
await fulfillAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
relayerFee,
true,
user,
transactionManagerReceiverSide,
callData,
);
expect(await counter.count()).to.be.eq(preExecute);
expect(await getOnchainBalance(assetId, other.address, other.provider)).to.be.eq(otherBalance);
expect(await getOnchainBalance(assetId, transaction.receivingAddress, other.provider)).to.be.eq(
fallbackBalance.add(counterAmount),
);
});
it("happy case: user fulfills in native asset with an unsuccessful external call (sends to fallback address)", async () => {
const prepareAmount = "10";
const relayerFee = "1";
const counterAmount = BigNumber.from(prepareAmount).sub(relayerFee);
// Set to revert
const revert = await counter.connect(wallet).setShouldRevert(true);
await revert.wait();
expect(await counter.shouldRevert()).to.be.true;
// Get calldata
const callData = counter.interface.encodeFunctionData("incrementAndSend", [
AddressZero,
other.address,
counterAmount.toString(),
]);
const callDataHash = utils.keccak256(callData);
const fallback = Wallet.createRandom().connect(ethers.provider);
const { transaction, record } = await getTransactionData(
{
sendingAssetId: AddressZero,
receivingAssetId: AddressZero,
callTo: counter.address,
callDataHash: callDataHash,
receivingAddress: fallback.address,
},
{ amount: prepareAmount },
);
await addAndAssertLiquidity(prepareAmount, transaction.receivingAssetId, router, transactionManagerReceiverSide);
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
const preExecute = await counter.count();
const fallbackBalance = await fallback.getBalance();
const otherBalance = await other.getBalance();
await fulfillAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
relayerFee,
true,
user,
transactionManagerReceiverSide,
callData,
);
expect(await counter.count()).to.be.eq(preExecute);
expect(await other.getBalance()).to.be.eq(otherBalance);
expect(await fallback.getBalance()).to.be.eq(fallbackBalance.add(counterAmount));
});
it("happy case: user fulfills relayerFee-valued tx", async () => {
const prepareAmount = "10";
const assetId = AddressZero;
const relayerFee = prepareAmount;
// Add receiving liquidity
await addAndAssertLiquidity(prepareAmount, assetId, router, transactionManagerReceiverSide);
const { transaction, record } = await getTransactionData(
{
sendingChainId: (await transactionManager.getChainId()).toNumber(),
receivingChainId: (await transactionManagerReceiverSide.getChainId()).toNumber(),
sendingAssetId: assetId,
receivingAssetId: assetId,
},
{ amount: prepareAmount },
);
// Router prepares
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
// User fulfills
await fulfillAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
relayerFee,
true,
user,
transactionManagerReceiverSide,
);
});
it("happy case: user fulfills 0-valued tx", async () => {
const prepareAmount = "0";
const assetId = AddressZero;
const { transaction, record } = await getTransactionData(
{
sendingChainId: (await transactionManager.getChainId()).toNumber(),
receivingChainId: (await transactionManagerReceiverSide.getChainId()).toNumber(),
sendingAssetId: assetId,
receivingAssetId: assetId,
},
{ amount: prepareAmount },
);
// Router prepares
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
// User fulfills
await fulfillAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
"0",
true,
user,
transactionManagerReceiverSide,
);
});
});
describe("cancel", () => {
it("should error if invalid txData", async () => {
const prepareAmount = "10";
const assetId = AddressZero;
// Add receiving liquidity
await addAndAssertLiquidity(prepareAmount, assetId, router, transactionManagerReceiverSide);
const { transaction, record } = await getTransactionData({}, { amount: prepareAmount });
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
const signature = await signCancelTransactionPayload(
transaction.transactionId,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
const args = convertToCancelArgs(transaction, { ...record, preparedBlockNumber: 0 }, signature);
await expect(transactionManagerReceiverSide.connect(user).cancel(args)).to.be.revertedWith(
getContractError("cancel: INVALID_VARIANT_DATA"),
);
});
it("should error if txData.preparedBlockNumber > 0 is (already fulfilled/cancelled)", async () => {
const prepareAmount = "10";
const assetId = AddressZero;
const relayerFee = constants.Zero;
// Add receiving liquidity
await addAndAssertLiquidity(prepareAmount, assetId, router, transactionManagerReceiverSide);
const { transaction, record } = await getTransactionData({}, { amount: prepareAmount });
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
// User fulfills
await fulfillAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
relayerFee.toString(),
true,
user,
transactionManagerReceiverSide,
);
const signature = await signCancelTransactionPayload(
transaction.transactionId,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
const args = convertToCancelArgs(transaction, { ...record, preparedBlockNumber: 0 }, signature);
await expect(transactionManagerReceiverSide.connect(user).cancel(args)).to.be.revertedWith(
getContractError("cancel: ALREADY_COMPLETED"),
);
});
describe("sending chain reverts (returns funds to user)", () => {
it("should fail if expiry didn't pass yet & msg.sender != router", async () => {
const prepareAmount = "10";
const { transaction, record } = await getTransactionData(
{
sendingAssetId: AddressZero,
receivingAssetId: tokenB.address,
},
{
amount: prepareAmount,
},
);
const { blockNumber } = await prepareAndAssert(transaction, record, user, transactionManager);
const signature = await signCancelTransactionPayload(
transaction.transactionId,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
const args = convertToCancelArgs(transaction, { ...record, preparedBlockNumber: blockNumber }, signature);
await expect(transactionManager.connect(receiver).cancel(args)).to.be.revertedWith(
getContractError("cancel: ROUTER_MUST_CANCEL"),
);
});
it("should fail if expiry didn't pass yet & msg.sender == router & transferAsset fails", async () => {
const prepareAmount = "10";
const { transaction, record } = await getTransactionData(
{
sendingAssetId: tokenA.address,
receivingAssetId: tokenB.address,
},
{
amount: prepareAmount,
},
);
await approveTokens(prepareAmount, user, transactionManager.address);
const { blockNumber } = await prepareAndAssert(transaction, record, user, transactionManager);
// Set should revert to true on sending asset
await (await tokenA.connect(wallet).setShouldRevert(true)).wait();
expect(await tokenA.shouldRevert()).to.be.true;
const signature = await signCancelTransactionPayload(
transaction.transactionId,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
const args = convertToCancelArgs(transaction, { ...record, preparedBlockNumber: blockNumber }, signature);
await expect(transactionManager.connect(router).cancel(args)).to.be.revertedWith("transfer: SHOULD_REVERT");
});
it("should error if is expired & relayerFee != 0 & user is sending & transfer to relayer fails", async () => {
const prepareAmount = "10";
const { transaction, record } = await getTransactionData(
{
sendingAssetId: tokenA.address,
receivingAssetId: tokenB.address,
},
{
amount: prepareAmount,
},
);
await approveTokens(prepareAmount, user, transactionManager.address);
const { blockNumber } = await prepareAndAssert(transaction, record, user, transactionManager);
await (await tokenA.connect(wallet).setShouldRevert(true)).wait();
expect(await tokenA.shouldRevert()).to.be.true;
await setBlockTime(+record.expiry + 1_000);
const signature = await signCancelTransactionPayload(
transaction.transactionId,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
const args = convertToCancelArgs(transaction, { ...record, preparedBlockNumber: blockNumber }, signature);
await expect(transactionManager.connect(user).cancel(args)).to.be.revertedWith("transfer: SHOULD_REVERT");
});
it("should fail if is expured & relayerFee == 0 & user is sending & transfer to user fails", async () => {
const prepareAmount = "10";
const { transaction, record } = await getTransactionData(
{
sendingAssetId: tokenA.address,
receivingAssetId: tokenB.address,
},
{
amount: prepareAmount,
},
);
await approveTokens(prepareAmount, user, transactionManager.address);
const { blockNumber } = await prepareAndAssert(transaction, record, user, transactionManager);
await (await tokenA.connect(wallet).setShouldRevert(true)).wait();
expect(await tokenA.shouldRevert()).to.be.true;
await setBlockTime(+record.expiry + 1_000);
const signature = await signCancelTransactionPayload(
transaction.transactionId,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
user,
);
const args = convertToCancelArgs(transaction, { ...record, preparedBlockNumber: blockNumber }, signature);
await expect(transactionManager.connect(user).cancel(args)).to.be.revertedWith("transfer: SHOULD_REVERT");
});
});
describe("receiving chain cancels (funds sent back to router)", () => {
it("should error if within expiry & signature is invalid && user did not send", async () => {
const prepareAmount = "10";
const assetId = AddressZero;
// Add receiving liquidity
await addAndAssertLiquidity(prepareAmount, assetId, router, transactionManagerReceiverSide);
const { transaction, record } = await getTransactionData({}, { amount: prepareAmount });
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
const signature = await signCancelTransactionPayload(
transaction.transactionId,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
receiver,
);
const args = convertToCancelArgs(transaction, { ...record, preparedBlockNumber: blockNumber }, signature);
await expect(transactionManagerReceiverSide.connect(receiver).cancel(args)).to.be.revertedWith(
getContractError("cancel: INVALID_SIGNATURE"),
);
});
});
it("happy case: user cancelling expired sender chain transfer without relayer && they are sending (signature invalid)", async () => {
const prepareAmount = "10";
const assetId = AddressZero;
// Add receiving liquidity
await addAndAssertLiquidity(prepareAmount, assetId, router, transactionManagerReceiverSide);
const { transaction, record } = await getTransactionData({}, { amount: prepareAmount });
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
await setBlockTime(+record.expiry + 1_000);
await cancelAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
user,
transactionManagerReceiverSide,
await signCancelTransactionPayload(
transaction.transactionId,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
receiver,
),
);
});
it("happy case: user can cancel receiving chain transfer themselves with invalid signature", async () => {
const prepareAmount = "10";
const assetId = AddressZero;
// Add receiving liquidity
await addAndAssertLiquidity(prepareAmount, assetId, router, transactionManagerReceiverSide);
const { transaction, record } = await getTransactionData({}, { amount: prepareAmount });
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
const signature = await signCancelTransactionPayload(
transaction.transactionId,
transaction.receivingChainId,
transaction.receivingChainTxManagerAddress,
receiver,
);
await cancelAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
user, // To avoid balance checks for eth
transactionManagerReceiverSide,
signature,
);
});
it("happy case: user cancels ETH before expiry on receiving chain", async () => {
const prepareAmount = "10";
const assetId = AddressZero;
// Add receiving liquidity
await addAndAssertLiquidity(prepareAmount, assetId, router, transactionManagerReceiverSide);
const { transaction, record } = await getTransactionData({}, { amount: prepareAmount });
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
await cancelAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
user, // To avoid balance checks for eth
transactionManagerReceiverSide,
);
});
it("happy case: user cancels ERC20 before expiry on receiving chain", async () => {
const prepareAmount = "10";
// Add receiving liquidity
await approveTokens(prepareAmount, router, transactionManagerReceiverSide.address, tokenB);
await addAndAssertLiquidity(prepareAmount, tokenB.address, router, transactionManagerReceiverSide);
const { transaction, record } = await getTransactionData(
{
sendingAssetId: tokenA.address,
receivingAssetId: tokenB.address,
},
{ amount: prepareAmount },
);
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
await cancelAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
user, // To avoid balance checks for eth
transactionManagerReceiverSide,
);
});
it("happy case: router cancels ETH before expiry on sending chain", async () => {
const prepareAmount = "10";
const { transaction, record } = await getTransactionData(
{
sendingAssetId: AddressZero,
receivingAssetId: tokenB.address,
},
{
amount: prepareAmount,
},
);
const { blockNumber } = await prepareAndAssert(transaction, record, user, transactionManager);
await cancelAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
router, // To avoid balance checks for eth
transactionManager,
);
});
it("happy case: router cancels ERC20 before expiry on sending chain", async () => {
const prepareAmount = "10";
const { transaction, record } = await getTransactionData(
{
sendingAssetId: tokenA.address,
receivingAssetId: tokenB.address,
},
{
amount: prepareAmount,
},
);
await approveTokens(prepareAmount, user, transactionManager.address, tokenA);
const { blockNumber } = await prepareAndAssert(transaction, record, user, transactionManager);
await cancelAndAssert(transaction, { ...record, preparedBlockNumber: blockNumber }, router, transactionManager);
});
it("happy case: user cancels ETH after expiry on sending chain", async () => {
const prepareAmount = "10";
const assetId = AddressZero;
// Add receiving liquidity
await addAndAssertLiquidity(prepareAmount, assetId, router, transactionManagerReceiverSide);
const { transaction, record } = await getTransactionData({}, { amount: prepareAmount });
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
await setBlockTime(+record.expiry + 1_000);
await cancelAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
user,
transactionManagerReceiverSide,
);
});
it("happy case: user cancels ERC20 after expiry on sending chain", async () => {
const prepareAmount = "10";
// Add receiving liquidity
await approveTokens(prepareAmount, router, transactionManagerReceiverSide.address, tokenB);
await addAndAssertLiquidity(prepareAmount, tokenB.address, router, transactionManagerReceiverSide);
const { transaction, record } = await getTransactionData(
{
sendingAssetId: tokenA.address,
receivingAssetId: tokenB.address,
},
{ amount: prepareAmount },
);
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
await setBlockTime(+record.expiry + 1_000);
await cancelAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
user,
transactionManagerReceiverSide,
"0x",
);
});
it("happy case: router cancels ETH after expiry", async () => {
const prepareAmount = "10";
const { transaction, record } = await getTransactionData(
{
sendingAssetId: AddressZero,
receivingAssetId: tokenB.address,
},
{
amount: prepareAmount,
},
);
const { blockNumber } = await prepareAndAssert(transaction, record, user, transactionManager);
await setBlockTime(+record.expiry + 1_000);
await cancelAndAssert(transaction, { ...record, preparedBlockNumber: blockNumber }, router, transactionManager);
});
it("happy case: router cancels ERC20 after expiry", async () => {
const prepareAmount = "10";
const { transaction, record } = await getTransactionData(
{
sendingAssetId: tokenA.address,
receivingAssetId: tokenB.address,
},
{
amount: prepareAmount,
},
);
await approveTokens(prepareAmount, user, transactionManager.address, tokenA);
const { blockNumber } = await prepareAndAssert(transaction, record, user, transactionManager);
await setBlockTime(+record.expiry + 1_000);
await cancelAndAssert(transaction, { ...record, preparedBlockNumber: blockNumber }, router, transactionManager);
});
it("happy case: relayer cancels at sender-side ETH after expiry", async () => {
const prepareAmount = "10";
const { transaction, record } = await getTransactionData(
{
sendingAssetId: AddressZero,
receivingAssetId: tokenB.address,
},
{
amount: prepareAmount,
},
);
const { blockNumber } = await prepareAndAssert(transaction, record, user, transactionManager);
await setBlockTime(+record.expiry + 1_000);
await cancelAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
other,
transactionManager,
"0x",
);
});
it("happy case: relayer cancels at receiver-side ETH after expiry", async () => {
const prepareAmount = "10";
const assetId = AddressZero;
// Add receiving liquidity
await addAndAssertLiquidity(prepareAmount, assetId, router, transactionManagerReceiverSide);
const { transaction, record } = await getTransactionData({}, { amount: prepareAmount });
const { blockNumber } = await prepareAndAssert(transaction, record, router, transactionManagerReceiverSide);
await setBlockTime(+record.expiry + 1_000);
await cancelAndAssert(
transaction,
{ ...record, preparedBlockNumber: blockNumber },
other,
transactionManagerReceiverSide,
);
});
});
}); | the_stack |
import React from 'react';
import { Button, MenuItem } from '@mui/material';
import { Form } from 'react-final-form';
import { Select, SelectData, SelectProps } from '../src';
import { act, customRender, fireEvent } from './TestUtils';
describe('Select', () => {
describe('basic component', () => {
interface ComponentProps {
data: SelectData[];
initialValues: FormData;
validator?: any;
label: boolean;
variant?: SelectProps['variant'];
}
interface FormData {
best: string;
}
const selectData: SelectData[] = [
{ label: 'Ack', value: 'ack' },
{ label: 'Bar', value: 'bar' },
{ label: 'Foo', value: 'foo' },
];
const initialValues: FormData = {
best: 'bar',
};
function SelectComponent({ initialValues, data, validator, label, variant }: ComponentProps) {
const onSubmit = (values: FormData) => {
console.log(values);
};
const validate = async (values: FormData) => {
if (validator) {
return validator(values);
}
};
return (
<Form
onSubmit={onSubmit}
initialValues={initialValues}
validate={validate}
render={({ handleSubmit }) => (
<form onSubmit={handleSubmit} noValidate data-testid="form">
<Select
label={label ? 'Test' : undefined}
required={true}
name="best"
data={data}
variant={variant}
formControlProps={{ margin: 'normal' }}
/>
</form>
)}
/>
);
}
it('renders without errors', async () => {
await act(async () => {
const rendered = customRender(
<SelectComponent data={selectData} initialValues={initialValues} label={true} />,
);
expect(rendered).toMatchSnapshot();
});
});
it('renders a selected item', async () => {
const { findByTestId } = customRender(
<SelectComponent data={selectData} initialValues={initialValues} label={true} />,
);
const form = await findByTestId('form');
const input = form.getElementsByTagName('input').item(0) as HTMLInputElement;
expect(input.value).toBe('bar');
});
it('has the Test label', async () => {
await act(async () => {
const rendered = customRender(
<SelectComponent data={selectData} initialValues={initialValues} label={true} />,
);
const elem = rendered.getAllByText('Test')[0] as HTMLLegendElement;
expect(elem.tagName).toBe('LABEL');
});
});
it('has the required *', async () => {
await act(async () => {
const rendered = customRender(
<SelectComponent data={selectData} initialValues={initialValues} label={true} />,
);
const elem = rendered.getByText('*') as HTMLSpanElement;
expect(elem.tagName).toBe('SPAN');
expect(elem.innerHTML).toBe(' *');
});
});
it('renders outlined', async () => {
await act(async () => {
const rendered = customRender(
<SelectComponent data={selectData} initialValues={initialValues} variant="outlined" label={true} />,
);
expect(rendered).toMatchSnapshot();
});
});
it('renders outlined without a label', async () => {
await act(async () => {
const rendered = customRender(
<SelectComponent
data={selectData}
initialValues={initialValues}
variant="outlined"
label={false}
/>,
);
expect(rendered).toMatchSnapshot();
});
});
it('requires something selected', async () => {
// const message = 'something for testing';
//
// const validateSchema = makeValidate(
// Yup.object().shape({
// best: Yup.string().required(message),
// })
// );
//
// const rendered = customRender(
// <SelectComponent
// data={selectData}
// validator={validateSchema}
// initialValues={initialValues}
// />
// );
// TODO: write this test...
});
});
describe('MenuItem component', () => {
interface ComponentProps {
data: SelectData[];
initialValues: FormData;
validator?: any;
}
interface FormData {
best: string;
}
const selectData: SelectData[] = [
{ label: 'Ack', value: 'ack' },
{ label: 'Bar', value: 'bar' },
{ label: 'Foo', value: 'foo' },
];
const initialValues: FormData = {
best: 'bar',
};
function SelectComponentMenuItem({ initialValues, data, validator }: ComponentProps) {
const onSubmit = (values: FormData) => {
console.log(values);
};
const validate = async (values: FormData) => {
if (validator) {
return validator(values);
}
};
return (
<Form
onSubmit={onSubmit}
initialValues={initialValues}
validate={validate}
render={({ handleSubmit }) => (
<form onSubmit={handleSubmit} noValidate data-testid="form">
<Select label="Test" required={true} name="best">
{data.map((item, idx) => (
<MenuItem value={item.value} key={idx}>
{item.label}
</MenuItem>
))}
</Select>
</form>
)}
/>
);
}
it('renders using menu items', async () => {
const { findByTestId, container } = customRender(
<SelectComponentMenuItem data={selectData} initialValues={initialValues} />,
);
const form = await findByTestId('form');
const input = form.getElementsByTagName('input').item(0) as HTMLInputElement;
expect(input.value).toBe('bar');
expect(container).toMatchSnapshot();
});
});
describe('Multiple', () => {
interface FormData {
best: string[];
}
interface ComponentProps {
data: SelectData[];
initialValues: FormData;
validator?: any;
multiple?: boolean;
}
const selectData: SelectData[] = [
{ label: 'Ack', value: 'ack' },
{ label: 'Bar', value: 'bar' },
{ label: 'Foo', value: 'foo' },
];
const initialValues: FormData = {
best: ['bar', 'ack'],
};
function SelectComponent({ initialValues, data, validator, multiple }: ComponentProps) {
const onSubmit = (values: FormData) => {
console.log(values);
};
const validate = async (values: FormData) => {
if (validator) {
return validator(values);
}
};
return (
<Form
onSubmit={onSubmit}
initialValues={initialValues}
validate={validate}
render={({ handleSubmit }) => (
<form onSubmit={handleSubmit} noValidate>
<Select label="Test" required={true} name="best" data={data} multiple={multiple} />
</form>
)}
/>
);
}
it('has multiple', async () => {
await act(async () => {
const rendered = customRender(
<SelectComponent data={selectData} initialValues={initialValues} multiple={true} />,
);
expect(rendered).toMatchSnapshot();
});
});
});
describe('displayEmpty', () => {
interface ComponentProps {
data: SelectData[];
initialValues: FormData;
validator?: any;
}
interface FormData {
best: string[];
}
const selectData: SelectData[] = [
{ label: 'Empty', value: '' },
{ label: 'Ack', value: 'ack' },
{ label: 'Bar', value: 'bar' },
{ label: 'Foo', value: 'foo' },
];
const initialValues: FormData = {
best: [''],
};
function SelectComponent({ initialValues, data, validator }: ComponentProps) {
const onSubmit = (values: FormData) => {
console.log(values);
};
const validate = async (values: FormData) => {
if (validator) {
return validator(values);
}
};
return (
<Form
onSubmit={onSubmit}
initialValues={initialValues}
validate={validate}
render={({ handleSubmit }) => (
<form onSubmit={handleSubmit} noValidate>
<Select label="Test" required={true} name="best" data={data} displayEmpty={true} />
</form>
)}
/>
);
}
it('renders without errors', async () => {
await act(async () => {
const rendered = customRender(<SelectComponent data={selectData} initialValues={initialValues} />);
expect(rendered).toMatchSnapshot();
});
});
});
describe('errors with single', () => {
interface ComponentProps {
data: SelectData[];
initialValues: FormData;
onSubmit?: any;
}
interface FormData {
best: string;
}
const selectData: SelectData[] = [
{ label: 'Ack', value: 'ack' },
{ label: 'Bar', value: 'bar' },
{ label: 'Foo', value: 'foo' },
];
function SelectComponent({ initialValues, data, onSubmit = () => {} }: ComponentProps) {
const validate = async (values: FormData) => {
if (!values.best.length) {
return { best: 'is not best' };
}
return;
};
return (
<Form
onSubmit={onSubmit}
initialValues={initialValues}
validate={validate}
render={({ handleSubmit, submitting }) => (
<form onSubmit={handleSubmit} noValidate>
<Select label="Test" required={true} name="best" helperText="omg helper text">
{data.map((item, idx) => (
<MenuItem value={item.value} key={idx}>
{item.label}
</MenuItem>
))}
</Select>
<Button
variant="contained"
color="primary"
type="submit"
disabled={submitting}
data-testid="submit"
>
Submit
</Button>
</form>
)}
/>
);
}
it('renders the helper text because no error', async () => {
const initialValues: FormData = {
best: '',
};
const { findByTestId, findByText, container } = customRender(
<SelectComponent data={selectData} initialValues={initialValues} />,
);
await findByText('omg helper text');
const submit = await findByTestId('submit');
fireEvent.click(submit);
// this snapshot won't have the helper text in it
expect(container).toMatchSnapshot();
});
it('has empty initialValues and submit', async () => {
const initialValues: FormData = {
best: '',
};
const { findByTestId, findByText, container } = customRender(
<SelectComponent data={selectData} initialValues={initialValues} />,
);
const submit = await findByTestId('submit');
fireEvent.click(submit);
await findByText('is not best');
expect(container).toMatchSnapshot();
});
it('shows submit error', async () => {
const onSubmit = () => {
return { best: 'submit error' };
};
const initialValues: FormData = {
best: 'ack',
};
const { findByTestId, findByText, container } = customRender(
<SelectComponent data={selectData} initialValues={initialValues} onSubmit={onSubmit} />,
);
const submit = await findByTestId('submit');
fireEvent.click(submit);
await findByText('submit error');
expect(container).toMatchSnapshot();
});
});
describe('errors with multiple', () => {
interface ComponentProps {
data: SelectData[];
initialValues: FormData;
onSubmit?: any;
}
interface FormData {
best: string[];
}
const selectData: SelectData[] = [
{ label: 'Ack', value: 'ack' },
{ label: 'Bar', value: 'bar' },
{ label: 'Foo', value: 'foo' },
];
function SelectComponent({ initialValues, data, onSubmit = () => {} }: ComponentProps) {
const validate = async (values: FormData) => {
if (!values.best.length) {
return { best: 'is not best' };
}
return;
};
return (
<Form
onSubmit={onSubmit}
initialValues={initialValues}
validate={validate}
render={({ handleSubmit, submitting }) => (
<form onSubmit={handleSubmit} noValidate>
<Select
label="Test"
required={true}
name="best"
multiple={true}
helperText="omg helper text"
>
{data.map((item, idx) => (
<MenuItem value={item.value} key={idx}>
{item.label}
</MenuItem>
))}
</Select>
<Button
variant="contained"
color="primary"
type="submit"
disabled={submitting}
data-testid="submit"
>
Submit
</Button>
</form>
)}
/>
);
}
it('renders the helper text because no error', async () => {
const initialValues: FormData = {
best: [],
};
const { findByTestId, findByText, container } = customRender(
<SelectComponent data={selectData} initialValues={initialValues} />,
);
await findByText('omg helper text');
const submit = await findByTestId('submit');
fireEvent.click(submit);
// this snapshot won't have the helper text in it
expect(container).toMatchSnapshot();
});
it('has empty initialValues and submit', async () => {
const initialValues: FormData = {
best: [],
};
const { findByTestId, findByText, container } = customRender(
<SelectComponent data={selectData} initialValues={initialValues} />,
);
const submit = await findByTestId('submit');
fireEvent.click(submit);
await findByText('is not best');
expect(container).toMatchSnapshot();
});
it('shows submit error', async () => {
const onSubmit = () => {
return { best: 'submit error' };
};
const initialValues: FormData = {
best: ['ack'],
};
const { findByTestId, findByText, container } = customRender(
<SelectComponent data={selectData} initialValues={initialValues} onSubmit={onSubmit} />,
);
const submit = await findByTestId('submit');
fireEvent.click(submit);
await findByText('submit error');
expect(container).toMatchSnapshot();
});
});
describe('works without initialValues', () => {
interface ComponentProps {
data: SelectData[];
multiple: boolean;
}
const selectData: SelectData[] = [
{ label: 'Ack', value: 'ack' },
{ label: 'Bar', value: 'bar' },
{ label: 'Foo', value: 'foo' },
];
function SelectComponent({ data, multiple }: ComponentProps) {
return (
<Form
onSubmit={() => {}}
initialValues={{}}
render={({ handleSubmit }) => (
<form onSubmit={handleSubmit} noValidate>
<Select
label="Test"
required={true}
name="best"
multiple={multiple}
helperText="omg helper text"
>
{data.map((item, idx) => (
<MenuItem value={item.value} key={idx}>
{item.label}
</MenuItem>
))}
</Select>
</form>
)}
/>
);
}
it('renders multiple=true without error', async () => {
const { container } = customRender(<SelectComponent data={selectData} multiple={true} />);
// this snapshot won't have the helper text in it
expect(container).toMatchSnapshot();
});
it('renders multiple=false without error', async () => {
const { container } = customRender(<SelectComponent data={selectData} multiple={false} />);
// this snapshot won't have the helper text in it
expect(container).toMatchSnapshot();
});
});
describe('supports correct types issue: #367', () => {
interface MyThing {
label: string;
value: string;
}
interface ComponentProps {
data: MyThing[];
multiple: boolean;
}
const selectData: MyThing[] = [
{ label: 'Ack', value: 'ack' },
{ label: 'Bar', value: 'bar' },
{ label: 'Foo', value: 'foo' },
];
function SelectComponent({ data, multiple }: ComponentProps) {
return (
<Form
onSubmit={() => {}}
initialValues={{}}
render={({ handleSubmit }) => (
<form onSubmit={handleSubmit} noValidate>
<Select
label="Test"
required={true}
name="best"
multiple={multiple}
helperText="omg helper text"
>
{data.map((item, idx) => (
<MenuItem value={item.value} key={idx}>
{item.label}
</MenuItem>
))}
</Select>
</form>
)}
/>
);
}
it('renders multiple=true without error', async () => {
const { container } = customRender(<SelectComponent data={selectData} multiple={true} />);
// this snapshot won't have the helper text in it
expect(container).toMatchSnapshot();
});
it('renders multiple=false without error', async () => {
const { container } = customRender(<SelectComponent data={selectData} multiple={false} />);
// this snapshot won't have the helper text in it
expect(container).toMatchSnapshot();
});
});
}); | the_stack |
RoomVisual.prototype.infoBox = function(info: string[], x: number, y: number, opts = {}): RoomVisual {
_.defaults(opts, {
color : colors.infoBoxGood,
textstyle: false,
textsize : speechSize,
textfont : 'verdana',
opacity : 0.7,
});
let fontstring = '';
if (opts.textstyle) {
fontstring = opts.textstyle + ' ';
}
fontstring += opts.textsize + ' ' + opts.textfont;
let pointer = [
[.9, -0.25],
[.9, 0.25],
[0.3, 0.0],
];
pointer = relPoly(x, y, pointer);
pointer.push(pointer[0]);
// Draw arrow
this.poly(pointer, {
fill : undefined,
stroke : opts.color,
opacity : opts.opacity,
strokeWidth: 0.0
});
// // Draw box
// this.rect(x + 0.9, y - 0.8 * opts.textsize,
// 0.55 * opts.textsize * _.max(_.map(info, line => line.length)), info.length * opts.textsize,
// {
// fill : undefined,
// opacity: opts.opacity
// });
// Draw vertical bar
const x0 = x + 0.9;
const y0 = y - 0.8 * opts.textsize;
this.line(x0, y0, x0, y0 + info.length * opts.textsize, {
color: opts.color,
});
// Draw text
let dy = 0;
for (const line of info) {
this.text(line, x + 1, y + dy, {
color : opts.color,
// backgroundColor : opts.background,
backgroundPadding: 0.1,
opacity : opts.opacity,
font : fontstring,
align : 'left',
});
dy += opts.textsize;
}
return this;
};
RoomVisual.prototype.multitext = function(textLines: string[], x: number, y: number, opts = {}): RoomVisual {
_.defaults(opts, {
color : colors.infoBoxGood,
textstyle: false,
textsize : speechSize,
textfont : 'verdana',
opacity : 0.7,
});
let fontstring = '';
if (opts.textstyle) {
fontstring = opts.textstyle + ' ';
}
fontstring += opts.textsize + ' ' + opts.textfont;
// // Draw vertical bar
// let x0 = x + 0.9;
// let y0 = y - 0.8 * opts.textsize;
// this.line(x0, y0, x0, y0 + textLines.length * opts.textsize, {
// color: opts.color,
// });
// Draw text
let dy = 0;
for (const line of textLines) {
this.text(line, x, y + dy, {
color : opts.color,
// backgroundColor : opts.background,
backgroundPadding: 0.1,
opacity : opts.opacity,
font : fontstring,
align : 'left',
});
dy += opts.textsize;
}
return this;
};
RoomVisual.prototype.box = function(x: number, y: number, w: number, h: number, style?: LineStyle): RoomVisual {
return this.line(x, y, x + w, y, style)
.line(x + w, y, x + w, y + h, style)
.line(x + w, y + h, x, y + h, style)
.line(x, y + h, x, y, style);
};
// Taken from https://github.com/screepers/RoomVisual with slight modification: ========================================
const colors = {
gray : '#555555',
light : '#AAAAAA',
road : '#666', // >:D
energy : '#FFE87B',
power : '#F53547',
dark : '#181818',
outline : '#8FBB93',
speechText : '#000000',
speechBackground: '#aebcc4',
infoBoxGood : '#09ff00',
infoBoxBad : '#ff2600'
};
const speechSize = 0.5;
const speechFont = 'Times New Roman';
RoomVisual.prototype.structure = function(x: number, y: number, type: string, opts = {}): RoomVisual {
_.defaults(opts, {opacity: 0.5});
switch (type) {
case STRUCTURE_EXTENSION:
this.circle(x, y, {
radius : 0.5,
fill : colors.dark,
stroke : colors.outline,
strokeWidth: 0.05,
opacity : opts.opacity
});
this.circle(x, y, {
radius : 0.35,
fill : colors.gray,
opacity: opts.opacity
});
break;
case STRUCTURE_SPAWN:
this.circle(x, y, {
radius : 0.65,
fill : colors.dark,
stroke : '#CCCCCC',
strokeWidth: 0.10,
opacity : opts.opacity
});
this.circle(x, y, {
radius : 0.40,
fill : colors.energy,
opacity: opts.opacity
});
break;
case STRUCTURE_POWER_SPAWN:
this.circle(x, y, {
radius : 0.65,
fill : colors.dark,
stroke : colors.power,
strokeWidth: 0.10,
opacity : opts.opacity
});
this.circle(x, y, {
radius : 0.40,
fill : colors.energy,
opacity: opts.opacity
});
break;
case STRUCTURE_LINK: {
// let osize = 0.3;
// let isize = 0.2;
let outer = [
[0.0, -0.5],
[0.4, 0.0],
[0.0, 0.5],
[-0.4, 0.0]
];
let inner = [
[0.0, -0.3],
[0.25, 0.0],
[0.0, 0.3],
[-0.25, 0.0]
];
outer = relPoly(x, y, outer);
inner = relPoly(x, y, inner);
outer.push(outer[0]);
inner.push(inner[0]);
this.poly(outer, {
fill : colors.dark,
stroke : colors.outline,
strokeWidth: 0.05,
opacity : opts.opacity
});
this.poly(inner, {
fill : colors.gray,
stroke : false,
opacity: opts.opacity
});
break;
}
case STRUCTURE_TERMINAL: {
let outer = [
[0.0, -0.8],
[0.55, -0.55],
[0.8, 0.0],
[0.55, 0.55],
[0.0, 0.8],
[-0.55, 0.55],
[-0.8, 0.0],
[-0.55, -0.55],
];
let inner = [
[0.0, -0.65],
[0.45, -0.45],
[0.65, 0.0],
[0.45, 0.45],
[0.0, 0.65],
[-0.45, 0.45],
[-0.65, 0.0],
[-0.45, -0.45],
];
outer = relPoly(x, y, outer);
inner = relPoly(x, y, inner);
outer.push(outer[0]);
inner.push(inner[0]);
this.poly(outer, {
fill : colors.dark,
stroke : colors.outline,
strokeWidth: 0.05,
opacity : opts.opacity
});
this.poly(inner, {
fill : colors.light,
stroke : false,
opacity: opts.opacity
});
this.rect(x - 0.45, y - 0.45, 0.9, 0.9, {
fill : colors.gray,
stroke : colors.dark,
strokeWidth: 0.1,
opacity : opts.opacity
});
break;
}
case STRUCTURE_LAB:
this.circle(x, y - 0.025, {
radius : 0.55,
fill : colors.dark,
stroke : colors.outline,
strokeWidth: 0.05,
opacity : opts.opacity
});
this.circle(x, y - 0.025, {
radius : 0.40,
fill : colors.gray,
opacity: opts.opacity
});
this.rect(x - 0.45, y + 0.3, 0.9, 0.25, {
fill : colors.dark,
stroke : false,
opacity: opts.opacity
});
{
let box = [
[-0.45, 0.3],
[-0.45, 0.55],
[0.45, 0.55],
[0.45, 0.3],
];
box = relPoly(x, y, box);
this.poly(box, {
stroke : colors.outline,
strokeWidth: 0.05,
opacity : opts.opacity
});
}
break;
case STRUCTURE_TOWER:
this.circle(x, y, {
radius : 0.6,
fill : colors.dark,
stroke : colors.outline,
strokeWidth: 0.05,
opacity : opts.opacity
});
this.rect(x - 0.4, y - 0.3, 0.8, 0.6, {
fill : colors.gray,
opacity: opts.opacity
});
this.rect(x - 0.2, y - 0.9, 0.4, 0.5, {
fill : colors.light,
stroke : colors.dark,
strokeWidth: 0.07,
opacity : opts.opacity
});
break;
case STRUCTURE_ROAD:
this.circle(x, y, {
radius : 0.175,
fill : colors.road,
stroke : false,
opacity: opts.opacity
});
if (!this.roads) this.roads = [];
this.roads.push([x, y]);
break;
case STRUCTURE_RAMPART:
this.circle(x, y, {
radius : 0.65,
fill : '#434C43',
stroke : '#5D735F',
strokeWidth: 0.10,
opacity : opts.opacity
});
break;
case STRUCTURE_WALL:
this.circle(x, y, {
radius : 0.40,
fill : colors.dark,
stroke : colors.light,
strokeWidth: 0.05,
opacity : opts.opacity
});
break;
case STRUCTURE_STORAGE:
const storageOutline = relPoly(x, y, [
[-0.45, -0.55],
[0, -0.65],
[0.45, -0.55],
[0.55, 0],
[0.45, 0.55],
[0, 0.65],
[-0.45, 0.55],
[-0.55, 0],
[-0.45, -0.55],
]);
this.poly(storageOutline, {
stroke : colors.outline,
strokeWidth: 0.05,
fill : colors.dark,
opacity : opts.opacity
});
this.rect(x - 0.35, y - 0.45, 0.7, 0.9, {
fill : colors.energy,
opacity: opts.opacity,
});
break;
case STRUCTURE_OBSERVER:
this.circle(x, y, {
fill : colors.dark,
radius : 0.45,
stroke : colors.outline,
strokeWidth: 0.05,
opacity : opts.opacity
});
this.circle(x + 0.225, y, {
fill : colors.outline,
radius : 0.20,
opacity: opts.opacity
});
break;
case STRUCTURE_NUKER:
let outline = [
[0, -1],
[-0.47, 0.2],
[-0.5, 0.5],
[0.5, 0.5],
[0.47, 0.2],
[0, -1],
];
outline = relPoly(x, y, outline);
this.poly(outline, {
stroke : colors.outline,
strokeWidth: 0.05,
fill : colors.dark,
opacity : opts.opacity
});
let inline = [
[0, -.80],
[-0.40, 0.2],
[0.40, 0.2],
[0, -.80],
];
inline = relPoly(x, y, inline);
this.poly(inline, {
stroke : colors.outline,
strokeWidth: 0.01,
fill : colors.gray,
opacity : opts.opacity
});
break;
case STRUCTURE_CONTAINER:
this.rect(x - 0.225, y - 0.3, 0.45, 0.6, {
fill : 'yellow',
opacity : opts.opacity,
stroke : colors.dark,
strokeWidth: 0.10,
});
break;
default:
this.circle(x, y, {
fill : colors.light,
radius : 0.35,
stroke : colors.dark,
strokeWidth: 0.20,
opacity : opts.opacity
});
break;
}
return this;
};
const dirs = [
[],
[0, -1],
[1, -1],
[1, 0],
[1, 1],
[0, 1],
[-1, 1],
[-1, 0],
[-1, -1]
];
RoomVisual.prototype.connectRoads = function(opts = {}): RoomVisual | void {
_.defaults(opts, {opacity: 0.5});
const color = opts.color || colors.road || 'white';
if (!this.roads) return;
// this.text(this.roads.map(r=>r.join(',')).join(' '),25,23)
this.roads.forEach((r: number[]) => {
// this.text(`${r[0]},${r[1]}`,r[0],r[1],{ size: 0.2 })
for (let i = 1; i <= 4; i++) {
const d = dirs[i];
const c = [r[0] + d[0], r[1] + d[1]];
const rd = _.some(<number[][]>this.roads, r => r[0] == c[0] && r[1] == c[1]);
// this.text(`${c[0]},${c[1]}`,c[0],c[1],{ size: 0.2, color: rd?'green':'red' })
if (rd) {
this.line(r[0], r[1], c[0], c[1], {
color : color,
width : 0.35,
opacity: opts.opacity
});
}
}
});
return this;
};
RoomVisual.prototype.speech = function(text: string, x: number, y: number, opts = {}): RoomVisual {
const background = !!opts.background ? opts.background : colors.speechBackground;
const textcolor = !!opts.textcolor ? opts.textcolor : colors.speechText;
// noinspection PointlessBooleanExpressionJS
const textstyle = !!opts.textstyle ? opts.textstyle : false;
const textsize = !!opts.textsize ? opts.textsize : speechSize;
const textfont = !!opts.textfont ? opts.textfont : speechFont;
const opacity = !!opts.opacity ? opts.opacity : 1;
let fontstring = '';
if (textstyle) {
fontstring = textstyle + ' ';
}
fontstring += textsize + ' ' + textfont;
let pointer = [
[-0.2, -0.8],
[0.2, -0.8],
[0, -0.3]
];
pointer = relPoly(x, y, pointer);
pointer.push(pointer[0]);
this.poly(pointer, {
fill : background,
stroke : background,
opacity : opacity,
strokeWidth: 0.0
});
this.text(text, x, y - 1, {
color : textcolor,
backgroundColor : background,
backgroundPadding: 0.1,
opacity : opacity,
font : fontstring
});
return this;
};
RoomVisual.prototype.animatedPosition = function(x: number, y: number, opts = {}): RoomVisual {
const color = !!opts.color ? opts.color : 'blue';
const opacity = !!opts.opacity ? opts.opacity : 0.5;
let radius = !!opts.radius ? opts.radius : 0.75;
const frames = !!opts.frames ? opts.frames : 6;
const angle = (Game.time % frames * 90 / frames) * (Math.PI / 180);
const s = Math.sin(angle);
const c = Math.cos(angle);
const sizeMod = Math.abs(Game.time % frames - frames / 2) / 10;
radius += radius * sizeMod;
const points = [
rotate(0, -radius, s, c, x, y),
rotate(radius, 0, s, c, x, y),
rotate(0, radius, s, c, x, y),
rotate(-radius, 0, s, c, x, y),
rotate(0, -radius, s, c, x, y),
];
this.poly(points, {stroke: color, opacity: opacity});
return this;
};
function rotate(x: number, y: number, s: number, c: number, px: number, py: number): { x: number, y: number } {
const xDelta = x * c - y * s;
const yDelta = x * s + y * c;
return {x: px + xDelta, y: py + yDelta};
}
function relPoly(x: number, y: number, poly: number[][]): number[][] {
return poly.map(p => {
p[0] += x;
p[1] += y;
return p;
});
}
RoomVisual.prototype.test = function(): RoomVisual {
const demopos = [19, 24];
this.clear();
this.structure(demopos[0] + 0, demopos[1] + 0, STRUCTURE_LAB);
this.structure(demopos[0] + 1, demopos[1] + 1, STRUCTURE_TOWER);
this.structure(demopos[0] + 2, demopos[1] + 0, STRUCTURE_LINK);
this.structure(demopos[0] + 3, demopos[1] + 1, STRUCTURE_TERMINAL);
this.structure(demopos[0] + 4, demopos[1] + 0, STRUCTURE_EXTENSION);
this.structure(demopos[0] + 5, demopos[1] + 1, STRUCTURE_SPAWN);
this.animatedPosition(demopos[0] + 7, demopos[1]);
this.speech('This is a test!', demopos[0] + 10, demopos[1], {opacity: 0.7});
// this.infoBox(['This is', 'a test', 'mmmmmmmmmmmmm'], demopos[0] + 15, demopos[1]);
return this;
};
const ColorSets: { [color: string]: [string, string] } = {
white : ['#ffffff', '#4c4c4c'],
grey : ['#b4b4b4', '#4c4c4c'],
red : ['#ff7b7b', '#592121'],
yellow: ['#fdd388', '#5d4c2e'],
green : ['#00f4a2', '#236144'],
blue : ['#50d7f9', '#006181'],
purple: ['#a071ff', '#371383'],
};
const ResourceColors: { [color: string]: [string, string] } = {
[RESOURCE_ENERGY]: ColorSets.yellow,
[RESOURCE_POWER] : ColorSets.red,
[RESOURCE_HYDROGEN] : ColorSets.grey,
[RESOURCE_OXYGEN] : ColorSets.grey,
[RESOURCE_UTRIUM] : ColorSets.blue,
[RESOURCE_LEMERGIUM]: ColorSets.green,
[RESOURCE_KEANIUM] : ColorSets.purple,
[RESOURCE_ZYNTHIUM] : ColorSets.yellow,
[RESOURCE_CATALYST] : ColorSets.red,
[RESOURCE_GHODIUM] : ColorSets.white,
[RESOURCE_HYDROXIDE] : ColorSets.grey,
[RESOURCE_ZYNTHIUM_KEANITE]: ColorSets.grey,
[RESOURCE_UTRIUM_LEMERGITE]: ColorSets.grey,
[RESOURCE_UTRIUM_HYDRIDE] : ColorSets.blue,
[RESOURCE_UTRIUM_OXIDE] : ColorSets.blue,
[RESOURCE_KEANIUM_HYDRIDE] : ColorSets.purple,
[RESOURCE_KEANIUM_OXIDE] : ColorSets.purple,
[RESOURCE_LEMERGIUM_HYDRIDE]: ColorSets.green,
[RESOURCE_LEMERGIUM_OXIDE] : ColorSets.green,
[RESOURCE_ZYNTHIUM_HYDRIDE] : ColorSets.yellow,
[RESOURCE_ZYNTHIUM_OXIDE] : ColorSets.yellow,
[RESOURCE_GHODIUM_HYDRIDE] : ColorSets.white,
[RESOURCE_GHODIUM_OXIDE] : ColorSets.white,
[RESOURCE_UTRIUM_ACID] : ColorSets.blue,
[RESOURCE_UTRIUM_ALKALIDE] : ColorSets.blue,
[RESOURCE_KEANIUM_ACID] : ColorSets.purple,
[RESOURCE_KEANIUM_ALKALIDE] : ColorSets.purple,
[RESOURCE_LEMERGIUM_ACID] : ColorSets.green,
[RESOURCE_LEMERGIUM_ALKALIDE]: ColorSets.green,
[RESOURCE_ZYNTHIUM_ACID] : ColorSets.yellow,
[RESOURCE_ZYNTHIUM_ALKALIDE] : ColorSets.yellow,
[RESOURCE_GHODIUM_ACID] : ColorSets.white,
[RESOURCE_GHODIUM_ALKALIDE] : ColorSets.white,
[RESOURCE_CATALYZED_UTRIUM_ACID] : ColorSets.blue,
[RESOURCE_CATALYZED_UTRIUM_ALKALIDE] : ColorSets.blue,
[RESOURCE_CATALYZED_KEANIUM_ACID] : ColorSets.purple,
[RESOURCE_CATALYZED_KEANIUM_ALKALIDE] : ColorSets.purple,
[RESOURCE_CATALYZED_LEMERGIUM_ACID] : ColorSets.green,
[RESOURCE_CATALYZED_LEMERGIUM_ALKALIDE]: ColorSets.green,
[RESOURCE_CATALYZED_ZYNTHIUM_ACID] : ColorSets.yellow,
[RESOURCE_CATALYZED_ZYNTHIUM_ALKALIDE] : ColorSets.yellow,
[RESOURCE_CATALYZED_GHODIUM_ACID] : ColorSets.white,
[RESOURCE_CATALYZED_GHODIUM_ALKALIDE] : ColorSets.white,
};
RoomVisual.prototype.resource = function(type, x, y, size = 0.25, opacity = 1) {
if (type == RESOURCE_ENERGY || type == RESOURCE_POWER) {
this._fluid(type, x, y, size, opacity);
} else if ((<string[]>[RESOURCE_CATALYST, RESOURCE_HYDROGEN, RESOURCE_OXYGEN, RESOURCE_LEMERGIUM, RESOURCE_UTRIUM,
RESOURCE_ZYNTHIUM, RESOURCE_KEANIUM])
.includes(type)) {
this._mineral(type, x, y, size, opacity);
} else if (ResourceColors[type] != undefined) {
this._compound(type, x, y, size, opacity);
} else {
return ERR_INVALID_ARGS;
}
return OK;
};
RoomVisual.prototype._fluid = function(type, x, y, size = 0.25, opacity = 1) {
this.circle(x, y, {
radius : size,
fill : ResourceColors[type][0],
opacity: opacity,
});
this.text(type[0], x, y - (size * 0.1), {
font : (size * 1.5),
color : ResourceColors[type][1],
backgroundColor : ResourceColors[type][0],
backgroundPadding: 0,
opacity : opacity
});
};
RoomVisual.prototype._mineral = function(type, x, y, size = 0.25, opacity = 1) {
this.circle(x, y, {
radius : size,
fill : ResourceColors[type][0],
opacity: opacity,
});
this.circle(x, y, {
radius : size * 0.8,
fill : ResourceColors[type][1],
opacity: opacity,
});
this.text(type, x, y + (size * 0.03), {
font : 'bold ' + (size * 1.25) + ' arial',
color : ResourceColors[type][0],
backgroundColor : ResourceColors[type][1],
backgroundPadding: 0,
opacity : opacity
});
};
RoomVisual.prototype._compound = function(type, x, y, size = 0.25, opacity = 1) {
const label = type.replace('2', '₂');
this.text(label, x, y, {
font : 'bold ' + (size * 1) + ' arial',
color : ResourceColors[type][1],
backgroundColor : ResourceColors[type][0],
backgroundPadding: 0.3 * size,
opacity : opacity
});
}; | the_stack |
import {
DateEnv,
createFormatter,
createDuration,
startOfDay,
diffWholeWeeks,
diffWholeDays,
diffDayAndTime,
Calendar,
} from '@fullcalendar/core'
import dayGridPlugin from '@fullcalendar/daygrid'
import { getDSTDeadZone } from '../lib/dst-dead-zone'
import { formatPrettyTimeZoneOffset, formatIsoTimeZoneOffset, formatIsoWithoutTz } from '../lib/datelib-utils'
describe('datelib', () => {
let enLocale
beforeEach(() => {
enLocale = new Calendar(document.createElement('div'), { // HACK
plugins: [dayGridPlugin],
}).getCurrentData().dateEnv.locale
})
describe('computeWeekNumber', () => {
it('works with local', () => {
let env = new DateEnv({
timeZone: 'UTC',
calendarSystem: 'gregory',
locale: enLocale,
})
let m1 = env.createMarker('2018-04-07')
let m2 = env.createMarker('2018-04-08')
expect(env.computeWeekNumber(m1)).toBe(14)
expect(env.computeWeekNumber(m2)).toBe(15)
})
it('works with ISO', () => {
let env = new DateEnv({
timeZone: 'UTC',
calendarSystem: 'gregory',
locale: enLocale,
weekNumberCalculation: 'ISO',
})
let m1 = env.createMarker('2018-04-01')
let m2 = env.createMarker('2018-04-02')
expect(env.computeWeekNumber(m1)).toBe(13)
expect(env.computeWeekNumber(m2)).toBe(14)
})
it('works with custom function', () => {
let env = new DateEnv({
timeZone: 'UTC',
calendarSystem: 'gregory',
locale: enLocale,
weekNumberCalculation(date) {
expect(date instanceof Date).toBe(true)
expect(date.valueOf()).toBe(Date.UTC(2018, 3, 1))
return 99
},
})
let m1 = env.createMarker('2018-04-01')
expect(env.computeWeekNumber(m1)).toBe(99)
})
})
it('startOfWeek with different firstDay', () => {
let env = new DateEnv({
timeZone: 'UTC',
calendarSystem: 'gregory',
locale: enLocale,
firstDay: 2, // tues
})
let m = env.createMarker('2018-04-19')
let w = env.startOfWeek(m)
expect(env.toDate(w)).toEqual(
new Date(Date.UTC(2018, 3, 17)),
)
})
describe('when UTC', () => {
let env
beforeEach(() => {
env = new DateEnv({
timeZone: 'UTC',
calendarSystem: 'gregory',
locale: enLocale,
})
})
describe('createMarker', () => {
it('with date', () => {
expect(
env.toDate(
env.createMarker(
new Date(2017, 5, 8),
),
),
).toEqual(
new Date(2017, 5, 8),
)
})
it('with timestamp', () => {
expect(
env.toDate(
env.createMarker(
new Date(2017, 5, 8).valueOf(),
),
),
).toEqual(
new Date(2017, 5, 8),
)
})
it('with array', () => {
expect(
env.toDate(
env.createMarker(
[2017, 5, 8],
),
),
).toEqual(
new Date(Date.UTC(2017, 5, 8)),
)
})
})
describe('ISO8601 parsing', () => {
it('parses non-tz as UTC', () => {
let res = env.createMarkerMeta('2018-06-08')
let date = env.toDate(res.marker)
expect(date).toEqual(new Date(Date.UTC(2018, 5, 8)))
expect(res.forcedTzo).toBeNull()
})
it('parses a date already in UTC', () => {
let res = env.createMarkerMeta('2018-06-08T00:00:00Z')
let date = env.toDate(res.marker)
expect(date).toEqual(new Date(Date.UTC(2018, 5, 8)))
expect(res.forcedTzo).toBeNull()
})
it('parses timezones into UTC', () => {
let res = env.createMarkerMeta('2018-06-08T00:00:00+12:00')
let date = env.toDate(res.marker)
expect(date).toEqual(new Date(Date.UTC(2018, 5, 7, 12)))
expect(res.forcedTzo).toBeNull()
})
it('detects lack of time', () => {
let res = env.createMarkerMeta('2018-06-08')
expect(res.isTimeUnspecified).toBe(true)
})
it('detects presence of time', () => {
let res = env.createMarkerMeta('2018-06-08T00:00:00')
expect(res.isTimeUnspecified).toBe(false)
})
it('parses a time with no \'T\'', () => {
let res = env.createMarkerMeta('2018-06-08 01:00:00')
let date = env.toDate(res.marker)
expect(date).toEqual(new Date(Date.UTC(2018, 5, 8, 1, 0)))
})
it('parses just a month', () => {
let res = env.createMarkerMeta('2018-06')
let date = env.toDate(res.marker)
expect(date).toEqual(new Date(Date.UTC(2018, 5, 1)))
})
it('detects presence of time even if timezone', () => {
let res = env.createMarkerMeta('2018-06-08T00:00:00+12:00')
expect(res.isTimeUnspecified).toBe(false)
})
})
it('outputs ISO8601 formatting', () => {
let marker = env.createMarker('2018-06-08T00:00:00')
let s = env.formatIso(marker)
expect(s).toBe('2018-06-08T00:00:00Z')
})
it('outputs pretty format with UTC timezone', () => {
let marker = env.createMarker('2018-06-08')
let formatter = createFormatter({
weekday: 'long',
day: 'numeric',
month: 'long',
hour: '2-digit',
minute: '2-digit',
year: 'numeric',
timeZoneName: 'short',
omitCommas: true, // for cross-browser
})
let s = env.format(marker, formatter)
expect(s).toBe('Friday June 8 2018 12:00 AM UTC')
})
describe('week number formatting', () => {
it('can output only number', () => {
let marker = env.createMarker('2018-06-08')
let formatter = createFormatter({ week: 'numeric' })
let s = env.format(marker, formatter)
expect(s).toBe('23')
})
it('can output narrow', () => {
let marker = env.createMarker('2018-06-08')
let formatter = createFormatter({ week: 'narrow' })
let s = env.format(marker, formatter)
expect(s).toBe('W23')
})
it('can output short', () => {
let marker = env.createMarker('2018-06-08')
let formatter = createFormatter({ week: 'short' })
let s = env.format(marker, formatter)
expect(s).toBe('W 23')
})
})
describe('range formatting', () => {
let formatter = createFormatter({
day: 'numeric',
month: 'long',
year: 'numeric',
separator: ' - ',
})
it('works with different days of same month', () => {
let m0 = env.createMarker('2018-06-08')
let m1 = env.createMarker('2018-06-09')
let s = env.formatRange(m0, m1, formatter)
expect(s).toBe('June 8 - 9, 2018')
})
it('works with different days of same month, with inprecise formatter', () => {
let otherFormatter = createFormatter({
month: 'long',
year: 'numeric',
})
let m0 = env.createMarker('2018-06-08')
let m1 = env.createMarker('2018-06-09')
let s = env.formatRange(m0, m1, otherFormatter)
expect(s).toBe('June 2018')
})
it('works with different day/month of same year', () => {
let m0 = env.createMarker('2018-06-08')
let m1 = env.createMarker('2018-07-09')
let s = env.formatRange(m0, m1, formatter)
expect(s).toBe('June 8 - July 9, 2018')
})
it('works with completely different dates', () => {
let m0 = env.createMarker('2018-06-08')
let m1 = env.createMarker('2020-07-09')
let s = env.formatRange(m0, m1, formatter)
expect(s).toBe('June 8, 2018 - July 9, 2020')
})
})
// date math
describe('add', () => {
it('works with positives', () => {
let dur = createDuration({
year: 1,
month: 2,
day: 3,
hour: 4,
minute: 5,
second: 6,
ms: 7,
})
let d0 = env.createMarker(new Date(Date.UTC(2018, 5, 5, 12)))
let d1 = env.toDate(env.add(d0, dur))
expect(d1).toEqual(
new Date(Date.UTC(2019, 7, 8, 16, 5, 6, 7)),
)
})
it('works with negatives', () => {
let dur = createDuration({
year: -1,
month: -2,
day: -3,
hour: -4,
minute: -5,
second: -6,
millisecond: -7,
})
let d0 = env.createMarker(new Date(Date.UTC(2018, 5, 5, 12)))
let d1 = env.toDate(env.add(d0, dur))
expect(d1).toEqual(
new Date(Date.UTC(2017, 3, 2, 7, 54, 53, 993)),
)
})
})
// test in Safari!
// https://github.com/fullcalendar/fullcalendar/issues/4363
it('startOfYear', () => {
let d0 = env.createMarker(new Date(Date.UTC(2018, 5, 5, 12)))
let d1 = env.toDate(env.startOfYear(d0))
expect(d1).toEqual(
new Date(Date.UTC(2018, 0, 1)),
)
})
it('startOfMonth', () => {
let d0 = env.createMarker(new Date(Date.UTC(2018, 5, 5, 12)))
let d1 = env.toDate(env.startOfMonth(d0))
expect(d1).toEqual(
new Date(Date.UTC(2018, 5, 1)),
)
})
it('startOfWeek', () => {
let d0 = env.createMarker(new Date(Date.UTC(2018, 5, 5, 12)))
let d1 = env.toDate(env.startOfWeek(d0))
expect(d1).toEqual(
new Date(Date.UTC(2018, 5, 3)),
)
})
it('startOfDay', () => {
let d0 = env.createMarker(new Date(Date.UTC(2018, 5, 5, 12, 30)))
let d1 = env.toDate(startOfDay(d0))
expect(d1).toEqual(
new Date(Date.UTC(2018, 5, 5)),
)
})
describe('diffWholeYears', () => {
it('returns null if not whole', () => {
let d0 = new Date(Date.UTC(2018, 5, 5, 12, 0))
let d1 = new Date(Date.UTC(2020, 5, 5, 12, 30))
let diff = env.diffWholeYears(
env.createMarker(d0),
env.createMarker(d1),
)
expect(diff).toBe(null)
})
it('returns negative', () => {
let d0 = new Date(Date.UTC(2020, 5, 5, 12, 0))
let d1 = new Date(Date.UTC(2018, 5, 5, 12, 0))
let diff = env.diffWholeYears(
env.createMarker(d0),
env.createMarker(d1),
)
expect(diff).toBe(-2)
})
it('returns positive', () => {
let d0 = new Date(Date.UTC(2018, 5, 5, 12, 0))
let d1 = new Date(Date.UTC(2020, 5, 5, 12, 0))
let diff = env.diffWholeYears(
env.createMarker(d0),
env.createMarker(d1),
)
expect(diff).toBe(2)
})
})
describe('diffWholeMonths', () => {
it('returns null if not whole', () => {
let d0 = new Date(Date.UTC(2018, 5, 5))
let d1 = new Date(Date.UTC(2020, 5, 6))
let diff = env.diffWholeMonths(
env.createMarker(d0),
env.createMarker(d1),
)
expect(diff).toBe(null)
})
it('returns negative', () => {
let d0 = new Date(Date.UTC(2020, 9, 5))
let d1 = new Date(Date.UTC(2018, 5, 5))
let diff = env.diffWholeMonths(
env.createMarker(d0),
env.createMarker(d1),
)
expect(diff).toBe(-12 * 2 - 4)
})
it('returns positive', () => {
let d0 = new Date(Date.UTC(2018, 5, 5))
let d1 = new Date(Date.UTC(2020, 9, 5))
let diff = env.diffWholeMonths(
env.createMarker(d0),
env.createMarker(d1),
)
expect(diff).toBe(12 * 2 + 4)
})
})
describe('diffWholeWeeks', () => {
it('returns null if not whole', () => {
let d0 = new Date(Date.UTC(2018, 5, 5))
let d1 = new Date(Date.UTC(2018, 5, 20))
let diff = diffWholeWeeks(
env.createMarker(d0),
env.createMarker(d1),
)
expect(diff).toBe(null)
})
it('returns negative', () => {
let d0 = new Date(Date.UTC(2018, 5, 19))
let d1 = new Date(Date.UTC(2018, 5, 5))
let diff = diffWholeWeeks(
env.createMarker(d0),
env.createMarker(d1),
)
expect(diff).toBe(-2)
})
it('returns positive', () => {
let d0 = new Date(Date.UTC(2018, 5, 5))
let d1 = new Date(Date.UTC(2018, 5, 19))
let diff = diffWholeWeeks(
env.createMarker(d0),
env.createMarker(d1),
)
expect(diff).toBe(2)
})
})
describe('diffWholeDays', () => {
it('returns null if not whole', () => {
let d0 = new Date(Date.UTC(2018, 5, 5))
let d1 = new Date(Date.UTC(2018, 5, 19, 12))
let diff = diffWholeDays(
env.createMarker(d0),
env.createMarker(d1),
)
expect(diff).toBe(null)
})
it('returns negative', () => {
let d0 = new Date(Date.UTC(2018, 5, 19))
let d1 = new Date(Date.UTC(2018, 5, 5))
let diff = diffWholeDays(
env.createMarker(d0),
env.createMarker(d1),
)
expect(diff).toBe(-14)
})
it('returns positive', () => {
let d0 = new Date(Date.UTC(2018, 5, 5))
let d1 = new Date(Date.UTC(2018, 5, 19))
let diff = diffWholeDays(
env.createMarker(d0),
env.createMarker(d1),
)
expect(diff).toBe(14)
})
})
describe('diffDayAndTime', () => {
it('returns negative', () => {
let d0 = new Date(Date.UTC(2018, 5, 19, 12))
let d1 = new Date(Date.UTC(2018, 5, 5))
let diff = diffDayAndTime(
env.createMarker(d0),
env.createMarker(d1),
)
expect(diff).toEqual({
years: 0,
months: 0,
days: -14,
milliseconds: -12 * 60 * 60 * 1000,
})
})
it('returns positive', () => {
let d0 = new Date(Date.UTC(2018, 5, 5))
let d1 = new Date(Date.UTC(2018, 5, 19, 12))
let diff = diffDayAndTime(
env.createMarker(d0),
env.createMarker(d1),
)
expect(diff).toEqual({
years: 0,
months: 0,
days: 14,
milliseconds: 12 * 60 * 60 * 1000,
})
})
})
})
describe('when local', () => {
let env
beforeEach(() => {
env = new DateEnv({
timeZone: 'local',
calendarSystem: 'gregory',
locale: enLocale,
})
})
describe('ISO8601 parsing', () => {
it('parses non-tz as local', () => {
let res = env.createMarkerMeta('2018-06-08')
let date = env.toDate(res.marker)
expect(date).toEqual(new Date(2018, 5, 8))
expect(res.forcedTzo).toBeNull()
})
it('parses timezones into local', () => {
let res = env.createMarkerMeta('2018-06-08T00:00:00+12:00')
let date = env.toDate(res.marker)
expect(date).toEqual(new Date(Date.UTC(2018, 5, 7, 12)))
expect(res.forcedTzo).toBeNull()
})
it('does not lose info when parsing a dst-dead-zone date', () => {
let deadZone = getDSTDeadZone()
if (!deadZone) {
console.log('could not determine DST dead zone') // eslint-disable-line no-console
} else {
// use a utc date to get a ISO8601 string representation of the start of the dead zone
let utcDate = new Date(Date.UTC(
deadZone[1].getFullYear(),
deadZone[1].getMonth(),
deadZone[1].getDate(),
deadZone[1].getHours() - 1, // back one hour. shouldn't exist in local time
deadZone[1].getMinutes(),
deadZone[1].getSeconds(),
deadZone[1].getMilliseconds(),
))
let s = formatIsoWithoutTz(utcDate)
// check that the local date falls out of the dead zone
let localDate = new Date(s)
expect(localDate.getHours()).not.toBe(deadZone[1].getHours() - 1)
// check that is parsed and retained the original hour,
// even tho it falls into the dead zone for local time
let marker = env.createMarker(s)
expect(formatIsoWithoutTz(marker)).toBe(s)
// TODO
// // when it uses the env to format to local time,
// // it should have jumped out of the dead zone.
// expect(env.formatIso(marker)).not.toMatch(s)
}
})
})
it('outputs ISO8601 formatting', () => {
let marker = env.createMarker('2018-06-08T00:00:00')
let s = env.formatIso(marker)
let realTzo = formatIsoTimeZoneOffset(new Date(2018, 5, 8))
expect(s).toBe('2018-06-08T00:00:00' + realTzo)
})
it('outputs pretty format with local timezone', () => {
let marker = env.createMarker('2018-06-08')
let formatter = createFormatter({
weekday: 'long',
day: 'numeric',
month: 'long',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
timeZoneName: 'short',
omitCommas: true, // for cross-browser
})
let s = env.format(marker, formatter)
expect(s).toBe('Friday June 8 2018 12:00 AM ' + formatPrettyTimeZoneOffset(new Date(2018, 5, 8)))
})
it('can output a timezone only', () => {
let marker = env.createMarker('2018-06-08')
let formatter = createFormatter({ timeZoneName: 'short' })
let s = env.format(marker, formatter)
expect(s).toBe(formatPrettyTimeZoneOffset(new Date(2018, 5, 8)))
})
// because `new Date(year)` is error-prone
it('startOfYear', () => {
let d0 = env.createMarker(new Date(2018, 5, 5, 12))
let d1 = env.toDate(env.startOfYear(d0))
expect(d1).toEqual(
new Date(2018, 0, 1),
)
})
})
describe('when named timezone with coercion', () => {
let env
beforeEach(() => {
env = new DateEnv({
timeZone: 'America/Chicago',
calendarSystem: 'gregory',
locale: enLocale,
})
})
describe('ISO8601 parsing', () => {
it('parses non-tz as UTC with no forcedTzo', () => {
let res = env.createMarkerMeta('2018-06-08')
let date = env.toDate(res.marker)
expect(date).toEqual(new Date(Date.UTC(2018, 5, 8)))
expect(res.forcedTzo).toBeNull()
})
it('parses as UTC after stripping and with a forcedTzo', () => {
let res = env.createMarkerMeta('2018-06-08T00:00:00+12:00')
let date = env.toDate(res.marker)
expect(date).toEqual(new Date(Date.UTC(2018, 5, 8)))
expect(res.forcedTzo).toBe(12 * 60)
})
it('parses as UTC after stripping and with a forcedTzo, alt format', () => {
let res = env.createMarkerMeta('2018-06-08T01:01:01.100+1200')
let date = env.toDate(res.marker)
expect(date).toEqual(new Date(Date.UTC(2018, 5, 8, 1, 1, 1, 100)))
expect(res.forcedTzo).toBe(12 * 60)
})
})
it('outputs UTC timezone when no timezone specified', () => {
let marker = env.createMarker('2018-06-08')
let formatter = createFormatter({
weekday: 'long',
day: 'numeric',
month: 'long',
year: 'numeric',
timeZoneName: 'short',
omitCommas: true, // for cross-browser
})
let s = env.format(marker, formatter)
expect(s).toBe('Friday June 8 2018 12:00 AM UTC')
})
it('outputs UTC short timezone when no timezone specified, when requested as long', () => {
let marker = env.createMarker('2018-06-08')
let formatter = createFormatter({
weekday: 'long',
day: 'numeric',
month: 'long',
year: 'numeric',
timeZoneName: 'long',
omitCommas: true, // for cross-browser
})
let s = env.format(marker, formatter)
expect(s).toBe('Friday June 8 2018 12:00 AM UTC')
})
it('computes current date as local values', () => {
let marker = env.createNowMarker()
let localDate = new Date()
expect(marker.getUTCFullYear()).toBe(localDate.getFullYear())
expect(marker.getUTCMonth()).toBe(localDate.getMonth())
expect(marker.getUTCDate()).toBe(localDate.getDate())
expect(marker.getUTCHours()).toBe(localDate.getHours())
expect(marker.getUTCMinutes()).toBe(localDate.getMinutes())
expect(marker.getUTCSeconds()).toBe(localDate.getSeconds())
})
})
describe('duration parsing', () => {
it('accepts whole day in string', () => {
let dur = createDuration('2.00:00:00')
expect(dur).toEqual({
years: 0,
months: 0,
days: 2,
milliseconds: 0,
})
})
it('accepts hours, minutes, seconds, and milliseconds', () => {
let dur = createDuration('01:02:03.500')
expect(dur).toEqual({
years: 0,
months: 0,
days: 0,
milliseconds:
1 * 60 * 60 * 1000 +
2 * 60 * 1000 +
3 * 1000 +
500,
})
})
it('accepts just hours and minutes', () => {
let dur = createDuration('01:02')
expect(dur).toEqual({
years: 0,
months: 0,
days: 0,
milliseconds:
1 * 60 * 60 * 1000 +
2 * 60 * 1000,
})
})
})
}) | the_stack |
import * as path from "path";
import * as openapiToolsCommon from "@azure-tools/openapi-tools-common";
import { Suppression } from "@azure/openapi-markdown";
import * as jsonPointer from "json-pointer";
import * as _ from "lodash";
import {
DefinitionsObject,
OperationObject,
ParameterObject,
ParametersDefinitionsObject,
PathsObject,
SchemaObject,
SwaggerObject,
} from "yasway";
import * as C from "../util/constants";
import { defaultIfUndefinedOrNull } from "../util/defaultIfUndefinedOrNull";
import { DocCache } from "../util/documents";
import * as jsonRefs from "../util/jsonRefs";
import * as jsonUtils from "../util/jsonUtils";
import { log } from "../util/logging";
import { getOperations } from "../util/methods";
import * as utils from "../util/utils";
import { PolymorphicTree } from "./polymorphicTree";
import { resolveNestedDefinitions } from "./resolveNestedDefinitions";
const ErrorCodes = C.ErrorCodes;
export interface Options {
consoleLogLevel?: unknown;
shouldResolveRelativePaths?: boolean | null;
shouldResolveXmsExamples?: boolean | null;
shouldResolveAllOf?: boolean;
shouldSetAdditionalPropertiesFalse?: boolean;
shouldResolvePureObjects?: boolean | null;
shouldResolveDiscriminator?: boolean;
shouldResolveParameterizedHost?: boolean | null;
shouldResolveNullableTypes?: boolean;
}
export interface RefDetails {
def: {
$ref: string;
};
}
/**
* @class
* Resolves the swagger spec by unifying x-ms-paths, resolving relative file references if any,
* resolving the allOf is present in any model definition and then setting additionalProperties
* to false if it is not previously set to true or an object in that definition.
*/
export class SpecResolver {
public specInJson: SwaggerObject;
private readonly specPath: string;
private readonly specDir: unknown;
private readonly visitedEntities: openapiToolsCommon.MutableStringMap<SchemaObject> = {};
private readonly resolvedAllOfModels: openapiToolsCommon.MutableStringMap<SchemaObject> = {};
private readonly options: Options;
/**
* @constructor
* Initializes a new instance of the SpecResolver class.
*
* @param {string} specPath the (remote|local) swagger spec path
*
* @param {object} specInJson the parsed spec in json format
*
* @param {object} [options] The options object
*
* @param {object} [options.shouldResolveRelativePaths] Should relative paths be resolved?
* Default: true
*
* @param {object} [options.shouldResolveXmsExamples] Should x-ms-examples be resolved?
* Default: true. If options.shouldResolveRelativePaths is false then this option will also be
* false implicitly and cannot be overridden.
*
* @param {object} [options.shouldResolveAllOf] Should allOf references be resolved? Default: true
*
* @param {object} [options.shouldResolveDiscriminator] Should discriminator be resolved?
* Default: true
*
* @param {object} [options.shouldSetAdditionalPropertiesFalse] Should additionalProperties be set
* to false? Default: true
*
* @param {object} [options.shouldResolvePureObjects] Should pure objects be resolved?
* Default: true
*
* @param {object} [options.shouldResolveParameterizedHost] Should x-ms-parameterized-host be
* resolved? Default: true
*
* @param {object} [options.shouldResolveNullableTypes] Should we allow null values to match any
* type? Default: true
*/
public constructor(
specPath: string,
specInJson: SwaggerObject,
options: Options,
private readonly reportError: openapiToolsCommon.ReportError,
private readonly docsCache: DocCache = {}
) {
if (
specPath === null ||
specPath === undefined ||
typeof specPath !== "string" ||
!specPath.trim().length
) {
throw new Error(
"specPath is a required property of type string and it cannot be an empty string."
);
}
if (specInJson === null || specInJson === undefined || typeof specInJson !== "object") {
throw new Error("specInJson is a required property of type object");
}
this.specInJson = specInJson;
this.specPath = specPath;
this.specDir = path.dirname(this.specPath);
options = defaultIfUndefinedOrNull<Options>(options, {});
options.shouldResolveRelativePaths = defaultIfUndefinedOrNull(
options.shouldResolveRelativePaths,
true
);
options.shouldResolveXmsExamples = defaultIfUndefinedOrNull(
options.shouldResolveXmsExamples,
true
);
if (options.shouldResolveAllOf === null || options.shouldResolveAllOf === undefined) {
if (!_.isUndefined(specInJson.definitions)) {
options.shouldResolveAllOf = true;
}
}
// Resolving allOf is a necessary precondition for resolving discriminators. Hence hard setting
// this to true
if (options.shouldResolveDiscriminator) {
options.shouldResolveAllOf = true;
}
options.shouldSetAdditionalPropertiesFalse = defaultIfUndefinedOrNull(
options.shouldSetAdditionalPropertiesFalse,
options.shouldResolveAllOf
);
options.shouldResolvePureObjects = defaultIfUndefinedOrNull(
options.shouldResolvePureObjects,
true
);
options.shouldResolveDiscriminator = defaultIfUndefinedOrNull(
options.shouldResolveDiscriminator,
options.shouldResolveAllOf
);
options.shouldResolveParameterizedHost = defaultIfUndefinedOrNull(
options.shouldResolveParameterizedHost,
true
);
options.shouldResolveNullableTypes = defaultIfUndefinedOrNull(
options.shouldResolveNullableTypes,
options.shouldResolveAllOf
);
this.options = options;
}
/**
* Resolves the swagger spec by unifying x-ms-paths, resolving relative file references if any,
* resolving the allOf is present in any model definition and then setting additionalProperties
* to false if it is not previously set to true or an object in that definition.
*/
public async resolve(suppression: Suppression | undefined): Promise<this> {
try {
// path resolvers
this.verifyInternalReference();
this.unifyXmsPaths();
if (this.options.shouldResolveRelativePaths) {
await this.resolveRelativePaths(suppression);
}
// resolve nested definitions
this.specInJson = resolveNestedDefinitions(this.specInJson);
// other resolvers (should be moved to resolveNestedDefinitions())
if (this.options.shouldResolveAllOf) {
this.resolveAllOfInDefinitions();
}
if (this.options.shouldResolveDiscriminator) {
this.resolveDiscriminator();
}
if (this.options.shouldResolveAllOf) {
this.deleteReferencesToAllOf();
}
if (this.options.shouldSetAdditionalPropertiesFalse) {
this.setAdditionalPropertiesFalse();
}
if (this.options.shouldResolveParameterizedHost) {
this.resolveParameterizedHost();
}
if (this.options.shouldResolvePureObjects) {
this.resolvePureObjects();
}
if (this.options.shouldResolveNullableTypes) {
this.resolveNullableTypes();
}
} catch (err) {
// to avoid double wrap the exception
if (typeof err === "object" && err.id && err.message) {
throw err;
}
const e = {
message: `internal error: ${err.message}`,
code: ErrorCodes.InternalError.name,
id: ErrorCodes.InternalError.id,
innerErrors: [err],
};
log.error(err);
throw e;
}
return this;
}
/**
* Resolves the references to relative paths in the provided object.
*
* @param {object} [doc] the json doc that contains relative references. Default: self.specInJson
* (current swagger spec).
*
* @param {string} [docPath] the absolute (local|remote) path of the doc Default: self.specPath
* (current swagger spec path).
*
* @param {string} [filterType] the type of paths to filter. By default the method will resolve
* 'relative' and 'remote' references.
* If provided the value should be 'all'. This indicates that 'local' references should also be
* resolved apart from the default ones.
*
* @return {Promise<void>}
*/
private async resolveRelativePaths(
suppression: Suppression | undefined,
doc?: openapiToolsCommon.StringMap<unknown>,
docPath?: string,
filterType?: string
): Promise<void> {
let docDir;
const options = {
/* TODO: it looks like a bug, relativeBase is always undefined */
relativeBase: docDir,
filter: ["relative", "remote"],
};
if (!doc) {
doc = this.specInJson;
}
if (!docPath) {
docPath = this.specPath;
docDir = this.specDir;
}
if (!docDir) {
docDir = path.dirname(docPath);
}
if (filterType === "all") {
delete options.filter;
}
const allRefsRemoteRelative = jsonRefs.findRefs(doc, options);
const e = openapiToolsCommon.mapEntries(
allRefsRemoteRelative as openapiToolsCommon.StringMap<RefDetails>
);
const promiseFactories = e
.map((ref) => async () => {
const [refName, refDetails] = ref;
return this.resolveRelativeReference(refName, refDetails, doc, docPath, suppression);
})
.toArray();
if (promiseFactories.length) {
await utils.executePromisesSequentially(promiseFactories);
}
}
/**
* Merges the x-ms-paths object into the paths object in swagger spec. The method assumes that the
* paths present in "x-ms-paths" and "paths" are unique. Hence it does a simple union.
*/
private unifyXmsPaths(): void {
// unify x-ms-paths into paths
const xmsPaths = this.specInJson["x-ms-paths"];
const paths = this.specInJson.paths as PathsObject;
if (
xmsPaths &&
xmsPaths instanceof Object &&
openapiToolsCommon.toArray(openapiToolsCommon.keys(xmsPaths)).length > 0
) {
for (const [property, v] of openapiToolsCommon.mapEntries(xmsPaths)) {
paths[property] = v;
}
this.specInJson.paths = utils.mergeObjects(xmsPaths, paths);
}
}
/**
* Resolves the relative reference in the provided object. If the object to be resolved contains
* more relative references then this method will call resolveRelativePaths
*
* @param refName the reference name/location that has a relative reference
*
* @param refDetails the value or the object that the refName points at
*
* @param doc the doc in which the refName exists
*
* @param docPath the absolute (local|remote) path of the doc
*
* @return undefined the modified object
*/
private async resolveRelativeReference(
refName: string,
refDetails: RefDetails,
doc: unknown,
docPath: string | undefined,
suppression: Suppression | undefined
): Promise<void> {
if (!refName || (refName && typeof refName.valueOf() !== "string")) {
throw new Error('refName cannot be null or undefined and must be of type "string".');
}
if (!refDetails || (refDetails && !(refDetails instanceof Object))) {
throw new Error('refDetails cannot be null or undefined and must be of type "object".');
}
if (!doc || (doc && !(doc instanceof Object))) {
throw new Error('doc cannot be null or undefined and must be of type "object".');
}
if (!docPath || (docPath && typeof docPath.valueOf() !== "string")) {
throw new Error('docPath cannot be null or undefined and must be of type "string".');
}
const node = refDetails.def;
const slicedRefName = refName.slice(1);
const reference = node.$ref;
const parsedReference = utils.parseReferenceInSwagger(reference);
const docDir = path.dirname(docPath);
if (parsedReference.filePath) {
const regexFilePath = new RegExp("^[.\\w\\\\\\/].*.[A-Za-z]+$");
if (!regexFilePath.test(parsedReference.filePath)) {
throw new Error(`${node.$ref} isn't a valid local reference file.`);
}
// assuming that everything in the spec is relative to it, let us join the spec directory
// and the file path in reference.
docPath = utils.joinPath(docDir, parsedReference.filePath);
}
if (parsedReference.localReference) {
await this.resolveLocalReference(
slicedRefName,
doc,
docPath,
node,
parsedReference.localReference,
suppression
);
} else {
// Since there is no local reference we will replace the key in the object with the parsed
// json (relative) file it is referring to.
await this.resolveRemoteReference(slicedRefName, doc, docPath, suppression);
}
}
/**
* Resolves references local to the file.
*/
private async resolveLocalReference(
slicedRefName: string,
doc: unknown,
docPath: string,
node: { $ref: string },
localReference: utils.LocalReference,
suppression: Suppression | undefined
) {
// resolve the local reference.
// make the reference local to the doc being processed
const result = await jsonUtils.parseJson(
suppression,
docPath,
this.reportError,
this.docsCache
);
node.$ref = localReference.value;
// TODO: doc should have a type
utils.setObject(doc as any, slicedRefName, node);
const slicedLocalReferenceValue = localReference.value.slice(1);
let referencedObj = this.visitedEntities[slicedLocalReferenceValue];
if (!referencedObj) {
// We get the definition/parameter from the relative file and then add it (make it local)
// to the doc (i.e. self.specInJson) being processed.
referencedObj = utils.getObject(result, slicedLocalReferenceValue) as SchemaObject;
utils.setObject(this.specInJson, slicedLocalReferenceValue, referencedObj);
this.visitedEntities[slicedLocalReferenceValue] = referencedObj;
await this.resolveRelativePaths(suppression, referencedObj, docPath, "all");
// After resolving a model definition, if there are models that have an allOf on that model
// definition.
// It may be possible that those models are not being referenced anywhere. Hence, we must
// ensure that they are consumed as well. Example model "CopyActivity" in file
// arm-datafactory/2017-03-01-preview/swagger/entityTypes/Pipeline.json is having an allOf
// on model "Activity". Spec "datafactory.json" has references to "Activity" in
// Pipeline.json but there are no references to "CopyActivity". The following code, ensures
// that we do not forget such models while resolving relative swaggers.
if (result && result.definitions) {
const definitions = result.definitions;
const unresolvedDefinitions: Array<() => Promise<void>> = [];
const processDefinition = (defEntry: openapiToolsCommon.MapEntry<SchemaObject>) => {
const defName = defEntry[0];
const def = defEntry[1];
unresolvedDefinitions.push(async () => {
const allOf = def.allOf;
if (allOf) {
const matchFound = allOf.some(() => !this.visitedEntities[`/definitions/${defName}`]);
if (matchFound) {
const slicedDefinitionRef = `/definitions/${defName}`;
const definitionObj = definitions[defName];
utils.setObject(this.specInJson, slicedDefinitionRef, definitionObj);
this.visitedEntities[slicedDefinitionRef] = definitionObj;
await this.resolveRelativePaths(suppression, definitionObj, docPath, "all");
}
}
});
};
for (const entry of openapiToolsCommon.mapEntries(result.definitions)) {
processDefinition(entry);
}
await utils.executePromisesSequentially(unresolvedDefinitions);
}
}
}
/**
* Resolves remote references for the document
*/
private async resolveRemoteReference(
slicedRefName: string,
doc: unknown,
docPath: string,
suppression: Suppression | undefined
) {
const regex = /.*x-ms-examples.*/gi;
if (this.options.shouldResolveXmsExamples || slicedRefName.match(regex) === null) {
const result = await jsonUtils.parseJson(
suppression,
docPath,
this.reportError,
this.docsCache
);
const resultWithReferenceDocPath: any = result;
resultWithReferenceDocPath.docPath = docPath;
// We set a function `() => result` instead of an object `result` to avoid
// reference resolution in the examples.
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
utils.setObject(doc as any, slicedRefName, () => resultWithReferenceDocPath);
} else {
if (jsonPointer.has(doc as any, slicedRefName)) {
jsonPointer.remove(doc as any, slicedRefName);
}
}
}
/**
* Resolves the "allOf" array present in swagger model definitions by composing all the properties
* of the parent model into the child model.
*/
private resolveAllOfInDefinitions(): void {
const spec = this.specInJson;
const definitions = spec.definitions as DefinitionsObject;
for (const [modelName, model] of openapiToolsCommon.mapEntries(definitions)) {
const modelRef = "/definitions/" + modelName;
this.resolveAllOfInModel(model, modelRef);
}
}
/**
* Resolves the "allOf" array present in swagger model definitions by composing all the properties
* of the parent model into the child model.
*/
private resolveAllOfInModel(model: SchemaObject, modelRef: string | undefined) {
const spec = this.specInJson;
if (!model || (model && typeof model !== "object")) {
throw new Error(`model cannot be null or undefined and must of type "object".`);
}
if (!modelRef || (modelRef && typeof modelRef.valueOf() !== "string")) {
throw new Error(`model cannot be null or undefined and must of type "string".`);
}
if (modelRef.startsWith("#")) {
modelRef = modelRef.slice(1);
}
if (!this.resolvedAllOfModels[modelRef]) {
if (model && model.allOf) {
model.allOf.forEach((item) => {
const ref = item.$ref;
const slicedRef = ref ? ref.slice(1) : undefined;
const referencedModel =
slicedRef === undefined ? item : (utils.getObject(spec, slicedRef) as SchemaObject);
if (referencedModel.allOf) {
this.resolveAllOfInModel(referencedModel, slicedRef);
}
model = this.mergeParentAllOfInChild(referencedModel, model);
this.resolvedAllOfModels[slicedRef as string] = referencedModel;
});
} else {
this.resolvedAllOfModels[modelRef] = model;
return model;
}
}
return undefined;
}
/**
* Merges the properties of the parent model into the child model.
*
* @param {object} parent object to be merged. Example: "Resource".
*
* @param {object} child object to be merged. Example: "Storage".
*
* @return {object} returns the merged child object
*/
private mergeParentAllOfInChild(parent: SchemaObject, child: SchemaObject): SchemaObject {
if (!parent || (parent && typeof parent !== "object")) {
throw new Error(`parent must be of type "object".`);
}
if (!child || (child && typeof child !== "object")) {
throw new Error(`child must be of type "object".`);
}
// merge the parent (Resource) model's properties into the properties
// of the child (StorageAccount) model.
if (!parent.properties) {
parent.properties = {};
}
if (!child.properties) {
child.properties = {};
}
child.properties = utils.mergeObjects(parent.properties, child.properties);
// merge the array of required properties
if (parent.required) {
if (!child.required) {
child.required = [];
}
child.required = [...new Set([...parent.required, ...child.required])];
}
// merge x-ms-azure-resource
if (parent["x-ms-azure-resource"]) {
child["x-ms-azure-resource"] = parent["x-ms-azure-resource"];
}
return child;
}
/**
* Deletes all the references to allOf from all the model definitions in the swagger spec.
*/
private deleteReferencesToAllOf(): void {
const spec = this.specInJson;
const definitions = spec.definitions as DefinitionsObject;
for (const model of openapiToolsCommon.values(definitions)) {
if (model.allOf) {
delete model.allOf;
}
}
}
/**
* Sets additionalProperties to false if additionalProperties is not defined.
*/
private setAdditionalPropertiesFalse(): void {
const spec = this.specInJson;
const definitions = spec.definitions as DefinitionsObject;
for (const model of openapiToolsCommon.values(definitions)) {
if (
!model.additionalProperties &&
!(
!model.properties ||
(model.properties &&
openapiToolsCommon.toArray(openapiToolsCommon.keys(model.properties)).length === 0)
)
) {
model.additionalProperties = false;
}
}
}
/**
* Resolves the parameters provided in 'x-ms-parameterized-host'
* extension by adding those parameters as local parameters to every operation.
*
* ModelValidation:
* This step should only be performed for model validation as we need to
* make sure that the examples contain correct values for parameters
* defined in 'x-ms-parameterized-host'.hostTemplate. Moreover, they are a
* part of the baseUrl.
*
* SemanticValidation:
* This step should not be performed for semantic validation, otherwise there will
* be a mismatch between the number of path parameters provided in the operation
* definition and the number of parameters actually present in the path template.
*/
private resolveParameterizedHost(): void {
const spec = this.specInJson;
const parameterizedHost = spec[C.xmsParameterizedHost];
const hostParameters = parameterizedHost ? parameterizedHost.parameters : null;
if (parameterizedHost && hostParameters) {
const paths = spec.paths;
for (const verbs of openapiToolsCommon.values(paths)) {
for (const operation of getOperations(verbs)) {
let operationParameters = operation.parameters;
if (!operationParameters) {
operationParameters = [];
}
// merge host parameters into parameters for that operation.
operation.parameters = operationParameters.concat(hostParameters);
}
}
}
}
/**
* Resolves entities (parameters, definitions, model properties, etc.) in the spec that are true
* objects.
* i.e `"type": "object"` and `"properties": {}` or `"properties"` is absent or the entity has
* "additionalProperties": { "type": "object" }.
*/
private resolvePureObjects(): void {
const spec = this.specInJson;
const definitions = spec.definitions;
// scan definitions and properties of every model in definitions
for (const model of openapiToolsCommon.values(definitions)) {
utils.relaxModelLikeEntities(model);
}
const resolveOperation = (operation: OperationObject) => {
// scan every parameter in the operation
const consumes = _.isUndefined(operation.consumes)
? _.isUndefined(spec.consumes)
? ["application/json"]
: spec.consumes
: operation.consumes;
const produces = _.isUndefined(operation.produces)
? _.isUndefined(spec.produces)
? ["application/json"]
: spec.produces
: operation.produces;
const octetStream = (elements: string[]) =>
elements.some((e) => e.toLowerCase() === "application/octet-stream");
const resolveParameter2 = (param: ParameterObject) => {
if (param.in && param.in === "body" && param.schema && !octetStream(consumes)) {
param.schema = utils.relaxModelLikeEntities(param.schema);
} else {
param = utils.relaxEntityType(param, param.required);
}
};
if (operation.parameters) {
operation.parameters.forEach(resolveParameter2);
}
// scan every response in the operation
for (const response of openapiToolsCommon.values(operation.responses)) {
if (response.schema && !octetStream(produces) && response.schema.type !== "file") {
response.schema = utils.relaxModelLikeEntities(response.schema);
}
}
};
const resolveParameter = (param: ParameterObject) => {
if (param.in && param.in === "body" && param.schema) {
param.schema = utils.relaxModelLikeEntities(param.schema);
} else {
param = utils.relaxEntityType(param, param.required);
}
};
// scan every operation
for (const pathObj of openapiToolsCommon.values(spec.paths)) {
for (const operation of getOperations(pathObj)) {
resolveOperation(operation);
}
// scan path level parameters if any
if (pathObj.parameters) {
pathObj.parameters.forEach(resolveParameter);
}
}
// scan global parameters
const parameters = spec.parameters as ParametersDefinitionsObject;
for (const [paramName, parameter] of openapiToolsCommon.mapEntries(parameters)) {
if (parameter.in && parameter.in === "body" && parameter.schema) {
parameter.schema = utils.relaxModelLikeEntities(parameter.schema);
}
parameters[paramName] = utils.relaxEntityType(parameter, parameter.required);
}
}
/**
* Resolves the discriminator by replacing all the references to the parent model with a oneOf
* array containing
* references to the parent model and all its child models. It also modifies the discriminator
* property in
* the child models by making it a constant (enum with one value) with the value expected for that
* model
* type on the wire.
* For example: There is a model named "Animal" with a discriminator as "animalType". Models like
* "Cat", "Dog",
* "Tiger" are children (having "allof": [ { "$ref": "#/definitions/Animal" } ] on) of "Animal" in
* the swagger spec.
*
* - This method will replace all the locations in the swagger spec that have a reference to the
* parent model "Animal" ("$ref": "#/definitions/Animal") except the allOf reference with a oneOf
* reference
* "oneOf": [ { "$ref": "#/definitions/Animal" }, { "$ref": "#/definitions/Cat" }, { "$ref":
* "#/definitions/Dog" }, { "$ref": "#/definitions/Tiger" } ]
*
* - It will also add a constant value (name of that animal on the wire or the value provided by
* "x-ms-discriminator-value")
* to the discrimiantor property "animalType" for each of the child models.
* For example: the Cat model's discriminator property will look like:
* "Cat": { "required": [ "animalType" ], "properties": { "animalType": { "type": "string",
* "enum": [ "Cat" ] }, . . } }.
*/
private resolveDiscriminator(): void {
const spec = this.specInJson;
const definitions = spec.definitions as DefinitionsObject;
const subTreeMap = new Map();
const references = jsonRefs.findRefs(spec);
for (const modelEntry of openapiToolsCommon.mapEntries(definitions)) {
const modelName = modelEntry[0];
const model = modelEntry[1];
const discriminator = model.discriminator;
if (discriminator) {
let rootNode = subTreeMap.get(modelName);
if (!rootNode) {
rootNode = this.createPolymorphicTree(modelName, discriminator, subTreeMap);
}
this.updateReferencesWithOneOf(subTreeMap, references);
}
}
}
/**
* Resolves all properties in models or responses that have a "type" defined, so that if the
* property
* is marked with "x-nullable", we'd honor it: we'd relax the type to include "null" if value is
* true, we won't if value is false.
* If the property does not have the "x-nullable" extension, then if not required, we'll relax
* the type to include "null"; if required we won't.
* The way we're relaxing the type is to have the model be a "oneOf" array with one value being
* the original content of the model and the second value "type": "null".
*/
private resolveNullableTypes(): void {
const spec = this.specInJson;
const definitions = spec.definitions as DefinitionsObject;
// scan definitions and properties of every model in definitions
for (const defEntry of openapiToolsCommon.mapEntries(definitions)) {
const defName = defEntry[0];
const model = defEntry[1];
definitions[defName] = utils.allowNullableTypes(model);
}
// scan every operation response
for (const pathObj of openapiToolsCommon.values(spec.paths)) {
// need to handle parameters at this level
if (pathObj.parameters) {
pathObj.parameters = openapiToolsCommon.arrayMap(
pathObj.parameters,
utils.allowNullableParams
);
}
for (const operation of getOperations(pathObj)) {
// need to account for parameters, except for path parameters
if (operation.parameters) {
operation.parameters = openapiToolsCommon.arrayMap(
operation.parameters,
utils.allowNullableParams
);
}
// going through responses
for (const response of openapiToolsCommon.values(operation.responses)) {
if (response.schema && response.schema.type !== "file") {
response.schema = utils.allowNullableTypes(response.schema);
}
}
}
}
// scan parameter definitions
const parameters = spec.parameters as ParametersDefinitionsObject;
for (const [parameterName, parameter] of openapiToolsCommon.mapEntries(parameters)) {
parameters[parameterName] = utils.allowNullableParams(parameter);
}
}
/**
* Updates the reference to a parent node with a oneOf array containing a reference to the parent
* and all its children.
*
* @param {Map<string, PolymorphicTree>} subTreeMap - A map containing a reference to a node in
* the PolymorphicTree.
* @param {object} references - This object is the output of findRefs function from "json-refs"
* library. Please refer
* to the documentation of json-refs over
* [here](https://bit.ly/2sw5MOa)
* for detailed structure of the object.
*/
private updateReferencesWithOneOf(
subTreeMap: Map<string, PolymorphicTree>,
references: openapiToolsCommon.StringMap<jsonRefs.UnresolvedRefDetails>
): void {
const spec = this.specInJson;
for (const node of subTreeMap.values()) {
// Have to process all the non-leaf nodes only
if (node.children.size > 0) {
const locationsToBeUpdated = [];
const modelReference = `#/definitions/${node.name}`;
// Create a list of all the locations where the current node is referenced
for (const [key, value] of openapiToolsCommon.mapEntries(references)) {
if (
value.uri === modelReference &&
key.indexOf("allOf") === -1 &&
key.indexOf("oneOf") === -1
) {
locationsToBeUpdated.push(key);
}
}
// Replace the reference to that node in that location with a oneOf array
// containing reference to the node and all its children.
for (const location of locationsToBeUpdated) {
const slicedLocation = location.slice(1);
const obj = utils.getObject(spec, slicedLocation) as any;
if (obj) {
if (obj.$ref) {
delete obj.$ref;
}
obj.oneOf = [...this.buildOneOfReferences(node)];
utils.setObject(spec, slicedLocation, obj);
}
}
}
}
}
/**
* Creates a PolymorphicTree for a given model in the inheritance chain
*
* @param {string} name- Name of the model for which the tree needs to be created.
* @param {string} discriminator- Name of the property that is marked as the discriminator.
* @param {Map<string, PolymorphicTree>} subTreeMap- A map that stores a reference to
* PolymorphicTree for a given model in the inheritance chain.
* @returns {PolymorphicTree} rootNode- A PolymorphicTree that represents the model in the
* inheritance chain.
*/
private createPolymorphicTree(
name: string,
discriminator: string,
subTreeMap: Map<string, PolymorphicTree>
): PolymorphicTree {
if (
name === null ||
name === undefined ||
typeof name.valueOf() !== "string" ||
!name.trim().length
) {
throw new Error(
"name is a required property of type string and it cannot be an empty string."
);
}
if (
discriminator === null ||
discriminator === undefined ||
typeof discriminator.valueOf() !== "string" ||
!discriminator.trim().length
) {
throw new Error(
"discriminator is a required property of type string and it cannot be an empty string."
);
}
if (subTreeMap === null || subTreeMap === undefined || !(subTreeMap instanceof Map)) {
throw new Error("subTreeMap is a required property of type Map.");
}
const rootNode = new PolymorphicTree(name);
const definitions = this.specInJson.definitions as DefinitionsObject;
// Adding the model name or it's discriminator value as an enum constraint with one value
// (constant) on property marked as discriminator
const definition = definitions[name];
if (definition && definition.properties) {
// all derived types should have `"type": "object"`.
// otherwise it may pass validation for other types, such as `string`.
// see also https://github.com/Azure/oav/issues/390
definition.type = "object";
const d = definition.properties[discriminator];
if (d) {
const required = definition.required;
if (!openapiToolsCommon.isArray(required)) {
definition.required = [discriminator];
} else if (required.find((v) => v === discriminator) === undefined) {
definition.required = [...required, discriminator];
}
const val = definition["x-ms-discriminator-value"] || name;
// Ensure that the property marked as a discriminator has only one value in the enum
// constraint for that model and it
// should be the one that is the model name or the value indicated by
// x-ms-discriminator-value. This will make the discriminator
// property a constant (in json schema terms).
if (d.$ref) {
// When the discriminator enum is null and point to the nested reference,
// we need to set discriminator enum value to the nested reference enum
if (!d.enum) {
const refDefinition = definitions[d.$ref.substring(d.$ref.lastIndexOf("/") + 1)];
if (refDefinition) {
d.enum = refDefinition.enum;
}
}
delete d.$ref;
}
const xMsEnum = d["x-ms-enum"];
if (xMsEnum !== undefined) {
// if modelAsString is set to `true` then validator will always succeeded on any string.
// Because of this, we have to set it to `false`.
openapiToolsCommon.asMutable(xMsEnum).modelAsString = false;
}
// We will set "type" to "string". It is safe to assume that properties marked as
// "discriminator" will be of type "string"
// as it needs to refer to a model definition name. Model name would be a key in the
// definitions object/dictionary in the
// swagger spec. keys would always be a string in a JSON object/dictionary.
if (!d.type) {
d.type = "string";
}
// For base class model, set the discriminator value to the base class name plus the origin enum values
if (definition.discriminator && d.enum) {
const baseClassDiscriminatorValue = d.enum;
if (d.enum.indexOf(val) === -1) {
d.enum = [`${val}`, ...baseClassDiscriminatorValue];
}
} else {
d.enum = [`${val}`];
}
}
}
const children = this.findChildren(name);
for (const childName of children) {
const childObj = this.createPolymorphicTree(childName, discriminator, subTreeMap);
rootNode.addChildByObject(childObj);
}
// Adding the created sub tree in the subTreeMap for future use.
subTreeMap.set(rootNode.name, rootNode);
return rootNode;
}
/**
* Finds children of a given model in the inheritance chain.
*
* @param {string} name- Name of the model for which the children need to be found.
* @returns {Set} result- A set of model names that are the children of the given model in the
* inheritance chain.
*/
private findChildren(name: string): Set<string> {
if (
name === null ||
name === undefined ||
typeof name.valueOf() !== "string" ||
!name.trim().length
) {
throw new Error(
"name is a required property of type string and it cannot be an empty string."
);
}
const definitions = this.specInJson.definitions as DefinitionsObject;
const reference = `#/definitions/${name}`;
const result = new Set<string>();
const findReferences = (definitionName: string) => {
const definition = definitions[definitionName];
if (definition && definition.allOf) {
definition.allOf.forEach((item) => {
// TODO: What if there is an inline definition instead of $ref
if (item.$ref && item.$ref === reference) {
log.debug(`reference found: ${reference} in definition: ${definitionName}`);
result.add(definitionName);
}
});
}
};
for (const definitionName of openapiToolsCommon.keys(definitions)) {
findReferences(definitionName);
}
return result;
}
/**
* Builds the oneOf array of references that comprise of the parent and its children.
*
* @param {PolymorphicTree} rootNode- A PolymorphicTree that represents the model in the
* inheritance chain.
* @returns {PolymorphicTree} An array of reference objects that comprise of the
* parent and its children.
*/
private buildOneOfReferences(rootNode: PolymorphicTree): Set<SchemaObject> {
let result = new Set<SchemaObject>();
result.add({ $ref: `#/definitions/${rootNode.name}` });
for (const enObj of rootNode.children.values()) {
if (enObj) {
result = new Set([...result, ...this.buildOneOfReferences(enObj)]);
}
}
return result;
}
/**
* Check if exist undefined within-document reference
*/
private verifyInternalReference() {
const errsDetail: any[] = [];
const unresolvedRefs = jsonUtils.findUndefinedWithinDocRefs(this.specInJson);
unresolvedRefs.forEach((pathStr, ref) => {
const err: any = {};
err.path = pathStr.join(".");
err.message = `JSON Pointer points to missing location:${ref}`;
errsDetail.push(err);
});
if (errsDetail.length) {
const err: any = C.ErrorCodes.RefNotFoundError;
err.message = "Reference could not be resolved";
err.innerErrors = errsDetail;
throw err;
}
}
} | the_stack |
import isEqual from 'lodash/isEqual';
import { Injectable, Autowired, INJECTOR_TOKEN, Injector } from '@opensumi/di';
import {
TreeModel,
DecorationsManager,
Decoration,
IRecycleTreeHandle,
TreeNodeType,
TreeNodeEvent,
} from '@opensumi/ide-components';
import {
Emitter,
ThrottledDelayer,
Deferred,
Event,
DisposableCollection,
IClipboardService,
} from '@opensumi/ide-core-browser';
import { AbstractContextMenuService, MenuId, ICtxMenuRenderer } from '@opensumi/ide-core-browser/lib/menu/next';
import { DebugProtocol } from '@opensumi/vscode-debugprotocol';
import { DebugSession } from '../../debug-session';
import {
ExpressionContainer,
ExpressionNode,
DebugVariableRoot,
DebugVariableContainer,
DebugVariable,
DebugScope,
} from '../../tree/debug-tree-node.define';
import { DebugViewModel } from '../debug-view-model';
import { DebugContextKey } from './../../contextkeys/debug-contextkey.service';
import { DebugVariablesModel } from './debug-variables-model';
import styles from './debug-variables.module.less';
export interface IDebugVariablesHandle extends IRecycleTreeHandle {
hasDirectFocus: () => boolean;
}
export type DebugVariableWithRawScope = DebugScope | DebugVariableContainer;
class KeepExpandedScopesModel {
private _keepExpandedScopesMap = new Map<DebugProtocol.Scope, Array<number>>();
constructor() {}
private getMirrorScope(item: DebugVariableWithRawScope) {
return Array.from(this._keepExpandedScopesMap.keys()).find((f) => isEqual(f, item.getRawScope()));
}
set(item: DebugVariableWithRawScope): void {
const scope = item.getRawScope();
if (scope) {
const keepScope = this.getMirrorScope(item);
if (keepScope) {
const kScopeVars = this._keepExpandedScopesMap.get(keepScope)!;
let nScopeVars: number[];
if (item.expanded) {
nScopeVars = Array.from(new Set([...kScopeVars, item.variablesReference]));
} else {
nScopeVars = kScopeVars.filter((v) => v !== item.variablesReference);
}
this._keepExpandedScopesMap.set(keepScope, nScopeVars);
} else {
this._keepExpandedScopesMap.set(scope, item.expanded ? [item.variablesReference] : []);
}
}
}
get(item: DebugVariableWithRawScope): number[] {
const keepScope = this.getMirrorScope(item);
if (keepScope) {
return this._keepExpandedScopesMap.get(keepScope) || [];
} else {
return [];
}
}
clear(): void {
this._keepExpandedScopesMap.clear();
}
}
@Injectable()
export class DebugVariablesModelService {
private static DEFAULT_TRIGGER_DELAY = 200;
@Autowired(INJECTOR_TOKEN)
private readonly injector: Injector;
@Autowired(ICtxMenuRenderer)
private readonly ctxMenuRenderer: ICtxMenuRenderer;
@Autowired(AbstractContextMenuService)
private readonly contextMenuService: AbstractContextMenuService;
@Autowired(DebugViewModel)
protected readonly viewModel: DebugViewModel;
@Autowired(IClipboardService)
private readonly clipboardService: IClipboardService;
@Autowired(DebugContextKey)
private readonly debugContextKey: DebugContextKey;
private _activeTreeModel: DebugVariablesModel | undefined;
private _decorations: DecorationsManager;
private _debugVariablesTreeHandle: IDebugVariablesHandle;
private _currentVariableInternalContext: DebugVariable | DebugVariableContainer | undefined;
public flushEventQueueDeferred: Deferred<void> | null;
// 装饰器
private selectedDecoration: Decoration = new Decoration(styles.mod_selected); // 选中态
private focusedDecoration: Decoration = new Decoration(styles.mod_focused); // 焦点态
private contextMenuDecoration: Decoration = new Decoration(styles.mod_actived); // 右键菜单激活态
private loadingDecoration: Decoration = new Decoration(styles.mod_loading); // 加载态
// 即使选中态也是焦点态的节点
private _focusedNode: ExpressionContainer | ExpressionNode | undefined;
// 选中态的节点
private _selectedNodes: (ExpressionContainer | ExpressionNode)[] = [];
// 右键菜单选中态的节点
private _contextMenuNode: ExpressionContainer | ExpressionNode | undefined;
private onDidRefreshedEmitter: Emitter<void> = new Emitter();
private onDidUpdateTreeModelEmitter: Emitter<TreeModel | void> = new Emitter();
private flushDispatchChangeDelayer = new ThrottledDelayer<void>(DebugVariablesModelService.DEFAULT_TRIGGER_DELAY);
private disposableCollection: DisposableCollection = new DisposableCollection();
private keepExpandedScopesModel: KeepExpandedScopesModel = new KeepExpandedScopesModel();
constructor() {
this.listenViewModelChange();
}
get flushEventQueuePromise() {
return this.flushEventQueueDeferred && this.flushEventQueueDeferred.promise;
}
get treeHandle() {
return this._debugVariablesTreeHandle;
}
get decorations() {
return this._decorations;
}
get treeModel() {
return this._activeTreeModel;
}
get currentVariableInternalContext() {
return this._currentVariableInternalContext;
}
// 既是选中态,也是焦点态节点
get focusedNode() {
return this._focusedNode;
}
// 是选中态,非焦点态节点
get selectedNodes() {
return this._selectedNodes;
}
// 右键菜单激活态的节点
get contextMenuNode() {
return this._contextMenuNode;
}
get onDidUpdateTreeModel(): Event<TreeModel | void> {
return this.onDidUpdateTreeModelEmitter.event;
}
get onDidRefreshed(): Event<void> {
return this.onDidRefreshedEmitter.event;
}
dispose() {
if (!this.disposableCollection.disposed) {
this.disposableCollection.dispose();
}
}
listenViewModelChange() {
this.viewModel.onDidChange(async () => {
if (!this.flushDispatchChangeDelayer.isTriggered()) {
this.flushDispatchChangeDelayer.cancel();
}
this.flushDispatchChangeDelayer.trigger(async () => {
if (this.viewModel && this.viewModel.currentSession && !this.viewModel.currentSession.terminated) {
const currentTreeModel = await this.initTreeModel(this.viewModel.currentSession);
this._activeTreeModel = currentTreeModel;
await this._activeTreeModel?.root.ensureLoaded();
/**
* 如果变量面板全部都是折叠状态
* 则需要找到当前 scope 作用域的 expensive 为 false 的变量列表,并默认展开它们
* PS: 一般的情况下有 Local
* */
const scopes = (this._activeTreeModel?.root.children as Array<DebugVariableWithRawScope>) || [];
if (scopes.length > 0 && scopes.every((s: DebugScope) => !s.expanded)) {
for (const s of scopes) {
if ((s as DebugScope).getRawScope().expensive === false && !s.expanded) {
await this.toggleDirectory(s);
}
}
}
const execExpands = async (data: Array<DebugVariableWithRawScope>) => {
for (const s of data) {
const cacheExpands = this.keepExpandedScopesModel.get(s);
if (cacheExpands.includes(s.variablesReference)) {
await s.setExpanded(true);
if (Array.isArray(s.children)) {
await execExpands(s.children as Array<DebugVariableWithRawScope>);
}
}
}
};
scopes.forEach(async (s) => {
if (Array.isArray(s.children)) {
await execExpands(s.children as Array<DebugVariableWithRawScope>);
}
});
} else {
this._activeTreeModel = undefined;
this.keepExpandedScopesModel.clear();
}
this.onDidUpdateTreeModelEmitter.fire(this._activeTreeModel);
});
});
}
listenTreeViewChange() {
this.dispose();
this.disposableCollection.push(
this.treeModel?.root.watcher.on(TreeNodeEvent.WillResolveChildren, (target) => {
this.loadingDecoration.addTarget(target);
}),
);
this.disposableCollection.push(
this.treeModel?.root.watcher.on(TreeNodeEvent.DidResolveChildren, (target) => {
this.loadingDecoration.removeTarget(target);
}),
);
this.disposableCollection.push(
this.treeModel!.onWillUpdate(() => {
// 更新树前更新下选中节点
if (this.selectedNodes.length !== 0) {
// 仅处理一下单选情况
const node = this.treeModel?.root.getTreeNodeByPath(this.selectedNodes[0].path);
this.selectedDecoration.addTarget(node as ExpressionNode);
}
}),
);
}
async initTreeModel(session?: DebugSession) {
// 根据是否为多工作区创建不同根节点
const root = new DebugVariableRoot(session);
if (!root) {
return;
}
this._activeTreeModel = this.injector.get<any>(DebugVariablesModel, [root]);
this.initDecorations(root);
this.listenTreeViewChange();
return this._activeTreeModel;
}
initDecorations(root) {
this._decorations = new DecorationsManager(root as any);
this._decorations.addDecoration(this.selectedDecoration);
this._decorations.addDecoration(this.focusedDecoration);
this._decorations.addDecoration(this.contextMenuDecoration);
this._decorations.addDecoration(this.loadingDecoration);
}
// 清空其他选中/焦点态节点,更新当前焦点节点
activeNodeDecoration = (target: ExpressionContainer | ExpressionNode, dispatchChange = true) => {
if (this.contextMenuNode) {
this.contextMenuDecoration.removeTarget(this.contextMenuNode);
this._contextMenuNode = undefined;
}
if (target) {
if (this.selectedNodes.length > 0) {
// 因为选择装饰器可能通过其他方式添加而不能及时在selectedNodes上更新
// 故这里遍历所有选中装饰器的节点进行一次统一清理
for (const target of this.selectedDecoration.appliedTargets.keys()) {
this.selectedDecoration.removeTarget(target);
}
}
if (this.focusedNode) {
this.focusedDecoration.removeTarget(this.focusedNode);
}
this.selectedDecoration.addTarget(target);
this.focusedDecoration.addTarget(target);
this._focusedNode = target;
this._selectedNodes = [target];
if (dispatchChange) {
// 通知视图更新
this.treeModel?.dispatchChange();
}
}
};
// 右键菜单焦点态切换
activeNodeActivedDecoration = (target: ExpressionContainer | ExpressionNode) => {
if (this.contextMenuNode) {
this.contextMenuDecoration.removeTarget(this.contextMenuNode);
}
if (this.focusedNode) {
this.focusedDecoration.removeTarget(this.focusedNode);
this._focusedNode = undefined;
}
this.contextMenuDecoration.addTarget(target);
this._contextMenuNode = target;
this.treeModel?.dispatchChange();
};
// 取消选中节点焦点
enactiveNodeDecoration = () => {
if (this.focusedNode) {
this.focusedDecoration.removeTarget(this.focusedNode);
this._focusedNode = undefined;
}
if (this.contextMenuNode) {
this.contextMenuDecoration.removeTarget(this.contextMenuNode);
}
this.treeModel?.dispatchChange();
};
removeNodeDecoration() {
if (!this.decorations) {
return;
}
this.decorations.removeDecoration(this.selectedDecoration);
this.decorations.removeDecoration(this.focusedDecoration);
this.decorations.removeDecoration(this.loadingDecoration);
this.decorations.removeDecoration(this.contextMenuDecoration);
}
handleContextMenu = (
ev: React.MouseEvent,
expression?: DebugScope | DebugVariableContainer | DebugVariable | undefined,
) => {
ev.stopPropagation();
ev.preventDefault();
if (!expression || expression instanceof DebugScope) {
this.enactiveNodeDecoration();
this.debugContextKey.contextVariableEvaluateNamePresent.set(false);
return;
}
this._currentVariableInternalContext = expression;
const { x, y } = ev.nativeEvent;
if (expression) {
this.activeNodeActivedDecoration(expression);
this.debugContextKey.contextDebugProtocolVariableMenu.set(expression.variableMenuContext);
this.debugContextKey.contextVariableEvaluateNamePresent.set(
!!(expression as DebugVariableContainer | DebugVariable).evaluateName,
);
}
const menus = this.contextMenuService.createMenu({
id: MenuId.DebugVariablesContext,
contextKeyService: this.debugContextKey.contextKeyScoped,
});
const menuNodes = menus.getMergedMenuNodes();
menus.dispose();
this.ctxMenuRenderer.show({
anchor: { x, y },
menuNodes,
args: [expression.toDebugProtocolObject()],
});
};
handleTreeHandler(handle: IDebugVariablesHandle) {
this._debugVariablesTreeHandle = {
...handle,
getModel: () => this.treeModel!,
};
}
handleTreeBlur = () => {
// 清空焦点状态
this.enactiveNodeDecoration();
};
handleItemClick = (item: ExpressionContainer | ExpressionNode) => {
// 单选操作默认先更新选中状态
this.activeNodeDecoration(item);
};
handleTwistierClick = (item: ExpressionContainer | ExpressionNode, type: TreeNodeType) => {
if (type === TreeNodeType.CompositeTreeNode) {
this.activeNodeDecoration(item, false);
this.toggleDirectory(item as DebugVariableWithRawScope);
} else {
this.activeNodeDecoration(item);
}
};
toggleDirectory = async (item: DebugVariableWithRawScope) => {
if (item.expanded) {
item.setCollapsed();
} else {
await item.setExpanded(true);
}
this.keepExpandedScopesModel.set(item);
};
async copyEvaluateName(node: DebugVariableContainer | DebugVariable | undefined) {
if (!node) {
return;
}
await this.clipboardService.writeText(node.evaluateName);
}
async copyValue(node: DebugVariableContainer | DebugVariable | undefined) {
if (!node) {
return;
}
const getClipboardValue = async () => {
if (node.session && node.session.capabilities.supportsValueFormattingOptions) {
try {
const {
variable: { evaluateName },
} = node;
if (evaluateName) {
const body = await node.session.evaluate(evaluateName, 'clipboard');
if (body) {
return body.result;
}
}
return '';
} catch (err) {
return '';
}
} else {
return node.value;
}
};
const value = await getClipboardValue();
if (value) {
await this.clipboardService.writeText(value);
}
}
} | the_stack |
import { ConcreteRequest } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type ShippingQuotes_Test_QueryVariables = {};
export type ShippingQuotes_Test_QueryResponse = {
readonly order: {
readonly lineItems: {
readonly edges: ReadonlyArray<{
readonly node: {
readonly shippingQuoteOptions: {
readonly edges: ReadonlyArray<{
readonly " $fragmentRefs": FragmentRefs<"ShippingQuotes_shippingQuotes">;
} | null> | null;
} | null;
} | null;
} | null> | null;
} | null;
} | null;
};
export type ShippingQuotes_Test_QueryRawResponse = {
readonly order: ({
readonly __typename: string | null;
readonly lineItems: ({
readonly edges: ReadonlyArray<({
readonly node: ({
readonly shippingQuoteOptions: ({
readonly edges: ReadonlyArray<({
readonly node: ({
readonly id: string;
readonly displayName: string;
readonly isSelected: boolean;
readonly price: string | null;
readonly priceCents: number;
}) | null;
}) | null> | null;
}) | null;
readonly id: string | null;
}) | null;
}) | null> | null;
}) | null;
readonly id: string | null;
}) | null;
};
export type ShippingQuotes_Test_Query = {
readonly response: ShippingQuotes_Test_QueryResponse;
readonly variables: ShippingQuotes_Test_QueryVariables;
readonly rawResponse: ShippingQuotes_Test_QueryRawResponse;
};
/*
query ShippingQuotes_Test_Query {
order: commerceOrder {
__typename
lineItems {
edges {
node {
shippingQuoteOptions {
edges {
...ShippingQuotes_shippingQuotes
}
}
id
}
}
}
id
}
}
fragment ShippingQuotes_shippingQuotes on CommerceShippingQuoteEdge {
node {
id
displayName
isSelected
price(precision: 2)
priceCents
}
}
*/
const node: ConcreteRequest = (function(){
var v0 = {
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
};
return {
"fragment": {
"argumentDefinitions": [],
"kind": "Fragment",
"metadata": null,
"name": "ShippingQuotes_Test_Query",
"selections": [
{
"alias": "order",
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "commerceOrder",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceLineItemConnection",
"kind": "LinkedField",
"name": "lineItems",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceLineItemEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceLineItem",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceShippingQuoteConnection",
"kind": "LinkedField",
"name": "shippingQuoteOptions",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceShippingQuoteEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"args": null,
"kind": "FragmentSpread",
"name": "ShippingQuotes_shippingQuotes"
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"type": "Query"
},
"kind": "Request",
"operation": {
"argumentDefinitions": [],
"kind": "Operation",
"name": "ShippingQuotes_Test_Query",
"selections": [
{
"alias": "order",
"args": null,
"concreteType": null,
"kind": "LinkedField",
"name": "commerceOrder",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "__typename",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "CommerceLineItemConnection",
"kind": "LinkedField",
"name": "lineItems",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceLineItemEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceLineItem",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceShippingQuoteConnection",
"kind": "LinkedField",
"name": "shippingQuoteOptions",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceShippingQuoteEdge",
"kind": "LinkedField",
"name": "edges",
"plural": true,
"selections": [
{
"alias": null,
"args": null,
"concreteType": "CommerceShippingQuote",
"kind": "LinkedField",
"name": "node",
"plural": false,
"selections": [
(v0/*: any*/),
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "displayName",
"storageKey": null
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "isSelected",
"storageKey": null
},
{
"alias": null,
"args": [
{
"kind": "Literal",
"name": "precision",
"value": 2
}
],
"kind": "ScalarField",
"name": "price",
"storageKey": "price(precision:2)"
},
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "priceCents",
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
},
(v0/*: any*/)
],
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
},
(v0/*: any*/)
],
"storageKey": null
}
]
},
"params": {
"id": null,
"metadata": {},
"name": "ShippingQuotes_Test_Query",
"operationKind": "query",
"text": "query ShippingQuotes_Test_Query {\n order: commerceOrder {\n __typename\n lineItems {\n edges {\n node {\n shippingQuoteOptions {\n edges {\n ...ShippingQuotes_shippingQuotes\n }\n }\n id\n }\n }\n }\n id\n }\n}\n\nfragment ShippingQuotes_shippingQuotes on CommerceShippingQuoteEdge {\n node {\n id\n displayName\n isSelected\n price(precision: 2)\n priceCents\n }\n}\n"
}
};
})();
(node as any).hash = '4dac5e210a9086537685cd4c7fb167e1';
export default node; | the_stack |
import _ = require('lodash');
import gql from 'graphql-tag';
import { MockedEndpoint, MockedEndpointData } from "../types";
import { buildBodyReader } from '../util/request-utils';
import { objectHeadersToRaw, rawHeadersToObject } from '../util/header-utils';
import type { Serialized } from '../serialization/serialization';
import { AdminQuery } from './admin-query';
import { SchemaIntrospector } from './schema-introspection';
import type { RequestRuleData } from "../rules/requests/request-rule";
import type { WebSocketRuleData } from '../rules/websockets/websocket-rule';
import { SubscribableEvent } from '../mockttp';
import { MockedEndpointClient } from "./mocked-endpoint-client";
import { AdminClient } from './admin-client';
function normalizeHttpMessage(message: any, event?: SubscribableEvent) {
if (message.timingEvents) {
// Timing events are serialized as raw JSON
message.timingEvents = JSON.parse(message.timingEvents);
} else if (event !== 'tls-client-error' && event !== 'client-error') {
// For backwards compat, all except errors should have timing events if they're missing
message.timingEvents = {};
}
if (message.rawHeaders) {
message.rawHeaders = JSON.parse(message.rawHeaders);
// We use raw headers where possible to derive headers, instead of using any pre-derived
// header data, for maximum accuracy (and to avoid any need to query for both).
message.headers = rawHeadersToObject(message.rawHeaders);
} else if (message.headers) {
// Backward compat for older servers:
message.headers = JSON.parse(message.headers);
message.rawHeaders = objectHeadersToRaw(message.headers);
}
if (message.body !== undefined) {
// Body is serialized as the raw encoded buffer in base64
message.body = buildBodyReader(Buffer.from(message.body, 'base64'), message.headers);
}
// For backwards compat, all except errors should have tags if they're missing
if (!message.tags) message.tags = [];
}
export class MockttpAdminRequestBuilder {
constructor(
private schema: SchemaIntrospector
) {}
buildAddRequestRulesQuery(
rules: Array<Serialized<RequestRuleData>>,
reset: boolean
): AdminQuery<
{ endpoints: Array<{ id: string, explanation?: string }> },
MockedEndpoint[]
> {
const requestName = (reset ? 'Set' : 'Add') + 'Rules';
const mutationName = (reset ? 'set' : 'add') + 'Rules';
return {
query: gql`
mutation ${requestName}($newRules: [MockRule!]!) {
endpoints: ${mutationName}(input: $newRules) {
id,
${this.schema.asOptionalField('MockedEndpoint', 'explanation')}
}
}
`,
variables: {
newRules: rules
},
transformResponse: (response, { adminClient }) => {
return response.endpoints.map(({ id, explanation }) =>
new MockedEndpointClient(
id,
explanation,
this.getEndpointDataGetter(adminClient, id)
)
)
}
};
}
buildAddWebSocketRulesQuery(
rules: Array<Serialized<WebSocketRuleData>>,
reset: boolean
): AdminQuery<
{ endpoints: Array<{ id: string, explanation?: string }> },
MockedEndpoint[]
> {
// Seperate and simpler than buildAddRequestRulesQuery, because it doesn't have to
// deal with backward compatibility.
const requestName = (reset ? 'Set' : 'Add') + 'WebSocketRules';
const mutationName = (reset ? 'set' : 'add') + 'WebSocketRules';
return {
query: gql`
mutation ${requestName}($newRules: [WebSocketMockRule!]!) {
endpoints: ${mutationName}(input: $newRules) {
id,
explanation
}
}
`,
variables: {
newRules: rules
},
transformResponse: (response, { adminClient }) => {
return response.endpoints.map(({ id, explanation }) =>
new MockedEndpointClient(
id,
explanation,
this.getEndpointDataGetter(adminClient, id)
)
);
}
};
};
buildMockedEndpointsQuery(): AdminQuery<
{ mockedEndpoints: MockedEndpointData[] },
MockedEndpoint[]
> {
return {
query: gql`
query GetAllEndpointData {
mockedEndpoints {
id,
${this.schema.asOptionalField('MockedEndpoint', 'explanation')}
}
}
`,
transformResponse: (response, { adminClient }) => {
const mockedEndpoints = response.mockedEndpoints;
return mockedEndpoints.map(({ id, explanation }) =>
new MockedEndpointClient(
id,
explanation,
this.getEndpointDataGetter(adminClient, id)
)
);
}
};
}
public buildPendingEndpointsQuery(): AdminQuery<
{ pendingEndpoints: MockedEndpointData[] },
MockedEndpoint[]
> {
return {
query: gql`
query GetPendingEndpointData {
pendingEndpoints {
id,
explanation
}
}
`,
transformResponse: (response, { adminClient }) => {
const pendingEndpoints = response.pendingEndpoints;
return pendingEndpoints.map(({ id, explanation }) =>
new MockedEndpointClient(
id,
explanation,
this.getEndpointDataGetter(adminClient, id)
)
);
}
};
}
public buildSubscriptionRequest<T>(event: SubscribableEvent): AdminQuery<unknown, T> {
// Note the asOptionalField checks - these are a quick hack for backward compatibility,
// introspecting the server schema to avoid requesting fields that don't exist on old servers.
const query = {
'request-initiated': gql`subscription OnRequestInitiated {
requestInitiated {
id,
protocol,
method,
url,
path,
${this.schema.asOptionalField('InitiatedRequest', 'remoteIpAddress')},
${this.schema.asOptionalField('InitiatedRequest', 'remotePort')},
hostname,
${this.schema.typeHasField('InitiatedRequest', 'rawHeaders')
? 'rawHeaders'
: 'headers'
}
timingEvents,
httpVersion,
${this.schema.asOptionalField('InitiatedRequest', 'tags')}
}
}`,
request: gql`subscription OnRequest {
requestReceived {
id,
${this.schema.asOptionalField('Request', 'matchedRuleId')}
protocol,
method,
url,
path,
${this.schema.asOptionalField('Request', 'remoteIpAddress')},
${this.schema.asOptionalField('Request', 'remotePort')},
hostname,
${this.schema.typeHasField('Request', 'rawHeaders')
? 'rawHeaders'
: 'headers'
}
body,
${this.schema.asOptionalField('Request', 'timingEvents')}
${this.schema.asOptionalField('Request', 'httpVersion')}
${this.schema.asOptionalField('Request', 'tags')}
}
}`,
response: gql`subscription OnResponse {
responseCompleted {
id,
statusCode,
statusMessage,
${this.schema.typeHasField('Response', 'rawHeaders')
? 'rawHeaders'
: 'headers'
}
body,
${this.schema.asOptionalField('Response', 'timingEvents')}
${this.schema.asOptionalField('Response', 'tags')}
}
}`,
abort: gql`subscription OnAbort {
requestAborted {
id,
protocol,
method,
url,
path,
hostname,
${this.schema.typeHasField('Request', 'rawHeaders')
? 'rawHeaders'
: 'headers'
}
${this.schema.asOptionalField('Request', 'timingEvents')}
${this.schema.asOptionalField('Request', 'tags')}
}
}`,
'tls-client-error': gql`subscription OnTlsClientError {
failedTlsRequest {
failureCause
hostname
remoteIpAddress
${this.schema.asOptionalField('TlsRequest', 'remotePort')}
${this.schema.asOptionalField('TlsRequest', 'tags')}
${this.schema.asOptionalField('TlsRequest', 'timingEvents')}
}
}`,
'client-error': gql`subscription OnClientError {
failedClientRequest {
errorCode
request {
id
timingEvents
tags
protocol
httpVersion
method
url
path
${this.schema.typeHasField('ClientErrorRequest', 'rawHeaders')
? 'rawHeaders'
: 'headers'
}
${this.schema.asOptionalField('ClientErrorRequest', 'remoteIpAddress')},
${this.schema.asOptionalField('ClientErrorRequest', 'remotePort')},
}
response {
id
timingEvents
tags
statusCode
statusMessage
${this.schema.typeHasField('Response', 'rawHeaders')
? 'rawHeaders'
: 'headers'
}
body
}
}
}`
}[event];
return {
query,
transformResponse: (data: any): T => {
if (event === 'client-error') {
data.request = _.mapValues(data.request, (v) =>
// Normalize missing values to undefined to match the local result
v === null ? undefined : v
);
normalizeHttpMessage(data.request, event);
if (data.response) {
normalizeHttpMessage(data.response, event);
} else {
data.response = 'aborted';
}
} else {
normalizeHttpMessage(data, event);
}
return data;
}
};
}
private getEndpointDataGetter = (adminClient: AdminClient<{}>, ruleId: string) =>
async (): Promise<MockedEndpointData | null> => {
let result = await adminClient.sendQuery<{
mockedEndpoint: MockedEndpointData | null
}>({
query: gql`
query GetEndpointData($id: ID!) {
mockedEndpoint(id: $id) {
seenRequests {
protocol,
method,
url,
path,
hostname
${this.schema.typeHasField('Request', 'rawHeaders')
? 'rawHeaders'
: 'headers'
}
body,
${this.schema.asOptionalField('Request', 'timingEvents')}
${this.schema.asOptionalField('Request', 'httpVersion')}
}
${this.schema.asOptionalField('MockedEndpoint', 'isPending')}
}
}
`,
variables: { id: ruleId }
});
const mockedEndpoint = result.mockedEndpoint;
if (!mockedEndpoint) return null;
mockedEndpoint.seenRequests.forEach(req => normalizeHttpMessage(req));
return mockedEndpoint;
}
} | the_stack |
import * as React from "react"
import * as ReactDOMServer from "react-dom/server"
import {
observable,
computed,
action,
autorun,
runInAction,
reaction,
IReactionDisposer,
} from "mobx"
import { bind } from "decko"
import { ColorScale } from "../color/ColorScale"
import {
uniqWith,
isEqual,
uniq,
slugify,
identity,
lowerCaseFirstLetterUnlessAbbreviation,
isMobile,
isVisible,
throttle,
next,
sampleFrom,
range,
difference,
exposeInstanceOnWindow,
findClosestTime,
excludeUndefined,
debounce,
isInIFrame,
differenceObj,
} from "../../clientUtils/Util"
import { QueryParams } from "../../clientUtils/urls/UrlUtils"
import {
ChartTypeName,
GrapherTabOption,
ScaleType,
StackMode,
EntitySelectionMode,
HighlightToggleConfig,
ScatterPointLabelStrategy,
RelatedQuestionsConfig,
BASE_FONT_SIZE,
CookieKey,
FacetStrategy,
ThereWasAProblemLoadingThisChart,
SeriesColorMap,
FacetAxisDomain,
} from "../core/GrapherConstants"
import { LegacyVariablesAndEntityKey } from "./LegacyVariableCode"
import * as Cookies from "js-cookie"
import {
ChartDimension,
LegacyDimensionsManager,
} from "../chart/ChartDimension"
import { Bounds, DEFAULT_BOUNDS } from "../../clientUtils/Bounds"
import { TooltipProps, TooltipManager } from "../tooltip/TooltipProps"
import {
minTimeBoundFromJSONOrNegativeInfinity,
maxTimeBoundFromJSONOrPositiveInfinity,
TimeBounds,
getTimeDomainFromQueryString,
TimeBound,
minTimeToJSON,
maxTimeToJSON,
timeBoundToTimeBoundString,
} from "../../clientUtils/TimeBounds"
import {
strToQueryParams,
queryParamsToStr,
setWindowQueryStr,
} from "../../clientUtils/urls/UrlUtils"
import { populationMap } from "../../coreTable/PopulationMap"
import {
GrapherInterface,
grapherKeysToSerialize,
GrapherQueryParams,
LegacyGrapherInterface,
} from "../core/GrapherInterface"
import { DimensionSlot } from "../chart/DimensionSlot"
import {
getSelectedEntityNamesParam,
setSelectedEntityNamesParam,
} from "./EntityUrlBuilder"
import { MapProjectionName } from "../mapCharts/MapProjections"
import { LogoOption } from "../captionedChart/Logos"
import { AxisConfig, FontSizeManager } from "../axis/AxisConfig"
import { ColorScaleConfig } from "../color/ColorScaleConfig"
import { MapConfig } from "../mapCharts/MapConfig"
import { ComparisonLineConfig } from "../scatterCharts/ComparisonLine"
import {
objectWithPersistablesToObject,
deleteRuntimeAndUnchangedProps,
updatePersistables,
} from "../persistable/Persistable"
import { ColumnSlugs, Time } from "../../coreTable/CoreTableConstants"
import { isOnTheMap } from "../mapCharts/EntitiesOnTheMap"
import { ChartManager } from "../chart/ChartManager"
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"
import { faExclamationTriangle } from "@fortawesome/free-solid-svg-icons/faExclamationTriangle"
import {
AbsRelToggleManager,
FacetStrategyDropdownManager,
FooterControls,
FooterControlsManager,
HighlightToggleManager,
SmallCountriesFilterManager,
} from "../controls/Controls"
import { TooltipView } from "../tooltip/Tooltip"
import { EntitySelectorModal } from "../controls/EntitySelectorModal"
import { DownloadTab, DownloadTabManager } from "../downloadTab/DownloadTab"
import * as ReactDOM from "react-dom"
import { observer } from "mobx-react"
import "d3-transition"
import { SourcesTab, SourcesTabManager } from "../sourcesTab/SourcesTab"
import { DataTable, DataTableManager } from "../dataTable/DataTable"
import { MapChartManager } from "../mapCharts/MapChartConstants"
import { MapChart } from "../mapCharts/MapChart"
import { DiscreteBarChartManager } from "../barCharts/DiscreteBarChartConstants"
import { Command, CommandPalette } from "../controls/CommandPalette"
import { ShareMenuManager } from "../controls/ShareMenu"
import {
CaptionedChart,
CaptionedChartManager,
StaticCaptionedChart,
} from "../captionedChart/CaptionedChart"
import {
TimelineController,
TimelineManager,
} from "../timeline/TimelineController"
import {
EntityId,
EntityName,
OwidColumnDef,
} from "../../coreTable/OwidTableConstants"
import { BlankOwidTable, OwidTable } from "../../coreTable/OwidTable"
import * as Mousetrap from "mousetrap"
import { SlideShowController } from "../slideshowController/SlideShowController"
import {
ChartComponentClassMap,
DefaultChartClass,
} from "../chart/ChartTypeMap"
import { ColorSchemeName } from "../color/ColorConstants"
import { SelectionArray } from "../selection/SelectionArray"
import { legacyToOwidTableAndDimensions } from "./LegacyToOwidTable"
import { ScatterPlotManager } from "../scatterCharts/ScatterPlotChartConstants"
import { autoDetectYColumnSlugs } from "../chart/ChartUtils"
import classNames from "classnames"
import { GrapherAnalytics } from "./GrapherAnalytics"
import {
ADMIN_BASE_URL,
BAKED_GRAPHER_URL,
} from "../../settings/clientSettings"
import { legacyToCurrentGrapherQueryParams } from "./GrapherUrlMigrations"
import { Url } from "../../clientUtils/urls/Url"
import {
Annotation,
ColumnSlug,
DimensionProperty,
SortBy,
SortConfig,
SortOrder,
} from "../../clientUtils/owidTypes"
import { ColumnTypeMap, CoreColumn } from "../../coreTable/CoreTableColumns"
import { ChartInterface } from "../chart/ChartInterface"
import { LegacyChartDimensionInterface } from "../../clientUtils/LegacyVariableDisplayConfigInterface"
import { MarimekkoChartManager } from "../stackedCharts/MarimekkoChartConstants"
import { AxisConfigInterface } from "../axis/AxisConfigInterface"
import Bugsnag from "@bugsnag/js"
import { FacetChartManager } from "../facetChart/FacetChartConstants"
declare const window: any
const legacyConfigToConfig = (
config: LegacyGrapherInterface | GrapherInterface
): GrapherInterface => {
const legacyConfig = config as LegacyGrapherInterface
if (!legacyConfig.selectedData) return legacyConfig
const newConfig = { ...legacyConfig } as GrapherInterface
newConfig.selectedEntityIds = uniq(
legacyConfig.selectedData.map((row) => row.entityId)
) // We need to do uniq because an EntityName may appear multiple times in the old graphers, once for each dimension
return newConfig
}
const DEFAULT_MS_PER_TICK = 100
// Exactly the same as GrapherInterface, but contains options that developers want but authors won't be touching.
export interface GrapherProgrammaticInterface extends GrapherInterface {
owidDataset?: LegacyVariablesAndEntityKey // This is temporarily used for testing. Will be removed
manuallyProvideData?: boolean // This will be removed.
hideEntityControls?: boolean
queryStr?: string
isMediaCard?: boolean
bounds?: Bounds
table?: OwidTable
bakedGrapherURL?: string
adminBaseUrl?: string
env?: string
getGrapherInstance?: (instance: Grapher) => void
enableKeyboardShortcuts?: boolean
bindUrlToWindow?: boolean
isEmbeddedInAnOwidPage?: boolean
manager?: GrapherManager
}
export interface GrapherManager {
canonicalUrl?: string
embedDialogUrl?: string
embedDialogAdditionalElements?: React.ReactElement
selection?: SelectionArray
editUrl?: string
}
@observer
export class Grapher
extends React.Component<GrapherProgrammaticInterface>
implements
TimelineManager,
ChartManager,
FontSizeManager,
CaptionedChartManager,
SourcesTabManager,
DownloadTabManager,
DiscreteBarChartManager,
LegacyDimensionsManager,
ShareMenuManager,
SmallCountriesFilterManager,
HighlightToggleManager,
AbsRelToggleManager,
TooltipManager,
FooterControlsManager,
DataTableManager,
ScatterPlotManager,
MarimekkoChartManager,
FacetStrategyDropdownManager,
FacetChartManager,
MapChartManager
{
@observable.ref type = ChartTypeName.LineChart
@observable.ref id?: number = undefined
@observable.ref version = 1
@observable.ref slug?: string = undefined
@observable.ref title?: string = undefined
@observable.ref subtitle = ""
@observable.ref sourceDesc?: string = undefined
@observable.ref note = ""
@observable.ref hideTitleAnnotation?: boolean = undefined
@observable.ref minTime?: TimeBound = undefined
@observable.ref maxTime?: TimeBound = undefined
@observable.ref timelineMinTime?: Time = undefined
@observable.ref timelineMaxTime?: Time = undefined
@observable.ref addCountryMode = EntitySelectionMode.MultipleEntities
@observable.ref highlightToggle?: HighlightToggleConfig = undefined
@observable.ref stackMode = StackMode.absolute
@observable.ref showNoDataArea: boolean = true
@observable.ref hideLegend?: boolean = false
@observable.ref logo?: LogoOption = undefined
@observable.ref hideLogo?: boolean = undefined
@observable.ref hideRelativeToggle? = true
@observable.ref entityType = "country"
@observable.ref entityTypePlural = "countries"
@observable.ref hideTimeline?: boolean = undefined
@observable.ref zoomToSelection?: boolean = undefined
@observable.ref minPopulationFilter?: number = undefined
@observable.ref showYearLabels?: boolean = undefined // Always show year in labels for bar charts
@observable.ref hasChartTab: boolean = true
@observable.ref hasMapTab: boolean = false
@observable.ref tab = GrapherTabOption.chart
@observable.ref overlay?: GrapherTabOption = undefined
@observable.ref internalNotes = ""
@observable.ref variantName?: string = undefined
@observable.ref originUrl = ""
@observable.ref isPublished?: boolean = undefined
@observable.ref baseColorScheme?: ColorSchemeName = undefined
@observable.ref invertColorScheme?: boolean = undefined
@observable.ref hideLinesOutsideTolerance?: boolean = undefined
@observable hideConnectedScatterLines?: boolean = undefined // Hides lines between points when timeline spans multiple years. Requested by core-econ for certain charts
@observable
scatterPointLabelStrategy?: ScatterPointLabelStrategy = undefined
@observable.ref compareEndPointsOnly?: boolean = undefined
@observable.ref matchingEntitiesOnly?: boolean = undefined
/** Hides the total value label that is normally displayed for stacked bar charts */
@observable.ref hideTotalValueLabel?: boolean = undefined
@observable.ref xAxis = new AxisConfig(undefined, this)
@observable.ref yAxis = new AxisConfig(undefined, this)
@observable colorScale = new ColorScaleConfig()
@observable map = new MapConfig()
@observable.ref dimensions: ChartDimension[] = []
@observable ySlugs?: ColumnSlugs = undefined
@observable xSlug?: ColumnSlug = undefined
@observable colorSlug?: ColumnSlug = undefined
@observable sizeSlug?: ColumnSlug = undefined
@observable tableSlugs?: ColumnSlugs = undefined
@observable backgroundSeriesLimit?: number = undefined
@observable selectedEntityNames: EntityName[] = []
@observable selectedEntityColors: { [entityName: string]: string } = {}
@observable selectedEntityIds: EntityId[] = []
@observable excludedEntities?: number[] = undefined
/** IncludedEntities are ususally empty which means use all available entites. When
includedEntities is set it means "only use these entities". excludedEntities
are evaluated afterwards and can still remove entities even if they were included before.
*/
@observable includedEntities?: number[] = undefined
@observable comparisonLines: ComparisonLineConfig[] = [] // todo: Persistables?
@observable relatedQuestions: RelatedQuestionsConfig[] = [] // todo: Persistables?
@observable.ref annotation?: Annotation = undefined
@observable hideFacetControl?: boolean = true
// the desired faceting strategy, which might not be possible if we change the data
@observable selectedFacetStrategy?: FacetStrategy = undefined
@observable sortBy?: SortBy
@observable sortOrder?: SortOrder
@observable sortColumnSlug?: string
owidDataset?: LegacyVariablesAndEntityKey = undefined // This is temporarily used for testing. Will be removed
manuallyProvideData? = false // This will be removed.
// TODO: Pass these 5 in as options, don't get them as globals.
isDev = this.props.env === "development"
analytics = new GrapherAnalytics(this.props.env ?? "")
isEditor =
typeof window !== "undefined" && (window as any).isEditor === true
@observable bakedGrapherURL = BAKED_GRAPHER_URL
adminBaseUrl = ADMIN_BASE_URL
@observable.ref inputTable: OwidTable
@observable.ref legacyConfigAsAuthored: Partial<LegacyGrapherInterface> = {}
@computed get dataTableSlugs(): ColumnSlug[] {
return this.tableSlugs ? this.tableSlugs.split(" ") : this.newSlugs
}
/**
* todo: factor this out and make more RAII.
*
* Explorers create 1 Grapher instance, but as the user clicks around the Explorer loads other author created Graphers.
* But currently some Grapher features depend on knowing how the current state is different than the "authored state".
* So when an Explorer updates the grapher, it also needs to update this "original state".
*/
@action.bound setAuthoredVersion(
config: Partial<LegacyGrapherInterface>
): void {
this.legacyConfigAsAuthored = config
}
@action.bound updateAuthoredVersion(
config: Partial<LegacyGrapherInterface>
): void {
this.legacyConfigAsAuthored = {
...this.legacyConfigAsAuthored,
...config,
}
}
constructor(
propsWithGrapherInstanceGetter: GrapherProgrammaticInterface = {}
) {
super(propsWithGrapherInstanceGetter)
const { getGrapherInstance, ...props } = propsWithGrapherInstanceGetter
this.inputTable = props.table ?? BlankOwidTable(`initialGrapherTable`)
const modernConfig = props ? legacyConfigToConfig(props) : props
if (props) this.setAuthoredVersion(props)
this.updateFromObject(modernConfig)
if (!props.table) this.downloadData()
this.populateFromQueryParams(
legacyToCurrentGrapherQueryParams(props.queryStr ?? "")
)
if (this.isEditor) this.ensureValidConfigWhenEditing()
if (getGrapherInstance) getGrapherInstance(this) // todo: possibly replace with more idiomatic ref
this.checkVisibility = throttle(this.checkVisibility, 400)
}
toObject(): GrapherInterface {
const obj: GrapherInterface = objectWithPersistablesToObject(
this,
grapherKeysToSerialize
)
if (this.selection.hasSelection)
obj.selectedEntityNames = this.selection.selectedEntityNames
deleteRuntimeAndUnchangedProps(obj, defaultObject)
// todo: nulls got into the DB for this one. we can remove after moving Graphers from DB.
if (obj.stackMode === null) delete obj.stackMode
// JSON doesn't support Infinity, so we use strings instead.
if (obj.minTime) obj.minTime = minTimeToJSON(this.minTime) as any
if (obj.maxTime) obj.maxTime = maxTimeToJSON(this.maxTime) as any
// todo: remove dimensions concept
// if (this.legacyConfigAsAuthored?.dimensions)
// obj.dimensions = this.legacyConfigAsAuthored.dimensions
return obj
}
@action.bound downloadData(): void {
if (this.manuallyProvideData) {
} else if (this.owidDataset)
this._receiveLegacyDataAndApplySelection(this.owidDataset)
else this.downloadLegacyDataFromOwidVariableIds()
}
@action.bound updateFromObject(obj?: GrapherProgrammaticInterface): void {
if (!obj) return
// we can remove when we purge current graphers which have this set.
if (obj.stackMode === null) delete obj.stackMode
updatePersistables(this, obj)
// Regression fix: some legacies have this set to Null. Todo: clean DB.
if (obj.originUrl === null) this.originUrl = ""
// JSON doesn't support Infinity, so we use strings instead.
this.minTime = minTimeBoundFromJSONOrNegativeInfinity(obj.minTime)
this.maxTime = maxTimeBoundFromJSONOrPositiveInfinity(obj.maxTime)
// Todo: remove once we are more RAII.
if (obj?.dimensions?.length)
this.setDimensionsFromConfigs(obj.dimensions)
}
@action.bound populateFromQueryParams(params: GrapherQueryParams): void {
// Set tab if specified
const tab = params.tab
if (tab) {
if (!this.availableTabs.includes(tab as GrapherTabOption))
console.error("Unexpected tab: " + tab)
else this.tab = tab as GrapherTabOption
}
const overlay = params.overlay
if (overlay) {
if (!this.availableTabs.includes(overlay as GrapherTabOption))
console.error("Unexpected overlay: " + overlay)
else this.overlay = overlay as GrapherTabOption
}
// Stack mode for bar and stacked area charts
this.stackMode = (params.stackMode ?? this.stackMode) as StackMode
this.zoomToSelection =
params.zoomToSelection === "true" ? true : this.zoomToSelection
this.minPopulationFilter = params.minPopulationFilter
? parseInt(params.minPopulationFilter)
: this.minPopulationFilter
// Axis scale mode
const xScaleType = params.xScale
if (xScaleType) {
if (xScaleType === ScaleType.linear || xScaleType === ScaleType.log)
this.xAxis.scaleType = xScaleType
else console.error("Unexpected xScale: " + xScaleType)
}
const yScaleType = params.yScale
if (yScaleType) {
if (yScaleType === ScaleType.linear || yScaleType === ScaleType.log)
this.yAxis.scaleType = yScaleType
else console.error("Unexpected xScale: " + yScaleType)
}
const time = params.time
if (time !== undefined && time !== "")
this.setTimeFromTimeQueryParam(time)
const endpointsOnly = params.endpointsOnly
if (endpointsOnly !== undefined)
this.compareEndPointsOnly = endpointsOnly === "1" ? true : undefined
const region = params.region
if (region !== undefined)
this.map.projection = region as MapProjectionName
const selection = getSelectedEntityNamesParam(
Url.fromQueryParams(params)
)
if (this.addCountryMode !== EntitySelectionMode.Disabled && selection)
this.selection.setSelectedEntities(selection)
// faceting
if (params.facet && params.facet in FacetStrategy) {
this.selectedFacetStrategy = params.facet as FacetStrategy
}
if (params.uniformYAxis === "0") {
this.yAxis.facetDomain = FacetAxisDomain.independent
}
}
@action.bound private setTimeFromTimeQueryParam(time: string): void {
this.timelineHandleTimeBounds = getTimeDomainFromQueryString(time).map(
(time) => findClosestTime(this.times, time) ?? time
) as TimeBounds
}
@computed private get isChartOrMapTab(): boolean {
return this.tab === GrapherTabOption.chart || this.isOnMapTab
}
@computed private get isOnMapTab(): boolean {
return this.tab === GrapherTabOption.map
}
@computed get yAxisConfig(): Readonly<AxisConfigInterface> {
return this.yAxis.toObject()
}
@computed get xAxisConfig(): Readonly<AxisConfigInterface> {
return this.xAxis.toObject()
}
@computed get tableForSelection(): OwidTable {
// This table specifies which entities can be selected in the charts EntitySelectorModal.
// It should contain all entities that can be selected, and none more.
// Depending on the chart type, the criteria for being able to select an entity are
// different; e.g. for scatterplots, the entity needs to (1) not be excluded and
// (2) needs to have data for the x and y dimension.
if (this.isScatter || this.isSlopeChart)
// for scatter and slope charts, the `transformTable()` call takes care of removing
// all entities that cannot be selected
return this.tableAfterAuthorTimelineAndActiveChartTransform
// for other chart types, the `transformTable()` call would sometimes remove too many
// entities, and we want to use the inputTable instead (which should have exactly the
// entities where data is available)
return this.inputTable
}
// If an author sets a timeline filter run it early in the pipeline so to the charts it's as if the filtered times do not exist
@computed get tableAfterAuthorTimelineFilter(): OwidTable {
const table = this.inputTable
if (
this.timelineMinTime === undefined &&
this.timelineMaxTime === undefined
)
return table
return table.filterByTimeRange(
this.timelineMinTime ?? -Infinity,
this.timelineMaxTime ?? Infinity
)
}
// Convenience method for debugging
windowQueryParams(str = location.search): QueryParams {
return strToQueryParams(str)
}
@computed
private get tableAfterAuthorTimelineAndActiveChartTransform(): OwidTable {
const table = this.tableAfterAuthorTimelineFilter
if (!this.isReady || !this.isChartOrMapTab) return table
return this.chartInstance.transformTable(table)
}
@computed get chartInstance(): ChartInterface {
// Note: when timeline handles on a LineChart are collapsed into a single handle, the
// LineChart turns into a DiscreteBar.
return this.isOnMapTab
? new MapChart({ manager: this })
: this.chartInstanceExceptMap
}
// When Map becomes a first-class chart instance, we should drop this
@computed get chartInstanceExceptMap(): ChartInterface {
const chartTypeName =
this.typeExceptWhenLineChartAndSingleTimeThenWillBeBarChart
const ChartClass =
ChartComponentClassMap.get(chartTypeName) ?? DefaultChartClass
return new ChartClass({ manager: this })
}
@computed get table(): OwidTable {
return this.tableAfterAuthorTimelineFilter
}
@computed
get tableAfterAuthorTimelineAndActiveChartTransformAndPopulationFilter(): OwidTable {
const table = this.tableAfterAuthorTimelineAndActiveChartTransform
// todo: could make these separate memoized computeds to speed up
// todo: add cross filtering. 1 dimension at a time.
return this.minPopulationFilter
? table.filterByPopulationExcept(
this.minPopulationFilter,
this.selection.selectedEntityNames
)
: table
}
@computed
private get tableAfterAllTransformsAndFilters(): OwidTable {
const { startTime, endTime } = this
const table =
this
.tableAfterAuthorTimelineAndActiveChartTransformAndPopulationFilter
if (startTime === undefined || endTime === undefined) return table
if (this.isOnMapTab)
return table.filterByTargetTimes(
[endTime],
this.map.timeTolerance ??
table.get(this.mapColumnSlug).tolerance
)
if (
this.isDiscreteBar ||
this.isLineChartThatTurnedIntoDiscreteBar ||
this.isMarimekko
)
return table.filterByTargetTimes(
[endTime],
table.get(this.yColumnSlugs[0]).tolerance
)
if (this.isSlopeChart)
return table.filterByTargetTimes([startTime, endTime])
return table.filterByTimeRange(startTime, endTime)
}
@computed get transformedTable(): OwidTable {
return this.tableAfterAllTransformsAndFilters
}
@observable.ref isMediaCard = false
@observable.ref isExportingtoSvgOrPng = false
@observable.ref tooltip?: TooltipProps
@observable isPlaying = false
@observable.ref isSelectingData = false
private get isStaging(): boolean {
if (typeof location === undefined) return false
return location.host.includes("staging")
}
@computed get editUrl(): string | undefined {
if (!this.showAdminControls && !this.isDev && !this.isStaging)
return undefined
return `${this.adminBaseUrl}/admin/${
this.manager?.editUrl ?? `charts/${this.id}/edit`
}`
}
private populationFilterToggleOption = 1e6
// Make the default filter toggle option reflect what is initially loaded.
@computed get populationFilterOption(): number {
if (this.minPopulationFilter)
this.populationFilterToggleOption = this.minPopulationFilter
return this.populationFilterToggleOption
}
// Checks if the data 1) is about countries and 2) has countries with less than the filter option. Used to partly determine whether to show the filter control.
@computed private get hasCountriesSmallerThanFilterOption(): boolean {
return this.inputTable.availableEntityNames.some(
(entityName) =>
populationMap[entityName] &&
populationMap[entityName] < this.populationFilterOption
)
}
// at startDrag, we want to show the full axis
@observable.ref useTimelineDomains = false
/**
* Whether the chart is rendered in an Admin context (e.g. on owid.cloud).
*/
@computed get useAdminAPI(): boolean {
if (typeof window === "undefined") return false
return window.admin !== undefined
}
/**
* Whether the user viewing the chart is an admin and we should show admin controls,
* like the "Edit" option in the share menu.
*/
@computed get showAdminControls(): boolean {
// This cookie is set by visiting ourworldindata.org/identifyadmin on the static site.
// There is an iframe on owid.cloud to trigger a visit to that page.
return !!Cookies.get(CookieKey.isAdmin)
}
@action.bound
private async downloadLegacyDataFromOwidVariableIds(): Promise<void> {
if (this.variableIds.length === 0)
// No data to download
return
try {
if (this.useAdminAPI) {
const json = await window.admin.getJSON(
`/api/data/variables/${this.dataFileName}`
)
this._receiveLegacyDataAndApplySelection(json)
} else {
const response = await fetch(this.dataUrl)
if (!response.ok) throw new Error(response.statusText)
const json = await response.json()
this._receiveLegacyDataAndApplySelection(json)
}
} catch (err) {
console.log(`Error fetching '${this.dataUrl}'`)
console.error(err)
}
}
@action.bound receiveLegacyData(json: LegacyVariablesAndEntityKey): void {
this._receiveLegacyDataAndApplySelection(json)
}
@action.bound private _setInputTable(
json: LegacyVariablesAndEntityKey,
legacyConfig: Partial<LegacyGrapherInterface>
): void {
const { dimensions, table } = legacyToOwidTableAndDimensions(
json,
legacyConfig
)
this.inputTable = table
// We need to reset the dimensions because some of them may have changed slugs in the legacy
// transformation (can happen when columns use targetTime)
this.setDimensionsFromConfigs(dimensions)
this.appendNewEntitySelectionOptions()
if (this.manager?.selection?.hasSelection) {
// Selection is managed externally, do nothing.
} else if (this.selection.hasSelection) {
// User has changed the selection, use theris
} else this.applyOriginalSelectionAsAuthored()
}
@action rebuildInputOwidTable(): void {
if (!this.legacyVariableDataJson) return
this._setInputTable(
this.legacyVariableDataJson,
this.legacyConfigAsAuthored
)
}
@observable private legacyVariableDataJson?: LegacyVariablesAndEntityKey
@action.bound private _receiveLegacyDataAndApplySelection(
json: LegacyVariablesAndEntityKey
): void {
this.legacyVariableDataJson = json
this.rebuildInputOwidTable()
}
@action.bound appendNewEntitySelectionOptions(): void {
const { selection } = this
const currentEntities = selection.availableEntityNameSet
const missingEntities = this.availableEntities.filter(
(entity) => !currentEntities.has(entity.entityName)
)
selection.addAvailableEntityNames(missingEntities)
}
@action.bound private applyOriginalSelectionAsAuthored(): void {
if (this.selectedEntityNames.length)
this.selection.setSelectedEntities(this.selectedEntityNames)
else if (this.selectedEntityIds.length)
this.selection.setSelectedEntitiesByEntityId(this.selectedEntityIds)
}
@observable private _baseFontSize = BASE_FONT_SIZE
@computed get baseFontSize(): number {
if (this.isMediaCard) return 24
else if (this.isExportingtoSvgOrPng) return 18
return this._baseFontSize
}
set baseFontSize(val: number) {
this._baseFontSize = val
}
// Ready to go iff we have retrieved data for every variable associated with the chart
@computed get isReady(): boolean {
return this.whatAreWeWaitingFor === ""
}
@computed get whatAreWeWaitingFor(): string {
const { newSlugs, inputTable, dimensions } = this
if (newSlugs.length || dimensions.length === 0) {
const missingColumns = newSlugs.filter(
(slug) => !inputTable.has(slug)
)
return missingColumns.length
? `Waiting for columns ${missingColumns.join(",")} in table '${
inputTable.tableSlug
}'. ${inputTable.tableDescription}`
: ""
}
if (dimensions.length > 0 && this.loadingDimensions.length === 0)
return ""
return `Waiting for dimensions ${this.loadingDimensions.join(",")}.`
}
// If we are using new slugs and not dimensions, Grapher is ready.
@computed get newSlugs(): string[] {
const { xSlug, colorSlug, sizeSlug } = this
const ySlugs = this.ySlugs ? this.ySlugs.split(" ") : []
return excludeUndefined([...ySlugs, xSlug, colorSlug, sizeSlug])
}
@computed private get loadingDimensions(): ChartDimension[] {
return this.dimensions.filter(
(dim) => !this.inputTable.has(dim.columnSlug)
)
}
@computed get isInIFrame(): boolean {
return isInIFrame()
}
@computed get times(): Time[] {
const columnSlugs = this.isOnMapTab
? [this.mapColumnSlug]
: this.yColumnSlugs
// Generate the times only after the chart transform has been applied, so that we don't show
// times on the timeline for which data may not exist, e.g. when the selected entity
// doesn't contain data for all years in the table.
// -@danielgavrilov, 2020-10-22
return this.tableAfterAuthorTimelineAndActiveChartTransformAndPopulationFilter.getTimesUniqSortedAscForColumns(
columnSlugs
)
}
@computed get startHandleTimeBound(): TimeBound {
if (this.onlySingleTimeSelectionPossible) return this.endHandleTimeBound
return this.timelineHandleTimeBounds[0]
}
set startHandleTimeBound(newValue: TimeBound) {
if (this.onlySingleTimeSelectionPossible)
this.timelineHandleTimeBounds = [newValue, newValue]
else
this.timelineHandleTimeBounds = [
newValue,
this.timelineHandleTimeBounds[1],
]
}
set endHandleTimeBound(newValue: TimeBound) {
if (this.onlySingleTimeSelectionPossible)
this.timelineHandleTimeBounds = [newValue, newValue]
else
this.timelineHandleTimeBounds = [
this.timelineHandleTimeBounds[0],
newValue,
]
}
@computed get endHandleTimeBound(): TimeBound {
return this.timelineHandleTimeBounds[1]
}
// Keeps a running cache of series colors at the Grapher level.
seriesColorMap: SeriesColorMap = new Map()
@computed get startTime(): Time | undefined {
return findClosestTime(this.times, this.startHandleTimeBound)
}
@computed get endTime(): Time | undefined {
return findClosestTime(this.times, this.endHandleTimeBound)
}
@computed private get onlySingleTimeSelectionPossible(): boolean {
return (
this.isDiscreteBar ||
this.isStackedDiscreteBar ||
this.isOnMapTab ||
this.isMarimekko
)
}
@computed get shouldLinkToOwid(): boolean {
if (
this.props.isEmbeddedInAnOwidPage ||
this.isExportingtoSvgOrPng ||
!this.isInIFrame
)
return false
return true
}
@computed.struct private get variableIds(): number[] {
return uniq(this.dimensions.map((d) => d.variableId))
}
@computed private get dataFileName(): string {
return `${this.variableIds.join("+")}.json?v=${
this.isEditor ? undefined : this.cacheTag
}`
}
@computed get dataUrl(): string {
return `${this.bakedGrapherURL ?? ""}/data/variables/${
this.dataFileName
}`
}
externalCsvLink = ""
@computed get hasOWIDLogo(): boolean {
return (
!this.hideLogo && (this.logo === undefined || this.logo === "owid")
)
}
// todo: did this name get botched in a merge?
@computed get hasFatalErrors(): boolean {
return this.relatedQuestions.some(
(question) => !!getErrorMessageRelatedQuestionUrl(question)
)
}
disposers: IReactionDisposer[] = []
@bind dispose(): void {
this.disposers.forEach((dispose) => dispose())
}
@computed get fontSize(): number {
return this.baseFontSize
}
// todo: can we remove this?
// I believe these states can only occur during editing.
@action.bound private ensureValidConfigWhenEditing(): void {
this.disposers.push(
reaction(
() => this.variableIds,
this.downloadLegacyDataFromOwidVariableIds
)
)
const disposers = [
autorun(() => {
if (!this.availableTabs.includes(this.tab))
runInAction(() => (this.tab = this.availableTabs[0]))
}),
autorun(() => {
const validDimensions = this.validDimensions
if (!isEqual(this.dimensions, validDimensions))
this.dimensions = validDimensions
}),
]
this.disposers.push(...disposers)
}
@computed private get validDimensions(): ChartDimension[] {
const { dimensions } = this
const validProperties = this.dimensionSlots.map((d) => d.property)
let validDimensions = dimensions.filter((dim) =>
validProperties.includes(dim.property)
)
this.dimensionSlots.forEach((slot) => {
if (!slot.allowMultiple)
validDimensions = uniqWith(
validDimensions,
(
a: LegacyChartDimensionInterface,
b: LegacyChartDimensionInterface
) =>
a.property === slot.property &&
a.property === b.property
)
})
return validDimensions
}
// todo: do we need this?
@computed get originUrlWithProtocol(): string {
let url = this.originUrl
if (!url.startsWith("http")) url = `https://${url}`
return url
}
@computed get overlayTab(): GrapherTabOption | undefined {
return this.overlay
}
@computed get currentTab(): GrapherTabOption {
return this.overlay ? this.overlay : this.tab
}
set currentTab(desiredTab: GrapherTabOption) {
if (
desiredTab === GrapherTabOption.chart ||
desiredTab === GrapherTabOption.map ||
desiredTab === GrapherTabOption.table
) {
this.tab = desiredTab
this.overlay = undefined
return
}
// table tab cannot be downloaded, so revert to default tab
if (desiredTab === GrapherTabOption.download && this.isOnTableTab)
this.tab = this.authorsVersion.tab ?? GrapherTabOption.chart
this.overlay = desiredTab
}
@computed get timelineHandleTimeBounds(): TimeBounds {
if (this.isOnMapTab) {
const time = maxTimeBoundFromJSONOrPositiveInfinity(this.map.time)
return [time, time]
}
return [
// Handle `undefined` values in minTime/maxTime
minTimeBoundFromJSONOrNegativeInfinity(this.minTime),
maxTimeBoundFromJSONOrPositiveInfinity(this.maxTime),
]
}
set timelineHandleTimeBounds(value: TimeBounds) {
if (this.isOnMapTab) {
this.map.time = value[1]
} else {
this.minTime = value[0]
this.maxTime = value[1]
}
}
// Get the dimension slots appropriate for this type of chart
@computed get dimensionSlots(): DimensionSlot[] {
const xAxis = new DimensionSlot(this, DimensionProperty.x)
const yAxis = new DimensionSlot(this, DimensionProperty.y)
const color = new DimensionSlot(this, DimensionProperty.color)
const size = new DimensionSlot(this, DimensionProperty.size)
if (this.isScatter) return [yAxis, xAxis, size, color]
else if (this.isMarimekko) return [yAxis, xAxis, color]
else if (this.isTimeScatter) return [yAxis, xAxis]
else if (this.isSlopeChart) return [yAxis, size, color]
return [yAxis]
}
@computed.struct get filledDimensions(): ChartDimension[] {
return this.isReady ? this.dimensions : []
}
@action.bound addDimension(config: LegacyChartDimensionInterface): void {
this.dimensions.push(new ChartDimension(config, this))
}
@action.bound setDimensionsForProperty(
property: DimensionProperty,
newConfigs: LegacyChartDimensionInterface[]
): void {
let newDimensions: ChartDimension[] = []
this.dimensionSlots.forEach((slot) => {
if (slot.property === property)
newDimensions = newDimensions.concat(
newConfigs.map((config) => new ChartDimension(config, this))
)
else newDimensions = newDimensions.concat(slot.dimensions)
})
this.dimensions = newDimensions
}
@action.bound setDimensionsFromConfigs(
configs: LegacyChartDimensionInterface[]
): void {
this.dimensions = configs.map(
(config) => new ChartDimension(config, this)
)
}
@computed get displaySlug(): string {
return this.slug ?? slugify(this.displayTitle)
}
@computed get availableTabs(): GrapherTabOption[] {
return [
this.hasChartTab && GrapherTabOption.chart,
this.hasMapTab && GrapherTabOption.map,
GrapherTabOption.table,
GrapherTabOption.sources,
GrapherTabOption.download,
].filter(identity) as GrapherTabOption[]
}
@computed get currentTitle(): string {
let text = this.displayTitle
const selectedEntityNames = this.selection.selectedEntityNames
const showTitleAnnotation = !this.hideTitleAnnotation
if (
this.tab === GrapherTabOption.chart &&
this.addCountryMode !== EntitySelectionMode.MultipleEntities &&
selectedEntityNames.length === 1 &&
(showTitleAnnotation || this.canChangeEntity)
) {
const entityStr = selectedEntityNames[0]
if (entityStr?.length) text = `${text}, ${entityStr}`
}
if (showTitleAnnotation && this.isLineChart && this.isRelativeMode)
text = "Change in " + lowerCaseFirstLetterUnlessAbbreviation(text)
if (
this.isReady &&
(showTitleAnnotation ||
(this.hasTimeline &&
(this.isLineChartThatTurnedIntoDiscreteBar ||
this.isOnMapTab)))
)
text += this.timeTitleSuffix
return text.trim()
}
@computed get hasTimeline(): boolean {
// we don't have more than one distinct time point in our data, so it doesn't make sense to show a timeline
if (this.times.length <= 1) return false
switch (this.currentTab) {
// the map tab has its own `hideTimeline` option
case GrapherTabOption.map:
return !this.map.hideTimeline
// use the chart-level `hideTimeline` option for the table, too
case GrapherTabOption.table:
return !this.hideTimeline
// StackedBar, StackedArea, and DiscreteBar charts never display a timeline
case GrapherTabOption.chart:
return (
!this.hideTimeline &&
!(
this.isStackedBar ||
this.isStackedArea ||
this.isDiscreteBar
)
)
// never show a timeline while we're showing one of these two overlays
case GrapherTabOption.download:
case GrapherTabOption.sources:
return false
}
}
@computed private get areHandlesOnSameTime(): boolean {
const times = this.tableAfterAuthorTimelineFilter.timeColumn.uniqValues
const [start, end] = this.timelineHandleTimeBounds.map((time) =>
findClosestTime(times, time)
)
return start === end
}
@computed get mapColumnSlug(): string {
const mapColumnSlug = this.map.columnSlug
// If there's no mapColumnSlug or there is one but it's not in the dimensions array, use the first ycolumn
if (
!mapColumnSlug ||
!this.dimensions.some((dim) => dim.columnSlug === mapColumnSlug)
)
return this.yColumnSlug!
return mapColumnSlug
}
getColumnForProperty(property: DimensionProperty): CoreColumn | undefined {
return this.dimensions.find((dim) => dim.property === property)?.column
}
getSlugForProperty(property: DimensionProperty): string | undefined {
return this.dimensions.find((dim) => dim.property === property)
?.columnSlug
}
@computed get yColumnsFromDimensions(): CoreColumn[] {
return this.filledDimensions
.filter((dim) => dim.property === DimensionProperty.y)
.map((dim) => dim.column)
}
@computed get yColumnSlugsInSelectionOrder(): string[] {
return this.selectedColumnSlugs?.length
? this.selectedColumnSlugs
: this.yColumnSlugs
}
@computed get yColumnSlugs(): string[] {
return this.ySlugs
? this.ySlugs.split(" ")
: this.dimensions
.filter((dim) => dim.property === DimensionProperty.y)
.map((dim) => dim.columnSlug)
}
@computed get yColumnSlug(): string | undefined {
return this.ySlugs
? this.ySlugs.split(" ")[0]
: this.getSlugForProperty(DimensionProperty.y)
}
@computed get xColumnSlug(): string | undefined {
return this.xSlug ?? this.getSlugForProperty(DimensionProperty.x)
}
@computed get sizeColumnSlug(): string | undefined {
return this.sizeSlug ?? this.getSlugForProperty(DimensionProperty.size)
}
@computed get colorColumnSlug(): string | undefined {
return (
this.colorSlug ?? this.getSlugForProperty(DimensionProperty.color)
)
}
@computed get yScaleType(): ScaleType | undefined {
return this.yAxis.scaleType
}
@computed get xScaleType(): ScaleType | undefined {
return this.xAxis.scaleType
}
@computed private get timeTitleSuffix(): string {
const timeColumn = this.table.timeColumn
if (timeColumn.isMissing) return "" // Do not show year until data is loaded
const { startTime, endTime } = this
if (startTime === undefined || endTime === undefined) return ""
const time =
startTime === endTime
? timeColumn.formatValue(startTime)
: timeColumn.formatValue(startTime) +
" to " +
timeColumn.formatValue(endTime)
return ", " + time
}
@computed get sourcesLine(): string {
return this.sourceDesc ?? this.defaultSourcesLine
}
// Columns that are used as a dimension in the currently active view
@computed get activeColumnSlugs(): string[] {
const { yColumnSlugs, xColumnSlug, sizeColumnSlug, colorColumnSlug } =
this
return excludeUndefined([
...yColumnSlugs,
xColumnSlug,
sizeColumnSlug,
colorColumnSlug,
])
}
@computed get columnsWithSources(): CoreColumn[] {
const { yColumnSlugs, xColumnSlug, sizeColumnSlug, colorColumnSlug } =
this
const columnSlugs = [...yColumnSlugs]
if (xColumnSlug !== undefined) columnSlugs.push(xColumnSlug)
// exclude "Total population (Gapminder, HYDE & UN)" if its used as the size dimension in a scatter plot
if (sizeColumnSlug !== undefined && sizeColumnSlug != "72")
columnSlugs.push(sizeColumnSlug)
// exclude "Countries Continent" if its used as the color dimension in a scatter plot, slope chart etc.
if (colorColumnSlug !== undefined && colorColumnSlug != "123")
columnSlugs.push(colorColumnSlug)
return this.inputTable
.getColumns(uniq(columnSlugs))
.filter((column) => !!column.source.name)
}
@computed private get defaultSourcesLine(): string {
let sourceNames = this.columnsWithSources.map(
(column) => column.source.name ?? ""
)
// Shorten automatic source names for certain major sources: todo: this sort of thing we could do in a smarter editor, and not at runtime
sourceNames = sourceNames.map((sourceName) => {
for (const majorSource of [
"World Bank – WDI",
"World Bank",
"ILOSTAT",
]) {
if (
sourceName.startsWith(majorSource) &&
!sourceName.match(
new RegExp(
"^" + majorSource + "\\s+(based on|and)",
"gi"
)
)
)
return majorSource
}
return sourceName
})
return uniq(sourceNames).join(", ")
}
@computed private get axisDimensions(): ChartDimension[] {
return this.filledDimensions.filter(
(dim) =>
dim.property === DimensionProperty.y ||
dim.property === DimensionProperty.x
)
}
// todo: remove when we remove dimensions
@computed private get yColumnsFromDimensionsOrSlugsOrAuto(): CoreColumn[] {
return this.yColumnsFromDimensions.length
? this.yColumnsFromDimensions
: this.table.getColumns(autoDetectYColumnSlugs(this))
}
@computed private get defaultTitle(): string {
const yColumns = this.yColumnsFromDimensionsOrSlugsOrAuto
if (this.isScatter)
return this.axisDimensions
.map((dimension) => dimension.column.displayName)
.join(" vs. ")
const uniqueDatasetNames = uniq(
excludeUndefined(
yColumns.map((col) => (col.def as OwidColumnDef).datasetName)
)
)
if (this.hasMultipleYColumns && uniqueDatasetNames.length === 1)
return uniqueDatasetNames[0]
if (yColumns.length === 2)
return yColumns.map((col) => col.displayName).join(" and ")
return yColumns.map((col) => col.displayName).join(", ")
}
@computed get displayTitle(): string {
return this.title ?? this.defaultTitle
}
// Returns an object ready to be serialized to JSON
@computed get object(): GrapherInterface {
return this.toObject()
}
@computed
get typeExceptWhenLineChartAndSingleTimeThenWillBeBarChart(): ChartTypeName {
// Switch to bar chart if a single year is selected. Todo: do we want to do this?
return this.isLineChartThatTurnedIntoDiscreteBar
? ChartTypeName.DiscreteBar
: this.type
}
@computed get isLineChart(): boolean {
return this.type === ChartTypeName.LineChart
}
@computed get isScatter(): boolean {
return this.type === ChartTypeName.ScatterPlot
}
@computed get isTimeScatter(): boolean {
return this.type === ChartTypeName.TimeScatter
}
@computed get isStackedArea(): boolean {
return this.type === ChartTypeName.StackedArea
}
@computed get isSlopeChart(): boolean {
return this.type === ChartTypeName.SlopeChart
}
@computed get isDiscreteBar(): boolean {
return this.type === ChartTypeName.DiscreteBar
}
@computed get isStackedBar(): boolean {
return this.type === ChartTypeName.StackedBar
}
@computed get isMarimekko(): boolean {
return this.type === ChartTypeName.Marimekko
}
@computed get isStackedDiscreteBar(): boolean {
return this.type === ChartTypeName.StackedDiscreteBar
}
@computed get isLineChartThatTurnedIntoDiscreteBar(): boolean {
return this.isLineChart && this.areHandlesOnSameTime
}
@computed get activeColorScale(): ColorScale | undefined {
const chart = this.chartInstance
return chart.colorScale
}
@computed get activeColorScaleExceptMap(): ColorScale | undefined {
const chart = this.chartInstanceExceptMap
return chart.colorScale
}
@computed get supportsMultipleYColumns(): boolean {
return !(this.isScatter || this.isTimeScatter || this.isSlopeChart)
}
@computed private get xDimension(): ChartDimension | undefined {
return this.filledDimensions.find(
(d) => d.property === DimensionProperty.x
)
}
// todo: this is only relevant for scatter plots and Marimekko. move to scatter plot class?
// todo: remove this. Should be done as a simple column transform at the data level.
// Possible to override the x axis dimension to target a special year
// In case you want to graph say, education in the past and democracy today https://ourworldindata.org/grapher/correlation-between-education-and-democracy
@computed get xOverrideTime(): number | undefined {
return this.xDimension?.targetYear
}
// todo: this is only relevant for scatter plots and Marimekko. move to scatter plot class?
set xOverrideTime(value: number | undefined) {
this.xDimension!.targetYear = value
}
@computed get idealBounds(): Bounds {
return this.isMediaCard
? new Bounds(0, 0, 1200, 630)
: new Bounds(0, 0, 850, 600)
}
@computed get hasYDimension(): boolean {
return this.dimensions.some((d) => d.property === DimensionProperty.y)
}
get staticSVG(): string {
const _isExportingtoSvgOrPng = this.isExportingtoSvgOrPng
this.isExportingtoSvgOrPng = true
const staticSvg = ReactDOMServer.renderToStaticMarkup(
<StaticCaptionedChart manager={this} bounds={this.idealBounds} />
)
this.isExportingtoSvgOrPng = _isExportingtoSvgOrPng
return staticSvg
}
@computed get mapConfig(): MapConfig {
return this.map
}
@computed get cacheTag(): string {
return this.version.toString()
}
@computed get mapIsClickable(): boolean {
return (
this.hasChartTab &&
(this.isLineChart || this.isScatter) &&
!isMobile()
)
}
@computed get relativeToggleLabel(): string {
if (this.isScatter || this.isTimeScatter) return "Average annual change"
else if (this.isLineChart) return "Relative change"
return "Relative"
}
// NB: The timeline scatterplot in relative mode calculates changes relative
// to the lower bound year rather than creating an arrow chart
@computed get isRelativeMode(): boolean {
return this.stackMode === StackMode.relative
}
@computed get canToggleRelativeMode(): boolean {
if (this.isLineChart)
return (
!this.hideRelativeToggle &&
!this.areHandlesOnSameTime &&
this.yScaleType !== ScaleType.log
)
// actually trying to exclude relative mode with just one metric
if (
this.isStackedDiscreteBar &&
this.facetStrategy !== FacetStrategy.none
)
return false
return !this.hideRelativeToggle
}
// Filter data to what can be display on the map (across all times)
@computed get mappableData() {
return this.inputTable
.get(this.mapColumnSlug)
.owidRows.filter((row) => isOnTheMap(row.entityName))
}
static renderGrapherIntoContainer(
config: GrapherProgrammaticInterface,
containerNode: Element
): Grapher | null {
const grapherInstanceRef = React.createRef<Grapher>()
let ErrorBoundary = React.Fragment // use React.Fragment as a sort of default error boundary if Bugsnag is not available
if (Bugsnag && (Bugsnag as any)._client) {
ErrorBoundary =
Bugsnag.getPlugin("react").createErrorBoundary(React)
}
const setBoundsFromContainerAndRender = (): void => {
const props: GrapherProgrammaticInterface = {
...config,
bounds: Bounds.fromRect(containerNode.getBoundingClientRect()),
}
ReactDOM.render(
<ErrorBoundary>
<Grapher ref={grapherInstanceRef} {...props} />
</ErrorBoundary>,
containerNode
)
}
setBoundsFromContainerAndRender()
window.addEventListener(
"resize",
throttle(setBoundsFromContainerAndRender, 400)
)
return grapherInstanceRef.current
}
static renderSingleGrapherOnGrapherPage(
jsonConfig: GrapherInterface
): void {
const container = document.getElementsByTagName("figure")[0]
try {
Grapher.renderGrapherIntoContainer(
{
...jsonConfig,
bindUrlToWindow: true,
enableKeyboardShortcuts: true,
queryStr: window.location.search,
},
container
)
} catch (err) {
container.innerHTML = `<img src="/grapher/exports/${jsonConfig.slug}.svg"/><p>Unable to load interactive visualization</p>`
container.setAttribute("id", "fallback")
throw err
}
}
@computed get isMobile(): boolean {
return isMobile()
}
@computed private get bounds(): Bounds {
return this.props.bounds ?? DEFAULT_BOUNDS
}
@computed private get isPortrait(): boolean {
return this.bounds.width < this.bounds.height && this.bounds.width < 850
}
@computed private get widthForDeviceOrientation(): number {
return this.isPortrait ? 400 : 680
}
@computed private get heightForDeviceOrientation(): number {
return this.isPortrait ? 640 : 480
}
@computed private get useIdealBounds(): boolean {
const {
isEditor,
isExportingtoSvgOrPng,
bounds,
widthForDeviceOrientation,
heightForDeviceOrientation,
isInIFrame,
} = this
// For these, defer to the bounds that is set externally
if (
this.props.isEmbeddedInAnOwidPage ||
this.props.manager ||
isInIFrame
)
return false
// If the user is using interactive version and then goes to export chart, use current bounds to maintain WSYIWYG
if (isExportingtoSvgOrPng) return false
// todo: can remove this if we drop old adminSite editor
if (isEditor) return true
// If the available space is very small, we use all of the space given to us
if (
bounds.height < heightForDeviceOrientation ||
bounds.width < widthForDeviceOrientation
)
return false
return true
}
// If we have a big screen to be in, we can define our own aspect ratio and sit in the center
@computed private get scaleToFitIdeal(): number {
return Math.min(
(this.bounds.width * 0.95) / this.widthForDeviceOrientation,
(this.bounds.height * 0.95) / this.heightForDeviceOrientation
)
}
// These are the final render dimensions
// Todo: add explanation around why isExporting removes 5 px
@computed private get renderWidth(): number {
return this.useIdealBounds
? this.widthForDeviceOrientation * this.scaleToFitIdeal
: this.bounds.width - (this.isExportingtoSvgOrPng ? 0 : 5)
}
@computed private get renderHeight(): number {
return this.useIdealBounds
? this.heightForDeviceOrientation * this.scaleToFitIdeal
: this.bounds.height - (this.isExportingtoSvgOrPng ? 0 : 5)
}
@computed get tabBounds(): Bounds {
const bounds = new Bounds(0, 0, this.renderWidth, this.renderHeight)
return this.isExportingtoSvgOrPng
? bounds
: bounds.padBottom(this.footerControlsHeight)
}
@observable.ref private popups: JSX.Element[] = []
base: React.RefObject<HTMLDivElement> = React.createRef()
@computed get containerElement(): HTMLDivElement | undefined {
return this.base.current || undefined
}
@observable private hasBeenVisible = false
@observable private uncaughtError?: Error
@action.bound setError(err: Error): void {
this.uncaughtError = err
}
@action.bound clearErrors(): void {
this.uncaughtError = undefined
}
// todo: clean up this popup stuff
addPopup(vnode: JSX.Element): void {
this.popups = this.popups.concat([vnode])
}
removePopup(vnodeType: JSX.Element): void {
this.popups = this.popups.filter((d) => !(d.type === vnodeType))
}
@computed private get isOnTableTab(): boolean {
return this.tab === GrapherTabOption.table
}
private renderPrimaryTab(): JSX.Element | undefined {
if (this.isChartOrMapTab) return <CaptionedChart manager={this} />
const { tabBounds } = this
if (this.isOnTableTab)
// todo: should this "Div" and styling just be in DataTable class?
return (
<div
className="tableTab"
style={{ ...tabBounds.toCSS(), position: "absolute" }}
>
<DataTable bounds={tabBounds} manager={this} />
</div>
)
return undefined
}
private renderOverlayTab(): JSX.Element | undefined {
const bounds = this.tabBounds
if (this.overlayTab === GrapherTabOption.sources)
return (
<SourcesTab key="sourcesTab" bounds={bounds} manager={this} />
)
if (this.overlayTab === GrapherTabOption.download)
return (
<DownloadTab key="downloadTab" bounds={bounds} manager={this} />
)
return undefined
}
private get commandPalette(): JSX.Element | null {
return this.props.enableKeyboardShortcuts ? (
<CommandPalette commands={this.keyboardShortcuts} display="none" />
) : null
}
formatTimeFn(time: Time): string {
return this.inputTable.timeColumnFormatFunction(time)
}
@action.bound private toggleTabCommand(): void {
this.currentTab = next(this.availableTabs, this.currentTab)
}
@action.bound private togglePlayingCommand(): void {
this.timelineController.togglePlay()
}
selection =
this.manager?.selection ??
new SelectionArray(
this.props.selectedEntityNames ?? [],
this.props.table?.availableEntities ?? []
)
@computed get availableEntities() {
return this.tableForSelection.availableEntities
}
private get keyboardShortcuts(): Command[] {
const temporaryFacetTestCommands = range(0, 10).map((num) => {
return {
combo: `${num}`,
fn: (): void => this.randomSelection(num),
}
})
const shortcuts = [
...temporaryFacetTestCommands,
{
combo: "t",
fn: (): void => this.toggleTabCommand(),
title: "Toggle tab",
category: "Navigation",
},
{
combo: "?",
fn: (): void => CommandPalette.togglePalette(),
title: `Toggle Help`,
category: "Navigation",
},
{
combo: "a",
fn: (): void | SelectionArray =>
this.selection.hasSelection
? this.selection.clearSelection()
: this.selection.selectAll(),
title: this.selection.hasSelection
? `Select None`
: `Select All`,
category: "Selection",
},
{
combo: "f",
fn: (): void => this.toggleFilterAllCommand(),
title: "Hide unselected",
category: "Selection",
},
{
combo: "p",
fn: (): void => this.togglePlayingCommand(),
title: this.isPlaying ? `Pause` : `Play`,
category: "Timeline",
},
{
combo: "f",
fn: (): void => this.toggleFacetControlVisibility(),
title: `Toggle Faceting`,
category: "Chart",
},
{
combo: "l",
fn: (): void => this.toggleYScaleTypeCommand(),
title: "Toggle Y log/linear",
category: "Chart",
},
{
combo: "esc",
fn: (): void => this.clearErrors(),
},
{
combo: "z",
fn: (): void => this.toggleTimelineCommand(),
title: "Latest/Earliest/All period",
category: "Timeline",
},
{
combo: "shift+o",
fn: (): void => this.clearQueryParams(),
title: "Reset to original",
category: "Navigation",
},
]
if (this.slideShow) {
const slideShow = this.slideShow
shortcuts.push({
combo: "right",
fn: () => slideShow.playNext(),
title: "Next chart",
category: "Browse",
})
shortcuts.push({
combo: "left",
fn: () => slideShow.playPrevious(),
title: "Previous chart",
category: "Browse",
})
}
return shortcuts
}
@observable slideShow?: SlideShowController<any>
@action.bound private toggleTimelineCommand(): void {
// Todo: add tests for this
this.setTimeFromTimeQueryParam(
next(["latest", "earliest", ".."], this.timeParam!)
)
}
@action.bound private toggleFilterAllCommand(): void {
this.minPopulationFilter =
this.minPopulationFilter === 2e9 ? undefined : 2e9
}
@action.bound private toggleYScaleTypeCommand(): void {
this.yAxis.scaleType = next(
[ScaleType.linear, ScaleType.log],
this.yAxis.scaleType
)
}
@action.bound private toggleFacetStrategy(): void {
this.facetStrategy = next(
this.availableFacetStrategies,
this.facetStrategy
)
}
@action.bound private toggleFacetControlVisibility(): void {
this.hideFacetControl = !this.hideFacetControl
}
@computed get showFacetYDomainToggle(): boolean {
// don't offer to make the y range relative if the range is discrete
return (
this.facetStrategy !== FacetStrategy.none &&
!this.isStackedDiscreteBar
)
}
@computed get _sortConfig(): Readonly<SortConfig> {
return {
sortBy: this.sortBy ?? SortBy.total,
sortOrder: this.sortOrder ?? SortOrder.desc,
sortColumnSlug: this.sortColumnSlug,
}
}
@computed get sortConfig(): SortConfig {
const sortConfig = { ...this._sortConfig }
// In relative mode, where the values for every entity sum up to 100%, sorting by total
// doesn't make sense. It's also jumpy because of some rounding errors. For this reason,
// we sort by entity name instead.
// Marimekko charts are special and there we don't do this forcing of sort order
if (
!this.isMarimekko &&
this.isRelativeMode &&
sortConfig.sortBy === SortBy.total
) {
sortConfig.sortBy = SortBy.entityName
sortConfig.sortOrder = SortOrder.asc
}
return sortConfig
}
@computed private get hasMultipleYColumns(): boolean {
return this.yColumnSlugs.length > 1
}
@computed get selectedColumnSlugs(): ColumnSlug[] {
const { selectedData } = this.legacyConfigAsAuthored
const dimensions = this.filledDimensions
if (selectedData) {
const columnSlugs = selectedData.map((item) => {
const columnSlug = dimensions[item.index]?.columnSlug
if (!columnSlug)
console.warn(
`Couldn't find specified dimension in chart config`,
item
)
return columnSlug
})
return uniq(excludeUndefined(columnSlugs))
}
return []
}
@computed get availableFacetStrategies(): FacetStrategy[] {
const strategies: FacetStrategy[] = [FacetStrategy.none]
const numNonProjectedColumns =
this.yColumnsFromDimensionsOrSlugsOrAuto.filter(
(c) => !c.display?.isProjection
).length
if (
// multiple metrics (excluding projections)
numNonProjectedColumns > 1 &&
// more than one data point per metric
this.transformedTable.numRows > 1
) {
strategies.push(FacetStrategy.metric)
}
if (
// multiple entities
this.selection.numSelectedEntities > 1 &&
// more than one data point per entity
this.transformedTable.numRows > this.selection.numSelectedEntities
) {
strategies.push(FacetStrategy.entity)
}
return strategies
}
private disableAutoFaceting = true // turned off for now
// the actual facet setting used by a chart, potentially overriding selectedFacetStrategy
@computed get facetStrategy(): FacetStrategy {
if (
this.selectedFacetStrategy &&
this.availableFacetStrategies.includes(this.selectedFacetStrategy)
)
return this.selectedFacetStrategy
if (this.disableAutoFaceting) return FacetStrategy.none
// Auto facet on SingleEntity charts with multiple selected entities
if (
this.addCountryMode === EntitySelectionMode.SingleEntity &&
this.selection.numSelectedEntities > 1
)
return FacetStrategy.entity
// Auto facet when multiple slugs and multiple entities selected. todo: not sure if this is correct.
if (
this.addCountryMode === EntitySelectionMode.MultipleEntities &&
this.hasMultipleYColumns &&
this.selection.numSelectedEntities > 1
)
return FacetStrategy.metric
return FacetStrategy.none
}
set facetStrategy(facet: FacetStrategy) {
this.selectedFacetStrategy = facet
if (
this.isStackedDiscreteBar &&
this.selectedFacetStrategy !== FacetStrategy.none
) {
// actually trying to exclude relative mode with just one metric
this.stackMode = StackMode.absolute
}
}
@action.bound randomSelection(num: number): void {
// Continent, Population, GDP PC, GDP, PopDens, UN, Language, etc.
this.clearErrors()
const currentSelection = this.selection.selectedEntityNames.length
const newNum = num ? num : currentSelection ? currentSelection * 2 : 10
this.selection.setSelectedEntities(
sampleFrom(this.selection.availableEntityNames, newNum, Date.now())
)
}
private renderError(): JSX.Element {
return (
<div
title={this.uncaughtError?.message}
style={{
width: "100%",
height: "100%",
position: "relative",
display: "flex",
flexDirection: "column",
justifyContent: "center",
textAlign: "center",
lineHeight: 1.5,
padding: "3rem",
}}
>
<p style={{ color: "#cc0000", fontWeight: 700 }}>
<FontAwesomeIcon icon={faExclamationTriangle} />
{ThereWasAProblemLoadingThisChart}
</p>
<p>
We have been notified of this error, please check back later
whether it's been fixed. If the error persists, get in touch
with us at{" "}
<a
href={`mailto:info@ourworldindata.org?subject=Broken chart on page ${window.location.href}`}
>
info@ourworldindata.org
</a>
.
</p>
{this.uncaughtError && this.uncaughtError.message && (
<pre style={{ fontSize: "11px" }}>
Error: {this.uncaughtError.message}
</pre>
)}
</div>
)
}
@action.bound
resetAnnotation(): void {
this.renderAnnotation(undefined)
}
@action.bound
renderAnnotation(annotation: Annotation | undefined): void {
this.setAuthoredVersion(this.props)
this.reset()
this.updateFromObject({ ...this.props })
this.populateFromQueryParams(
legacyToCurrentGrapherQueryParams(this.props.queryStr ?? "")
)
this.annotation = annotation
}
render(): JSX.Element | undefined {
const { isExportingtoSvgOrPng, isPortrait } = this
// TODO how to handle errors in exports?
// TODO tidy this up
if (isExportingtoSvgOrPng) return this.renderPrimaryTab() // todo: remove this? should have a simple toStaticSVG for importing.
const { renderWidth, renderHeight } = this
const style = {
width: renderWidth,
height: renderHeight,
fontSize: this.baseFontSize,
}
const classes = classNames(
"GrapherComponent",
isExportingtoSvgOrPng && "isExportingToSvgOrPng",
isPortrait && "GrapherPortraitClass"
)
return (
<div ref={this.base} className={classes} style={style}>
{this.commandPalette}
{this.uncaughtError ? this.renderError() : this.renderReady()}
</div>
)
}
private renderReady(): JSX.Element {
return (
<>
{this.hasBeenVisible && this.renderPrimaryTab()}
<FooterControls manager={this} />
{this.renderOverlayTab()}
{this.popups}
<TooltipView
width={this.renderWidth}
height={this.renderHeight}
tooltipProvider={this}
/>
{this.isSelectingData && (
<EntitySelectorModal
canChangeEntity={this.canChangeEntity}
selectionArray={this.selection}
key="entitySelector"
isMobile={this.isMobile}
onDismiss={action(() => (this.isSelectingData = false))}
/>
)}
</>
)
}
// Chart should only render SVG when it's on the screen
@action.bound private checkVisibility(): void {
if (!this.hasBeenVisible && isVisible(this.base.current))
this.hasBeenVisible = true
}
@action.bound private setBaseFontSize(): void {
const { renderWidth } = this
if (renderWidth <= 400) this.baseFontSize = 14
else if (renderWidth < 1080) this.baseFontSize = 16
else if (renderWidth >= 1080) this.baseFontSize = 18
}
// Binds chart properties to global window title and URL. This should only
// ever be invoked from top-level JavaScript.
private bindToWindow(): void {
// There is a surprisingly considerable performance overhead to updating the url
// while animating, so we debounce to allow e.g. smoother timelines
const pushParams = (): void =>
setWindowQueryStr(queryParamsToStr(this.changedParams))
const debouncedPushParams = debounce(pushParams, 100)
reaction(
() => this.changedParams,
() => (this.debounceMode ? debouncedPushParams() : pushParams())
)
autorun(() => (document.title = this.currentTitle))
}
componentDidMount(): void {
window.addEventListener("scroll", this.checkVisibility)
this.setBaseFontSize()
this.checkVisibility()
exposeInstanceOnWindow(this, "grapher")
if (this.props.bindUrlToWindow) this.bindToWindow()
if (this.props.enableKeyboardShortcuts) this.bindKeyboardShortcuts()
}
private _shortcutsBound = false
private bindKeyboardShortcuts(): void {
if (this._shortcutsBound) return
this.keyboardShortcuts.forEach((shortcut) => {
Mousetrap.bind(shortcut.combo, () => {
shortcut.fn()
this.analytics.logKeyboardShortcut(
shortcut.title || "",
shortcut.combo
)
return false
})
})
this._shortcutsBound = true
}
private unbindKeyboardShortcuts(): void {
if (!this._shortcutsBound) return
this.keyboardShortcuts.forEach((shortcut) => {
Mousetrap.unbind(shortcut.combo)
})
this._shortcutsBound = false
}
componentWillUnmount(): void {
this.unbindKeyboardShortcuts()
window.removeEventListener("scroll", this.checkVisibility)
this.dispose()
}
componentDidUpdate(): void {
this.setBaseFontSize()
this.checkVisibility()
}
componentDidCatch(error: Error, info: any): void {
this.setError(error)
this.analytics.logGrapherViewError(error, info)
}
@observable isShareMenuActive = false
@computed get hasRelatedQuestion(): boolean {
if (!this.relatedQuestions.length) return false
const question = this.relatedQuestions[0]
return !!question && !!question.text && !!question.url
}
@computed private get footerControlsLines(): number {
return this.hasTimeline ? 2 : 1
}
@computed get footerControlsHeight(): number {
const footerRowHeight = 32 // todo: cleanup. needs to keep in sync with grapher.scss' $footerRowHeight
return (
this.footerControlsLines * footerRowHeight +
(this.hasRelatedQuestion ? 20 : 0)
)
}
@action.bound clearQueryParams(): void {
const { authorsVersion } = this
this.tab = authorsVersion.tab
this.xAxis.scaleType = authorsVersion.xAxis.scaleType
this.yAxis.scaleType = authorsVersion.yAxis.scaleType
this.stackMode = authorsVersion.stackMode
this.zoomToSelection = authorsVersion.zoomToSelection
this.minPopulationFilter = authorsVersion.minPopulationFilter
this.compareEndPointsOnly = authorsVersion.compareEndPointsOnly
this.minTime = authorsVersion.minTime
this.maxTime = authorsVersion.maxTime
this.map.time = authorsVersion.map.time
this.map.projection = authorsVersion.map.projection
this.selection.clearSelection()
this.applyOriginalSelectionAsAuthored()
}
// Todo: come up with a more general pattern?
// The idea here is to reset the Grapher to a blank slate, so that if you updateFromObject and the object contains some blanks, those blanks
// won't overwrite defaults (like type == LineChart). RAII would probably be better, but this works for now.
@action.bound reset(): void {
const grapher = new Grapher()
this.title = grapher.title
this.subtitle = grapher.subtitle
this.note = grapher.note
this.type = grapher.type
this.ySlugs = grapher.ySlugs
this.xSlug = grapher.xSlug
this.colorSlug = grapher.colorSlug
this.sizeSlug = grapher.sizeSlug
this.hasMapTab = grapher.hasMapTab
this.selectedFacetStrategy = FacetStrategy.none
this.hasChartTab = grapher.hasChartTab
this.map = grapher.map
this.yAxis.scaleType = grapher.yAxis.scaleType
this.yAxis.min = grapher.yAxis.min
this.sortBy = grapher.sortBy
this.sortOrder = grapher.sortOrder
this.sortColumnSlug = grapher.sortColumnSlug
this.hideRelativeToggle = grapher.hideRelativeToggle
this.stackMode = grapher.stackMode
this.hideTotalValueLabel = grapher.hideTotalValueLabel
}
debounceMode = false
@computed.struct get allParams(): GrapherQueryParams {
const params: GrapherQueryParams = {}
params.tab = this.tab
params.xScale = this.xAxis.scaleType
params.yScale = this.yAxis.scaleType
params.stackMode = this.stackMode
params.zoomToSelection = this.zoomToSelection ? "true" : undefined
params.minPopulationFilter = this.minPopulationFilter?.toString()
params.endpointsOnly = this.compareEndPointsOnly ? "1" : "0"
params.time = this.timeParam
params.region = this.map.projection
params.facet = this.selectedFacetStrategy
params.uniformYAxis =
this.yAxis.facetDomain === FacetAxisDomain.independent ? "0" : "1"
return setSelectedEntityNamesParam(
Url.fromQueryParams(params),
this.selectedEntitiesIfDifferentThanAuthors
).queryParams
}
// Todo: move all Graphers to git. Upgrade the selection property; delete the entityId stuff, and remove this.
@computed private get selectedEntitiesIfDifferentThanAuthors():
| EntityName[]
| undefined {
const authoredConfig = this.legacyConfigAsAuthored
const originalSelectedEntityIds =
authoredConfig.selectedData?.map((row) => row.entityId) || []
const currentSelectedEntityIds = this.selection.allSelectedEntityIds
const entityIdsThatTheUserDeselected = difference(
currentSelectedEntityIds,
originalSelectedEntityIds
)
if (
currentSelectedEntityIds.length !==
originalSelectedEntityIds.length ||
entityIdsThatTheUserDeselected.length
)
return this.selection.selectedEntityNames
return undefined
}
// Autocomputed url params to reflect difference between current grapher state
// and original config state
@computed.struct get changedParams(): Partial<GrapherQueryParams> {
return differenceObj(this.allParams, this.authorsVersion.allParams)
}
// If you want to compare current state against the published grapher.
@computed private get authorsVersion(): Grapher {
return new Grapher({
...this.legacyConfigAsAuthored,
manager: undefined,
manuallyProvideData: true,
queryStr: "",
})
}
@computed get queryStr(): string {
return queryParamsToStr(this.changedParams)
}
@computed get baseUrl(): string | undefined {
return this.isPublished
? `${this.bakedGrapherURL ?? "/grapher"}/${this.displaySlug}`
: undefined
}
@computed private get manager(): GrapherManager | undefined {
return this.props.manager
}
// Get the full url representing the canonical location of this grapher state
@computed get canonicalUrl(): string | undefined {
return (
this.manager?.canonicalUrl ??
(this.baseUrl ? this.baseUrl + this.queryStr : undefined)
)
}
@computed get embedUrl(): string | undefined {
return this.manager?.embedDialogUrl ?? this.canonicalUrl
}
@computed get embedDialogAdditionalElements():
| React.ReactElement
| undefined {
return this.manager?.embedDialogAdditionalElements
}
@computed private get hasUserChangedTimeHandles(): boolean {
const authorsVersion = this.authorsVersion
return (
this.minTime !== authorsVersion.minTime ||
this.maxTime !== authorsVersion.maxTime
)
}
@computed private get hasUserChangedMapTimeHandle(): boolean {
return this.map.time !== this.authorsVersion.map.time
}
@computed get timeParam(): string | undefined {
const { timeColumn } = this.table
const formatTime = (t: Time) =>
timeBoundToTimeBoundString(
t,
timeColumn instanceof ColumnTypeMap.Day
)
if (this.isOnMapTab) {
return this.map.time !== undefined &&
this.hasUserChangedMapTimeHandle
? formatTime(this.map.time)
: undefined
}
if (!this.hasUserChangedTimeHandles) return undefined
const [startTime, endTime] =
this.timelineHandleTimeBounds.map(formatTime)
return startTime === endTime ? startTime : `${startTime}..${endTime}`
}
msPerTick = DEFAULT_MS_PER_TICK
timelineController = new TimelineController(this)
onPlay(): void {
this.analytics.logGrapherTimelinePlay(this.slug)
}
// todo: restore this behavior??
onStartPlayOrDrag(): void {
this.debounceMode = true
this.useTimelineDomains = true
}
onStopPlayOrDrag(): void {
this.debounceMode = false
this.useTimelineDomains = false
}
@computed get disablePlay(): boolean {
return this.isSlopeChart
}
formatTime(value: Time): string {
const timeColumn = this.table.timeColumn
if (timeColumn.isMissing)
return this.table.timeColumnFormatFunction(value)
return isMobile()
? timeColumn.formatValueForMobile(value)
: timeColumn.formatValue(value)
}
@computed get showSmallCountriesFilterToggle(): boolean {
return this.isScatter && this.hasCountriesSmallerThanFilterOption
}
@computed get showYScaleToggle(): boolean | undefined {
if (this.isRelativeMode) return false
if (this.isStackedArea || this.isStackedBar) return false // We currently do not have these charts with log scale
return this.yAxis.canChangeScaleType
}
@computed get showXScaleToggle(): boolean | undefined {
if (this.isRelativeMode) return false
return this.xAxis.canChangeScaleType
}
@computed get showZoomToggle(): boolean {
return this.isScatter && this.selection.hasSelection
}
@computed get showAbsRelToggle(): boolean {
if (!this.canToggleRelativeMode) return false
if (this.isScatter)
return this.xOverrideTime === undefined && this.hasTimeline
return (
this.isStackedArea ||
this.isStackedDiscreteBar ||
this.isScatter ||
this.isLineChart ||
this.isMarimekko
)
}
@computed get showNoDataAreaToggle(): boolean {
return this.isMarimekko
}
@computed get showHighlightToggle(): boolean {
return this.isScatter && !!this.highlightToggle
}
@computed get showChangeEntityButton(): boolean {
return !this.hideEntityControls && this.canChangeEntity
}
@computed get showAddEntityButton(): boolean {
return (
!this.hideEntityControls &&
this.canSelectMultipleEntities &&
(this.isLineChart ||
this.isStackedArea ||
this.isDiscreteBar ||
this.isStackedDiscreteBar)
)
}
@computed get showSelectEntitiesButton(): boolean {
return (
!this.hideEntityControls &&
this.addCountryMode !== EntitySelectionMode.Disabled &&
this.numSelectableEntityNames > 1 &&
!this.showAddEntityButton &&
!this.showChangeEntityButton
)
}
@computed get canSelectMultipleEntities(): boolean {
if (this.numSelectableEntityNames < 2) return false
if (this.addCountryMode === EntitySelectionMode.MultipleEntities)
return true
if (
this.addCountryMode === EntitySelectionMode.SingleEntity &&
this.facetStrategy !== FacetStrategy.none
)
return true
return false
}
// This is just a helper method to return the correct table for providing entity choices. We want to
// provide the root table, not the transformed table.
// A user may have added time or other filters that would filter out all rows from certain entities, but
// we may still want to show those entities as available in a picker. We also do not want to do things like
// hide the Add Entity button as the user drags the timeline.
@computed private get numSelectableEntityNames(): number {
return this.selection.numAvailableEntityNames
}
@computed get canChangeEntity(): boolean {
return (
!this.isScatter &&
!this.canSelectMultipleEntities &&
this.addCountryMode === EntitySelectionMode.SingleEntity &&
this.numSelectableEntityNames > 1
)
}
@computed get startSelectingWhenLineClicked(): boolean {
return this.showAddEntityButton
}
// For now I am only exposing this programmatically for the dashboard builder. Setting this to true
// allows you to still use add country "modes" without showing the buttons in order to prioritize
// another entity selector over the built in ones.
@observable hideEntityControls = false
}
const defaultObject = objectWithPersistablesToObject(
new Grapher(),
grapherKeysToSerialize
)
export const getErrorMessageRelatedQuestionUrl = (
question: RelatedQuestionsConfig
): string | undefined => {
return question.text
? (!question.url && "Missing URL") ||
(!question.url.match(/^https?:\/\//) &&
"URL should start with http(s)://") ||
undefined
: undefined
} | the_stack |
import type {Mutable, Class, Timing} from "@swim/util";
import {Affinity, Animator} from "@swim/component";
import {AnyLength, Length, AnyR2Point, R2Point, R2Segment, R2Box} from "@swim/math";
import {AnyGeoPoint, GeoPoint, GeoBox} from "@swim/geo";
import {AnyColor, Color} from "@swim/style";
import {MoodVector, ThemeMatrix, ThemeAnimator} from "@swim/theme";
import {ViewContextType, ViewFlags, View} from "@swim/view";
import {
Sprite,
Graphics,
GraphicsView,
Icon,
FilledIcon,
IconViewInit,
IconView,
IconGraphicsAnimator,
CanvasRenderer,
} from "@swim/graphics";
import {GeoViewInit, GeoView} from "../geo/GeoView";
import {GeoRippleOptions, GeoRippleView} from "../effect/GeoRippleView";
import type {GeoIconViewObserver} from "./GeoIconViewObserver";
/** @public */
export type AnyGeoIconView = GeoIconView | GeoIconViewInit;
/** @public */
export interface GeoIconViewInit extends GeoViewInit, IconViewInit {
geoCenter?: AnyGeoPoint;
viewCenter?: AnyR2Point;
}
/** @public */
export class GeoIconView extends GeoView implements IconView {
constructor() {
super();
this.sprite = null;
Object.defineProperty(this, "viewBounds", {
value: R2Box.undefined(),
writable: true,
enumerable: true,
configurable: true,
});
}
override readonly observerType?: Class<GeoIconViewObserver>;
/** @internal */
sprite: Sprite | null;
@Animator<GeoIconView, GeoPoint | null, AnyGeoPoint | null>({
type: GeoPoint,
value: null,
didSetState(newGeoCenter: GeoPoint | null, oldGeoCenter: GeoPoint | null): void {
this.owner.projectGeoCenter(newGeoCenter);
},
willSetValue(newGeoCenter: GeoPoint | null, oldGeoCenter: GeoPoint | null): void {
this.owner.callObservers("viewWillSetGeoCenter", newGeoCenter, oldGeoCenter, this.owner);
},
didSetValue(newGeoCenter: GeoPoint | null, oldGeoCenter: GeoPoint | null): void {
this.owner.setGeoBounds(newGeoCenter !== null ? newGeoCenter.bounds : GeoBox.undefined());
if (this.mounted) {
this.owner.projectIcon(this.owner.viewContext);
}
this.owner.callObservers("viewDidSetGeoCenter", newGeoCenter, oldGeoCenter, this.owner);
},
})
readonly geoCenter!: Animator<this, GeoPoint | null, AnyGeoPoint | null>;
@Animator<GeoIconView, R2Point | null, AnyR2Point | null>({
type: R2Point,
value: R2Point.undefined(),
updateFlags: View.NeedsComposite,
})
readonly viewCenter!: Animator<this, R2Point | null, AnyR2Point | null>;
@Animator<GeoIconView, number>({
type: Number,
value: 0.5,
updateFlags: View.NeedsProject | View.NeedsRender | View.NeedsRasterize | View.NeedsComposite,
})
readonly xAlign!: Animator<this, number>;
@Animator<GeoIconView, number>({
type: Number,
value: 0.5,
updateFlags: View.NeedsProject | View.NeedsRender | View.NeedsRasterize | View.NeedsComposite,
})
readonly yAlign!: Animator<this, number>;
@ThemeAnimator<GeoIconView, Length | null, AnyLength | null>({
type: Length,
value: null,
updateFlags: View.NeedsProject | View.NeedsRender | View.NeedsRasterize | View.NeedsComposite,
})
readonly iconWidth!: ThemeAnimator<this, Length | null, AnyLength | null>;
@ThemeAnimator<GeoIconView, Length | null, AnyLength | null>({
type: Length,
value: null,
updateFlags: View.NeedsProject | View.NeedsRender | View.NeedsRasterize | View.NeedsComposite,
})
readonly iconHeight!: ThemeAnimator<this, Length | null, AnyLength | null>;
@ThemeAnimator<GeoIconView, Color | null, AnyColor | null>({
type: Color,
value: null,
updateFlags: View.NeedsRender | View.NeedsRasterize | View.NeedsComposite,
didSetValue(newIconColor: Color | null, oldIconColor: Color | null): void {
if (newIconColor !== null) {
const oldGraphics = this.owner.graphics.value;
if (oldGraphics instanceof FilledIcon) {
const newGraphics = oldGraphics.withFillColor(newIconColor);
this.owner.graphics.setState(newGraphics, Affinity.Reflexive);
}
}
},
})
readonly iconColor!: ThemeAnimator<this, Color | null, AnyColor | null>;
@ThemeAnimator<GeoIconView, Graphics | null>({
extends: IconGraphicsAnimator,
type: Object,
updateFlags: View.NeedsRender | View.NeedsRasterize | View.NeedsComposite,
willSetValue(newGraphics: Graphics | null, oldGraphics: Graphics | null): void {
this.owner.callObservers("viewWillSetGraphics", newGraphics, oldGraphics, this.owner);
},
didSetValue(newGraphics: Graphics | null, oldGraphics: Graphics | null): void {
this.owner.callObservers("viewDidSetGraphics", newGraphics, oldGraphics, this.owner);
},
})
readonly graphics!: ThemeAnimator<this, Graphics | null>;
protected override onApplyTheme(theme: ThemeMatrix, mood: MoodVector, timing: Timing | boolean): void {
super.onApplyTheme(theme, mood, timing);
if (!this.graphics.inherited) {
const oldGraphics = this.graphics.value;
if (oldGraphics instanceof Icon) {
const newGraphics = oldGraphics.withTheme(theme, mood);
this.graphics.setState(newGraphics, oldGraphics.isThemed() ? timing : false, Affinity.Reflexive);
}
}
}
protected override onProject(viewContext: ViewContextType<this>): void {
super.onProject(viewContext);
this.projectIcon(viewContext);
}
protected projectGeoCenter(geoCenter: GeoPoint | null): void {
if (this.mounted) {
const viewContext = this.viewContext as ViewContextType<this>;
const viewCenter = geoCenter !== null && geoCenter.isDefined()
? viewContext.geoViewport.project(geoCenter)
: null;
this.viewCenter.setInterpolatedValue(this.viewCenter.value, viewCenter);
this.projectIcon(viewContext);
}
}
protected projectIcon(viewContext: ViewContextType<this>): void {
if (Affinity.Intrinsic >= (this.viewCenter.flags & Affinity.Mask)) { // this.viewCenter.hasAffinity(Affinity.Intrinsic)
const geoCenter = this.geoCenter.value;
const viewCenter = geoCenter !== null && geoCenter.isDefined()
? viewContext.geoViewport.project(geoCenter)
: null;
(this.viewCenter as Mutable<typeof this.viewCenter>).value = viewCenter; // this.viewCenter.setValue(viewCenter, Affinity.Intrinsic)
}
const viewFrame = viewContext.viewFrame;
(this as Mutable<GeoIconView>).viewBounds = this.deriveViewBounds(viewFrame);
const p0 = this.viewCenter.value;
const p1 = this.viewCenter.state;
if (p0 !== null && p1 !== null && (
viewFrame.intersectsBox(this.viewBounds) ||
viewFrame.intersectsSegment(new R2Segment(p0.x, p0.y, p1.x, p1.y)))) {
this.setCulled(false);
} else {
this.setCulled(true);
}
}
protected override onRasterize(viewContext: ViewContextType<this>): void {
super.onRasterize(viewContext);
if (!this.hidden && !this.culled) {
this.rasterizeIcon(this.viewBounds);
}
}
protected rasterizeIcon(frame: R2Box): void {
let sprite = this.sprite;
const graphics = this.graphics.value;
if (graphics !== null && frame.isDefined()) {
const width = frame.width;
const height = frame.height;
if (sprite !== null && (sprite.width < width || sprite.height < height ||
(width < sprite.width / 2 && height < sprite.height / 2))) {
this.sprite = null;
sprite.release();
sprite = null;
}
if (sprite === null) {
sprite = this.spriteProvider.service!.acquireSprite(width, height);
this.sprite = sprite;
}
const renderer = sprite.getRenderer();
const context = renderer.context;
context.clearRect(0, 0, sprite.width, sprite.height);
context.beginPath();
graphics.render(renderer, new R2Box(0, 0, width, height));
} else if (sprite !== null) {
this.sprite = null;
sprite.release();
}
}
protected override onComposite(viewContext: ViewContextType<this>): void {
super.onComposite(viewContext);
const renderer = viewContext.renderer;
if (renderer instanceof CanvasRenderer && !this.hidden && !this.culled) {
this.compositeIcon(renderer, this.viewBounds);
}
}
protected compositeIcon(renderer: CanvasRenderer, frame: R2Box): void {
const sprite = this.sprite;
if (sprite !== null) {
sprite.draw(renderer.context, frame);
}
}
protected override renderGeoBounds(viewContext: ViewContextType<this>, outlineColor: Color, outlineWidth: number): void {
// nop
}
protected override updateGeoBounds(): void {
// nop
}
override readonly viewBounds!: R2Box;
override deriveViewBounds(viewFrame?: R2Box): R2Box {
const viewCenter = this.viewCenter.value;
if (viewCenter !== null && viewCenter.isDefined()) {
if (viewFrame === void 0) {
viewFrame = this.viewContext.viewFrame;
}
const viewSize = Math.min(viewFrame.width, viewFrame.height);
let iconWidth: Length | number | null = this.iconWidth.value;
iconWidth = iconWidth instanceof Length ? iconWidth.pxValue(viewSize) : viewSize;
let iconHeight: Length | number | null = this.iconHeight.value;
iconHeight = iconHeight instanceof Length ? iconHeight.pxValue(viewSize) : viewSize;
const x = viewCenter.x - iconWidth * this.xAlign.value;
const y = viewCenter.y - iconHeight * this.yAlign.value;
return new R2Box(x, y, x + iconWidth, y + iconHeight);
} else {
return R2Box.undefined();
}
}
override get popoverFrame(): R2Box {
const viewCenter = this.viewCenter.value;
if (viewCenter !== null && viewCenter.isDefined()) {
const viewFrame = this.viewContext.viewFrame;
const viewSize = Math.min(viewFrame.width, viewFrame.height);
const inversePageTransform = this.pageTransform.inverse();
const px = inversePageTransform.transformX(viewCenter.x, viewCenter.y);
const py = inversePageTransform.transformY(viewCenter.x, viewCenter.y);
let iconWidth: Length | number | null = this.iconWidth.value;
iconWidth = iconWidth instanceof Length ? iconWidth.pxValue(viewSize) : viewSize;
let iconHeight: Length | number | null = this.iconHeight.value;
iconHeight = iconHeight instanceof Length ? iconHeight.pxValue(viewSize) : viewSize;
const x = px - iconWidth * this.xAlign.getValue();
const y = py - iconHeight * this.yAlign.getValue();
return new R2Box(x, y, x + iconWidth, y + iconHeight);
} else {
return this.pageBounds;
}
}
protected override hitTest(x: number, y: number, viewContext: ViewContextType<this>): GraphicsView | null {
const renderer = viewContext.renderer;
if (renderer instanceof CanvasRenderer) {
return this.hitTestIcon(x, y, renderer, this.viewBounds);
}
return null;
}
protected hitTestIcon(x: number, y: number, renderer: CanvasRenderer, frame: R2Box): GraphicsView | null {
// TODO: icon hit test mode
if (this.hitBounds.contains(x, y)) {
return this;
}
//const graphics = this.graphics.value;
//if (graphics !== null) {
// const context = renderer.context;
// context.beginPath();
// graphics.render(renderer, frame);
// if (context.isPointInPath(x * renderer.pixelRatio, y * renderer.pixelRatio)) {
// return this;
// }
//}
return null;
}
ripple(options?: GeoRippleOptions): GeoRippleView | null {
return GeoRippleView.ripple(this, options);
}
protected override onUnmount(): void {
super.onUnmount();
const sprite = this.sprite;
if (sprite !== null) {
this.sprite = null;
sprite.release();
}
}
override init(init: GeoIconViewInit): void {
super.init(init);
IconView.init(this, init);
if (init.geoCenter !== void 0) {
this.geoCenter(init.geoCenter);
}
if (init.viewCenter !== void 0) {
this.viewCenter(init.viewCenter);
}
}
static override readonly MountFlags: ViewFlags = GeoView.MountFlags | View.NeedsRasterize;
static override readonly UncullFlags: ViewFlags = GeoView.UncullFlags | View.NeedsRasterize;
} | the_stack |
import { ChartDataSectionType } from 'app/constants';
import {
ChartConfig,
ChartDataSectionField,
ChartStyleConfig,
LabelStyle,
LegendStyle,
LineStyle,
SeriesStyle,
} from 'app/types/ChartConfig';
import ChartDataSetDTO, { IChartDataSet } from 'app/types/ChartDataSet';
import {
getAxisLabel,
getAxisLine,
getAxisTick,
getColumnRenderName,
getExtraSeriesDataFormat,
getExtraSeriesRowData,
getGridStyle,
getReference2,
getSeriesTooltips4Polar2,
getSplitLine,
getStyles,
hadAxisLabelOverflowConfig,
setOptionsByAxisLabelOverflow,
toFormattedValue,
transformToDataSet,
} from 'app/utils/chartHelper';
import { init } from 'echarts';
import Chart from '../../../models/Chart';
import Config from './config';
import { DoubleYChartXAxis, DoubleYChartYAxis, Series } from './types';
class BasicDoubleYChart extends Chart {
dependency = [];
config = Config;
chart: any = null;
constructor() {
super('double-y', 'chartName', 'fsux_tubiao_shuangzhoutu');
this.meta.requirements = [
{
group: 1,
aggregate: [2, 999],
},
];
}
onMount(options, context): void {
if (options.containerId === undefined || !context.document) {
return;
}
this.chart = init(
context.document.getElementById(options.containerId),
'default',
);
this.mouseEvents?.forEach(event => {
this.chart.on(event.name, event.callback);
});
}
onUpdated(props): void {
if (!props.dataset || !props.dataset.columns || !props.config) {
return;
}
if (!this.isMatchRequirement(props.config)) {
return this.chart?.clear();
}
const newOptions = this.getOptions(props.dataset, props.config);
this.chart?.setOption(Object.assign({}, newOptions), true);
}
onUnMount(): void {
this.chart?.dispose();
}
onResize(opt: any, context): void {
this.chart?.resize(context);
hadAxisLabelOverflowConfig(this.chart?.getOption()) && this.onUpdated(opt);
}
private getOptions(dataset: ChartDataSetDTO, config: ChartConfig) {
const dataConfigs = config.datas || [];
const styleConfigs = config.styles || [];
const settingConfigs = config.settings || [];
const chartDataSet = transformToDataSet(
dataset.rows,
dataset.columns,
dataConfigs,
);
const groupConfigs = dataConfigs
.filter(c => c.type === ChartDataSectionType.GROUP)
.flatMap(config => config.rows || []);
const infoConfigs = dataConfigs
.filter(c => c.type === ChartDataSectionType.INFO)
.flatMap(config => config.rows || []);
const leftMetricsConfigs = dataConfigs
.filter(
c => c.type === ChartDataSectionType.AGGREGATE && c.key === 'metricsL',
)
.flatMap(config => config.rows || []);
const rightMetricsConfigs = dataConfigs
.filter(
c => c.type === ChartDataSectionType.AGGREGATE && c.key === 'metricsR',
)
.flatMap(config => config.rows || []);
if (!leftMetricsConfigs.concat(rightMetricsConfigs)?.length) {
return {};
}
const yAxisNames: string[] = leftMetricsConfigs
.concat(rightMetricsConfigs)
.map(getColumnRenderName);
// @TM 溢出自动根据bar长度设置标尺
const option = setOptionsByAxisLabelOverflow({
chart: this.chart,
xAxis: this.getXAxis(styleConfigs, groupConfigs, chartDataSet),
yAxis: this.getYAxis(
styleConfigs,
leftMetricsConfigs,
rightMetricsConfigs,
),
grid: getGridStyle(styleConfigs),
series: this.getSeries(
styleConfigs,
settingConfigs,
leftMetricsConfigs,
rightMetricsConfigs,
chartDataSet,
),
yAxisNames,
});
return {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'cross',
},
formatter: this.getTooltipFormmaterFunc(
styleConfigs,
groupConfigs,
leftMetricsConfigs.concat(rightMetricsConfigs),
[],
infoConfigs,
chartDataSet,
),
},
legend: this.getLegend(styleConfigs, yAxisNames),
...option,
};
}
private getSeries(
styles: ChartStyleConfig[],
settingConfigs: ChartStyleConfig[],
leftDeminsionConfigs,
rightDeminsionConfigs,
chartDataSet: IChartDataSet<string>,
): Series[] {
const _getSeriesByDemisionPostion =
() =>
(
config: ChartDataSectionField,
styles: ChartStyleConfig[],
settings: ChartStyleConfig[],
data: IChartDataSet<string>,
direction: string,
yAxisIndex: number,
): Series => {
const [graphType, graphStyle] = getStyles(
styles,
[direction],
['graphType', 'graphStyle'],
);
return {
yAxisIndex,
name: getColumnRenderName(config),
type: graphType || 'line',
sampling: 'average',
data: chartDataSet.map(dc => ({
...config,
...getExtraSeriesRowData(dc),
...getExtraSeriesDataFormat(config?.format),
value: dc.getCell(config),
})),
...this.getItemStyle(config),
...this.getGraphStyle(graphType, graphStyle),
...this.getLabelStyle(styles, direction),
...this.getSeriesStyle(styles),
...getReference2(settings, data, config, false),
};
};
const series = []
.concat(
leftDeminsionConfigs.map(lc =>
_getSeriesByDemisionPostion()(
lc,
styles,
settingConfigs,
chartDataSet,
'leftY',
0,
),
),
)
.concat(
rightDeminsionConfigs.map(rc =>
_getSeriesByDemisionPostion()(
rc,
styles,
settingConfigs,
chartDataSet,
'rightY',
1,
),
),
);
return series;
}
private getItemStyle(config): { itemStyle: { color: string | undefined } } {
const color = config?.color?.start;
return {
itemStyle: {
color,
},
};
}
private getGraphStyle(
graphType,
style,
): { lineStyle?: LineStyle; barWidth?: string; color?: string } {
if (graphType === 'line') {
return { lineStyle: style };
} else {
return {
barWidth: style?.width,
color: style?.color,
};
}
}
private getXAxis(
styles: ChartStyleConfig[],
xAxisConfigs: ChartDataSectionField[],
chartDataSet: IChartDataSet<string>,
): DoubleYChartXAxis {
const fisrtXAxisConfig = xAxisConfigs[0];
const [
showAxis,
inverse,
lineStyle,
showLabel,
font,
rotate,
showInterval,
interval,
overflow,
] = getStyles(
styles,
['xAxis'],
[
'showAxis',
'inverseAxis',
'lineStyle',
'showLabel',
'font',
'rotate',
'showInterval',
'interval',
'overflow',
],
);
const [showVerticalLine, verticalLineStyle] = getStyles(
styles,
['splitLine'],
['showVerticalLine', 'verticalLineStyle'],
);
return {
type: 'category',
tooltip: { show: true },
inverse,
axisLabel: getAxisLabel(
showLabel,
font,
showInterval ? interval : null,
rotate,
overflow,
),
axisLine: getAxisLine(showAxis, lineStyle),
axisTick: getAxisTick(showLabel, lineStyle),
splitLine: getSplitLine(showVerticalLine, verticalLineStyle),
data: chartDataSet.map(d => d.getCell(fisrtXAxisConfig)),
};
}
private getYAxis(
styles: ChartStyleConfig[],
leftDeminsionConfigs: ChartDataSectionField[],
rightDeminsionConfigs: ChartDataSectionField[],
): DoubleYChartYAxis[] {
const [showHorizonLine, horizonLineStyle] = getStyles(
styles,
['splitLine'],
['showHorizonLine', 'horizonLineStyle'],
);
const _yAxisTemplate = (position, name): DoubleYChartYAxis => {
const [showAxis, inverse, font, showLabel] = getStyles(
styles,
[`${position}Y`],
['showAxis', 'inverseAxis', 'font', 'showLabel'],
);
return {
type: 'value',
position,
showTitleAndUnit: true,
name,
nameLocation: 'middle',
nameGap: 50,
nameRotate: 90,
nameTextStyle: {
color: '#666',
fontFamily: 'PingFang SC',
fontSize: 12,
},
inverse,
axisLine: getAxisLine(showAxis),
axisLabel: getAxisLabel(showLabel, font),
splitLine: getSplitLine(showHorizonLine, horizonLineStyle),
};
};
const leftYAxisNames = leftDeminsionConfigs
.map(getColumnRenderName)
.join('/');
const rightYAxisNames = rightDeminsionConfigs
.map(getColumnRenderName)
.join('/');
return [
_yAxisTemplate('left', leftYAxisNames),
_yAxisTemplate('right', rightYAxisNames),
];
}
private getLegend(styles, seriesNames): LegendStyle {
const [show, type, font, legendPos, selectAll] = getStyles(
styles,
['legend'],
['showLegend', 'type', 'font', 'position', 'selectAll'],
);
let positions = {};
let orient = '';
switch (legendPos) {
case 'top':
orient = 'horizontal';
positions = { top: 8, left: 8, right: 8, height: 32 };
break;
case 'bottom':
orient = 'horizontal';
positions = { bottom: 8, left: 8, right: 8, height: 32 };
break;
case 'left':
orient = 'vertical';
positions = { left: 8, top: 16, bottom: 24, width: 96 };
break;
default:
orient = 'vertical';
positions = { right: 8, top: 16, bottom: 24, width: 96 };
break;
}
const selected: { [x: string]: boolean } = seriesNames.reduce(
(obj, name) => ({
...obj,
[name]: selectAll,
}),
{},
);
return {
...positions,
show,
type,
orient,
selected,
data: seriesNames,
textStyle: font,
};
}
private getLabelStyle(
styles: ChartStyleConfig[],
direction: string,
): LabelStyle {
const [showLabel, position, LabelFont] = getStyles(
styles,
[direction + 'Label'],
['showLabel', 'position', 'font'],
);
return {
label: {
show: showLabel,
position,
...LabelFont,
formatter: params => {
const { value, data } = params;
const formattedValue = toFormattedValue(value, data.format);
const labels: string[] = [];
labels.push(formattedValue);
return labels.join('\n');
},
},
};
}
private getTooltipFormmaterFunc(
styleConfigs: ChartStyleConfig[],
groupConfigs: ChartDataSectionField[],
aggregateConfigs: ChartDataSectionField[],
colorConfigs: ChartDataSectionField[],
infoConfigs: ChartDataSectionField[],
chartDataSet: IChartDataSet<string>,
): (params) => string {
return seriesParams => {
return getSeriesTooltips4Polar2(
chartDataSet,
seriesParams[0],
groupConfigs,
colorConfigs,
aggregateConfigs,
infoConfigs,
);
};
}
private getSeriesStyle(styles: ChartStyleConfig[]): SeriesStyle {
const [smooth, stack, step, symbol] = getStyles(
styles,
['graph'],
['smooth', 'stack', 'step', 'symbol'],
);
return { smooth, step, symbol: symbol ? 'emptyCircle' : 'none', stack };
}
}
export default BasicDoubleYChart; | the_stack |
import { isLeft, isRight } from "fp-ts/lib/Either";
import { reporter } from "io-ts-reporters";
import { normalize, relative } from "path";
import { IModule } from "../interfaces/modules";
import {
IWebpackStats,
IWebpackStatsAsset,
IWebpackStatsAssets,
IWebpackStatsChunk,
IWebpackStatsModule,
IWebpackStatsModuleModules,
IWebpackStatsModules,
IWebpackStatsModuleSource,
IWebpackStatsModuleOrphan,
IWebpackStatsModuleSynthetic,
RWebpackStats,
RWebpackStatsModuleModules,
RWebpackStatsModuleSource,
RWebpackStatsModuleOrphan,
RWebpackStatsModuleSynthetic,
} from "../interfaces/webpack-stats";
import { toPosixPath } from "../util/files";
import { sort } from "../util/strings";
export interface IActionConstructor {
stats: IWebpackStats;
ignoredPackages?: (string | RegExp)[];
}
export interface IModulesByAsset {
[asset: string]: {
asset: IWebpackStatsAsset;
mods: IModule[];
};
}
// Helper structure
interface IModulesSetByAsset {
[asset: string]: {
asset: IWebpackStatsAsset;
mods: Set<IModule>
};
}
// Note: Should only use with strings from `toPosixName()`.
const NM_RE = /(^|\/)(node_modules|\~)(\/|$)/g;
export const nodeModulesParts = (name: string) => toPosixPath(name).split(NM_RE);
// True if name is part of a `node_modules` path.
export const _isNodeModules = (name: string): boolean => nodeModulesParts(name).length > 1;
// Attempt to "unwind" webpack paths in `identifier` and `name` to remove
// prefixes and produce a normal, usable filepath.
//
// First, strip off anything before a `?` and `!`:
// - `REMOVE?KEEP`
// - `REMOVE!KEEP`
//
// TODO(106): Revise code and tests for `fullPath`.
// https://github.com/FormidableLabs/inspectpack/issues/106
export const _normalizeWebpackPath = (identifier: string, name?: string): string => {
const bangLastIdx = identifier.lastIndexOf("!");
const questionLastIdx = identifier.lastIndexOf("?");
const prefixEnd = Math.max(bangLastIdx, questionLastIdx);
let candidate = identifier;
// Remove prefix here.
if (prefixEnd > -1) {
candidate = candidate.substr(prefixEnd + 1);
}
// Naive heuristic: remove known starting webpack tokens.
candidate = candidate.replace(/^(multi |ignored )/, "");
// Assume a normalized then truncate to name if applicable.
//
// E.g.,
// - `identifier`: "css /PATH/TO/node_modules/cache-loader/dist/cjs.js!STUFF
// !/PATH/TO/node_modules/font-awesome/css/font-awesome.css 0"
// - `name`: "node_modules/font-awesome/css/font-awesome.css"
//
// Forms of name:
// - v1, v2: "/PATH/TO/ROOT/~/pkg/index.js"
// - v3: "/PATH/TO/ROOT/node_modules/pkg/index.js"
// - v4: "./node_modules/pkg/index.js"
if (name) {
name = name
.replace("/~/", "/node_modules/")
.replace("\\~\\", "\\node_modules\\");
if (name.startsWith("./") || name.startsWith(".\\")) {
// Remove dot-slash relative part.
name = name.slice(2);
}
// Now, truncate suffix of the candidate if name has less.
const nameLastIdx = candidate.lastIndexOf(name);
if (nameLastIdx > -1 && candidate.length !== nameLastIdx + name.length) {
candidate = candidate.substr(0, nameLastIdx + name.length);
}
}
return candidate;
};
// Convert a `node_modules` name to a base name.
//
// **Note**: Assumes only passed `node_modules` values.
//
// Normalizations:
// - Remove starting path if `./`
// - Switch Windows paths to Mac/Unix style.
export const _getBaseName = (name: string): string | null => {
// Slice to just after last occurrence of node_modules.
const parts = nodeModulesParts(name);
const lastName = parts[parts.length - 1];
// Normalize out the rest of the string.
let candidate = normalize(relative(".", lastName));
// Short-circuit on empty string / current path.
if (candidate === ".") {
return "";
}
// Special case -- synthetic modules can end up with trailing `/` because
// of a regular expression. Preserve this.
//
// E.g., `/PATH/TO/node_modules/moment/locale sync /es/`
//
// **Note**: The rest of this tranform _should_ be safe for synthetic regexps,
// but we can always revisit.
if (name[name.length - 1] === "/") {
candidate += "/";
}
return toPosixPath(candidate);
};
export abstract class Action {
public stats: IWebpackStats;
private _data?: object;
private _modules?: IModule[];
private _assets?: IModulesByAsset;
private _template?: ITemplate;
private _ignoredPackages: (string | RegExp)[];
constructor({ stats, ignoredPackages }: IActionConstructor) {
this.stats = stats;
this._ignoredPackages = (ignoredPackages || [])
.map((pattern) => typeof pattern === "string" ? `${pattern}/` : pattern);
}
public validate(): Promise<IAction> {
return Promise.resolve()
.then(() => {
// Validate the stats object.
const result = RWebpackStats.decode(this.stats);
if (isLeft(result)) {
const errs = reporter(result);
throw new Error(`Invalid webpack stats object. (Errors: ${errs.join(", ")})`);
}
})
.then(() => this);
}
// Create the internal data object for this action.
//
// This is a memoizing wrapper on the abstract internal method actions
// must implement.
public getData(): Promise<object> {
return Promise.resolve()
.then(() => this._data || this._getData())
.then((data) => this._data = data);
}
// Flat array of webpack source modules only. (Memoized)
public get modules(): IModule[] {
return this._modules = this._modules || this.getSourceMods(this.stats.modules);
}
// Whether or not we consider the data to indicate we should bail with error.
public shouldBail(): Promise<boolean> {
return Promise.resolve(false);
}
protected ignorePackage(baseName: string): boolean {
const base = toPosixPath(baseName.trim());
return this._ignoredPackages.some((pattern) => typeof pattern === "string" ?
base.startsWith(pattern) :
(pattern as RegExp).test(base),
);
}
protected getSourceMods(
mods: IWebpackStatsModules,
parentChunks?: IWebpackStatsChunk[],
): IModule[] {
return mods
// Recursively flatten to list of source modules.
.reduce(
(list: IModule[], mod: IWebpackStatsModule) => {
// Add in any parent chunks and ensure unique array.
const chunks = Array.from(new Set(mod.chunks.concat(parentChunks || [])));
// Fields
let isSynthetic = false;
let source = null;
let identifier;
let name;
let size;
if (isRight(RWebpackStatsModuleModules.decode(mod))) {
// Recursive case -- more modules.
const modsMod = mod as IWebpackStatsModuleModules;
// Return and recurse.
return list.concat(this.getSourceMods(modsMod.modules, chunks));
} else if (isRight(RWebpackStatsModuleSource.decode(mod))) {
// webpack5+: Check if an orphan and just skip entirely.
if (
isRight(RWebpackStatsModuleOrphan.decode(mod)) &&
(mod as IWebpackStatsModuleOrphan).orphan
) {
return list;
}
// Base case -- a normal source code module that is **not** an orphan.
const srcMod = mod as IWebpackStatsModuleSource;
identifier = srcMod.identifier;
name = srcMod.name;
// Note: there are isolated cases where webpack4 appears to be
// wrong in it's `size` estimation vs the actual string length.
// See `version mismatch for v1-v4 moment-app` wherein the
// real length of `moment/locale/es-us.js` is 3017 but webpack
// v4 reports it in stats object as 3029.
size = srcMod.source.length || srcMod.size;
source = srcMod.source;
} else if (isRight(RWebpackStatsModuleSynthetic.decode(mod))) {
// Catch-all case -- a module without modules or source.
const syntheticMod = mod as IWebpackStatsModuleSynthetic;
identifier = syntheticMod.identifier;
name = syntheticMod.name;
size = syntheticMod.size;
isSynthetic = true;
} else {
throw new Error(`Cannot match to known module type: ${JSON.stringify(mod)}`);
}
// We've now got a single entry to prepare and add.
const normalizedName = _normalizeWebpackPath(name);
const normalizedId = _normalizeWebpackPath(identifier, normalizedName);
const isNodeModules = _isNodeModules(normalizedId);
const baseName = isNodeModules ? _getBaseName(normalizedId) : null;
if (baseName && this.ignorePackage(baseName)) {
return list;
}
return list.concat([{
baseName,
chunks,
identifier,
isNodeModules,
isSynthetic,
size,
source,
}]);
},
[],
)
// Sort: via https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare
.sort((a, b) => a.identifier.localeCompare(b.identifier));
}
// Object of source modules grouped by asset. (Memoized)
public get assets(): IModulesByAsset {
return this._assets = this._assets || this.getSourceAssets(this.stats.assets);
}
protected getSourceAssets(assets: IWebpackStatsAssets): IModulesByAsset {
// Helper: LUT from chunk to asset name.
const chunksToAssets: { [chunk: string]: Set<string> } = {};
// Actual working data object.
const modulesSetByAsset: IModulesSetByAsset = {};
// Limit assets to possible JS files.
const jsAssets = assets.filter((asset) => /\.(m|)js$/.test(asset.name));
// Iterate assets and begin populating structures.
jsAssets.forEach((asset) => {
modulesSetByAsset[asset.name] = {
asset,
mods: new Set(),
};
asset.chunks.forEach((chunk) => {
// Skip null chunks, allowing only strings or numbers.
if (chunk === null) { return; }
chunk = chunk.toString(); // force to string.
chunksToAssets[chunk] = chunksToAssets[chunk] || new Set();
// Add unique assets.
chunksToAssets[chunk].add(asset.name);
});
});
// Iterate modules and attach as appropriate.
this.modules.forEach((mod) => {
mod.chunks.forEach((chunk) => {
// Skip null chunks, allowing only strings or numbers.
if (chunk === null) { return; }
chunk = chunk.toString(); // force to string.
(chunksToAssets[chunk] || []).forEach((assetName) => {
const assetObj = modulesSetByAsset[assetName];
if (assetObj) {
assetObj.mods.add(mod);
}
});
});
});
// Convert to final form
return Object.keys(modulesSetByAsset)
.sort(sort)
.reduce((memo: IModulesByAsset, assetName) => {
const assetSetObj = modulesSetByAsset[assetName];
memo[assetName] = {
asset: assetSetObj.asset,
mods: Array.from(assetSetObj.mods),
};
return memo;
}, {});
}
public get template(): ITemplate {
this._template = this._template || this._createTemplate();
return this._template;
}
protected abstract _getData(): Promise<object>;
protected abstract _createTemplate(): ITemplate;
}
// Simple alias for now (may extend later as real interface).
export type IAction = Action;
interface ITemplateConstructor {
action: IAction;
}
export enum TemplateFormat {
json = "json",
text = "text",
tsv = "tsv",
}
export interface ITemplate {
json(): Promise<string>;
text(): Promise<string>;
tsv(): Promise<string>;
render(format: TemplateFormat): Promise<string>;
}
export abstract class Template implements ITemplate {
protected action: IAction;
constructor({ action }: ITemplateConstructor) {
this.action = action;
}
public json(): Promise<string> {
return this.action.getData().then((data) => JSON.stringify(data, null, 2));
}
public abstract text(): Promise<string>;
public abstract tsv(): Promise<string>;
public render(format: TemplateFormat): Promise<string> {
return this[format]();
}
protected trim(str: string, num: number) {
return str
.trimRight() // trailing space.
.replace(/^[ ]*\s*/m, "") // First line, if empty.
.replace(new RegExp(`^[ ]{${num}}`, "gm"), "");
}
} | the_stack |
export type Selector<S, R> = (state: S) => R
export type ParametricSelector<S, P, R> = (
state: S,
props: P,
...args: any[]
) => R
interface OutputProps<C> {
resultFunc: C
recomputations: () => number
resetRecomputations: () => number
}
export type OutputSelector<S, R, C> = Selector<S, R> & OutputProps<C>
export type OutputParametricSelector<S, P, R, C> = ParametricSelector<S, P, R> &
OutputProps<C>
////////////////////////
/// createIdSelector ///
////////////////////////
interface IdSelector<P> {
(props: P, ...args: any[]): string
}
export function createIdSelector<P>(
idSelector: IdSelector<P>
): ParametricSelector<{}, P, string>
//////////////////////
/// createSelector ///
//////////////////////
type EqualityFn<T> = (a: T, b: T) => boolean
interface SelectorCreator {
/* one selector */
<S1, R1, T>(
selectors: [Selector<S1, R1>],
combiner: (res1: R1) => T,
equalityFn?: EqualityFn<T>
): OutputSelector<S1, T, (res1: R1) => T>
<S1, P1, R1, T>(
selectors: [ParametricSelector<S1, P1, R1>],
combiner: (res1: R1) => T,
equalityFn?: EqualityFn<T>
): OutputParametricSelector<S1, P1, T, (res1: R1) => T>
/* two selectors */
<S1, S2, R1, R2, T>(
selectors: [Selector<S1, R1>, Selector<S2, R2>],
combiner: (res1: R1, res2: R2) => T,
equalityFn?: EqualityFn<T>
): OutputSelector<S1 & S2, T, (res1: R1, res2: R2) => T>
<S1, S2, P1, P2, R1, R2, T>(
selectors: [ParametricSelector<S1, P1, R1>, ParametricSelector<S2, P2, R2>],
combiner: (res1: R1, res2: R2) => T,
equalityFn?: EqualityFn<T>
): OutputParametricSelector<S1 & S2, P1 & P2, T, (res1: R1, res2: R2) => T>
/* three selectors */
<S1, S2, S3, R1, R2, R3, T>(
selectors: [Selector<S1, R1>, Selector<S2, R2>, Selector<S3, R3>],
combiner: (res1: R1, res2: R2, res3: R3) => T,
equalityFn?: EqualityFn<T>
): OutputSelector<S1 & S2 & S3, T, (res1: R1, res2: R2, res3: R3) => T>
<S1, S2, S3, P1, P2, P3, R1, R2, R3, T>(
selectors: [
ParametricSelector<S1, P1, R1>,
ParametricSelector<S2, P2, R2>,
ParametricSelector<S3, P3, R3>
],
combiner: (res1: R1, res2: R2, res3: R3) => T,
equalityFn?: EqualityFn<T>
): OutputParametricSelector<
S1 & S2 & S3,
P1 & P2 & P3,
T,
(res1: R1, res2: R2, res3: R3) => T
>
/* four selectors */
<S1, S2, S3, S4, R1, R2, R3, R4, T>(
selectors: [
Selector<S1, R1>,
Selector<S2, R2>,
Selector<S3, R3>,
Selector<S4, R4>
],
combiner: (res1: R1, res2: R2, res3: R3, res4: R4) => T
): OutputSelector<
S1 & S2 & S3 & S4,
T,
(res1: R1, res2: R2, res3: R3, res4: R4) => T
>
<S1, S2, S3, S4, P1, P2, P3, P4, R1, R2, R3, R4, T>(
selectors: [
ParametricSelector<S1, P1, R1>,
ParametricSelector<S2, P2, R2>,
ParametricSelector<S3, P3, R3>,
ParametricSelector<S4, P4, R4>
],
combiner: (res1: R1, res2: R2, res3: R3, res4: R4) => T
): OutputParametricSelector<
S1 & S2 & S3 & S4,
P1 & P2 & P3 & P4,
T,
(res1: R1, res2: R2, res3: R3, res4: R4) => T
>
/* five selectors */
<S1, S2, S3, S4, S5, R1, R2, R3, R4, R5, T>(
selectors: [
Selector<S1, R1>,
Selector<S2, R2>,
Selector<S3, R3>,
Selector<S4, R4>,
Selector<S5, R5>
],
combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5) => T
): OutputSelector<
S1 & S2 & S3 & S4 & S5,
T,
(res1: R1, res2: R2, res3: R3, res4: R4, res5: R5) => T
>
<S1, S2, S3, S4, S5, P1, P2, P3, P4, P5, R1, R2, R3, R4, R5, T>(
selectors: [
ParametricSelector<S1, P1, R1>,
ParametricSelector<S2, P2, R2>,
ParametricSelector<S3, P3, R3>,
ParametricSelector<S4, P4, R4>,
ParametricSelector<S5, P5, R5>
],
combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5) => T
): OutputParametricSelector<
S1 & S2 & S3 & S4 & S5,
P1 & P2 & P3 & P4 & P5,
T,
(res1: R1, res2: R2, res3: R3, res4: R4, res5: R5) => T
>
/* six selectors */
<S1, S2, S3, S4, S5, S6, R1, R2, R3, R4, R5, R6, T>(
selectors: [
Selector<S1, R1>,
Selector<S2, R2>,
Selector<S3, R3>,
Selector<S4, R4>,
Selector<S5, R5>,
Selector<S6, R6>
],
combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6) => T
): OutputSelector<
S1 & S2 & S3 & S4 & S5 & S6,
T,
(res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6) => T
>
<S1, S2, S3, S4, S5, S6, P1, P2, P3, P4, P5, P6, R1, R2, R3, R4, R5, R6, T>(
selectors: [
ParametricSelector<S1, P1, R1>,
ParametricSelector<S2, P2, R2>,
ParametricSelector<S3, P3, R3>,
ParametricSelector<S4, P4, R4>,
ParametricSelector<S5, P5, R5>,
ParametricSelector<S6, P6, R6>
],
combiner: (res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6) => T
): OutputParametricSelector<
S1 & S2 & S3 & S4 & S5 & S6,
P1 & P2 & P3 & P4 & P5 & P6,
T,
(res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6) => T
>
/* seven selectors */
<S1, S2, S3, S4, S5, S6, S7, R1, R2, R3, R4, R5, R6, R7, T>(
selectors: [
Selector<S1, R1>,
Selector<S2, R2>,
Selector<S3, R3>,
Selector<S4, R4>,
Selector<S5, R5>,
Selector<S6, R6>,
Selector<S7, R7>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7
) => T
): OutputSelector<
S1 & S2 & S3 & S4 & S5 & S6 & S7,
T,
(res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7) => T
>
<
S1,
S2,
S3,
S4,
S5,
S6,
S7,
P1,
P2,
P3,
P4,
P5,
P6,
P7,
R1,
R2,
R3,
R4,
R5,
R6,
R7,
T
>(
selectors: [
ParametricSelector<S1, P1, R1>,
ParametricSelector<S2, P2, R2>,
ParametricSelector<S3, P3, R3>,
ParametricSelector<S4, P4, R4>,
ParametricSelector<S5, P5, R5>,
ParametricSelector<S6, P6, R6>,
ParametricSelector<S7, P7, R7>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7
) => T
): OutputParametricSelector<
S1 & S2 & S3 & S4 & S5 & S6 & S7,
P1 & P2 & P3 & P4 & P5 & P6 & P7,
T,
(res1: R1, res2: R2, res3: R3, res4: R4, res5: R5, res6: R6, res7: R7) => T
>
/* eight selectors */
<S1, S2, S3, S4, S5, S6, S7, S8, R1, R2, R3, R4, R5, R6, R7, R8, T>(
selectors: [
Selector<S1, R1>,
Selector<S2, R2>,
Selector<S3, R3>,
Selector<S4, R4>,
Selector<S5, R5>,
Selector<S6, R6>,
Selector<S7, R7>,
Selector<S8, R8>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8
) => T
): OutputSelector<
S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8,
T,
(
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8
) => T
>
<
S1,
S2,
S3,
S4,
S5,
S6,
S7,
S8,
P1,
P2,
P3,
P4,
P5,
P6,
P7,
P8,
R1,
R2,
R3,
R4,
R5,
R6,
R7,
R8,
T
>(
selectors: [
ParametricSelector<S1, P1, R1>,
ParametricSelector<S2, P2, R2>,
ParametricSelector<S3, P3, R3>,
ParametricSelector<S4, P4, R4>,
ParametricSelector<S5, P5, R5>,
ParametricSelector<S6, P6, R6>,
ParametricSelector<S7, P7, R7>,
ParametricSelector<S8, P8, R8>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8
) => T
): OutputParametricSelector<
S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8,
P1 & P2 & P3 & P4 & P5 & P6 & P7 & P8,
T,
(
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8
) => T
>
/* nine selectors */
<S1, S2, S3, S4, S5, S6, S7, S8, S9, R1, R2, R3, R4, R5, R6, R7, R8, R9, T>(
selectors: [
Selector<S1, R1>,
Selector<S2, R2>,
Selector<S3, R3>,
Selector<S4, R4>,
Selector<S5, R5>,
Selector<S6, R6>,
Selector<S7, R7>,
Selector<S8, R8>,
Selector<S9, R9>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9
) => T
): OutputSelector<
S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9,
T,
(
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9
) => T
>
<
S1,
S2,
S3,
S4,
S5,
S6,
S7,
S8,
S9,
P1,
P2,
P3,
P4,
P5,
P6,
P7,
P8,
P9,
R1,
R2,
R3,
R4,
R5,
R6,
R7,
R8,
R9,
T
>(
selectors: [
ParametricSelector<S1, P1, R1>,
ParametricSelector<S2, P2, R2>,
ParametricSelector<S3, P3, R3>,
ParametricSelector<S4, P4, R4>,
ParametricSelector<S5, P5, R5>,
ParametricSelector<S6, P6, R6>,
ParametricSelector<S7, P7, R7>,
ParametricSelector<S8, P8, R8>,
ParametricSelector<S9, P9, R9>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9
) => T
): OutputParametricSelector<
S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9,
P1 & P2 & P3 & P4 & P5 & P6 & P7 & P8 & P9,
T,
(
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9
) => T
>
/* ten selectors */
<
S1,
S2,
S3,
S4,
S5,
S6,
S7,
S8,
S9,
S10,
R1,
R2,
R3,
R4,
R5,
R6,
R7,
R8,
R9,
R10,
T
>(
selectors: [
Selector<S1, R1>,
Selector<S2, R2>,
Selector<S3, R3>,
Selector<S4, R4>,
Selector<S5, R5>,
Selector<S6, R6>,
Selector<S7, R7>,
Selector<S8, R8>,
Selector<S9, R9>,
Selector<S10, R10>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10
) => T
): OutputSelector<
S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9 & S10,
T,
(
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10
) => T
>
<
S1,
S2,
S3,
S4,
S5,
S6,
S7,
S8,
S9,
S10,
P1,
P2,
P3,
P4,
P5,
P6,
P7,
P8,
P9,
P10,
R1,
R2,
R3,
R4,
R5,
R6,
R7,
R8,
R9,
R10,
T
>(
selectors: [
ParametricSelector<S1, P1, R1>,
ParametricSelector<S2, P2, R2>,
ParametricSelector<S3, P3, R3>,
ParametricSelector<S4, P4, R4>,
ParametricSelector<S5, P5, R5>,
ParametricSelector<S6, P6, R6>,
ParametricSelector<S7, P7, R7>,
ParametricSelector<S8, P8, R8>,
ParametricSelector<S9, P9, R9>,
ParametricSelector<S10, P10, R10>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10
) => T
): OutputParametricSelector<
S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9 & S10,
P1 & P2 & P3 & P4 & P5 & P6 & P7 & P8 & P9 & P10,
T,
(
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10
) => T
>
/* eleven selectors */
<
S1,
S2,
S3,
S4,
S5,
S6,
S7,
S8,
S9,
S10,
S11,
R1,
R2,
R3,
R4,
R5,
R6,
R7,
R8,
R9,
R10,
R11,
T
>(
selectors: [
Selector<S1, R1>,
Selector<S2, R2>,
Selector<S3, R3>,
Selector<S4, R4>,
Selector<S5, R5>,
Selector<S6, R6>,
Selector<S7, R7>,
Selector<S8, R8>,
Selector<S9, R9>,
Selector<S10, R10>,
Selector<S11, R11>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11
) => T
): OutputSelector<
S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9 & S10 & S11,
T,
(
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11
) => T
>
<
S1,
S2,
S3,
S4,
S5,
S6,
S7,
S8,
S9,
S10,
S11,
P1,
P2,
P3,
P4,
P5,
P6,
P7,
P8,
P9,
P10,
P11,
R1,
R2,
R3,
R4,
R5,
R6,
R7,
R8,
R9,
R10,
R11,
T
>(
selectors: [
ParametricSelector<S1, P1, R1>,
ParametricSelector<S2, P2, R2>,
ParametricSelector<S3, P3, R3>,
ParametricSelector<S4, P4, R4>,
ParametricSelector<S5, P5, R5>,
ParametricSelector<S6, P6, R6>,
ParametricSelector<S7, P7, R7>,
ParametricSelector<S8, P8, R8>,
ParametricSelector<S9, P9, R9>,
ParametricSelector<S10, P10, R10>,
ParametricSelector<S11, P11, R11>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11
) => T
): OutputParametricSelector<
S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9 & S10 & S11,
P1 & P2 & P3 & P4 & P5 & P6 & P7 & P8 & P9 & P10 & P11,
T,
(
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11
) => T
>
/* twelve selectors */
<
S1,
S2,
S3,
S4,
S5,
S6,
S7,
S8,
S9,
S10,
S11,
S12,
R1,
R2,
R3,
R4,
R5,
R6,
R7,
R8,
R9,
R10,
R11,
R12,
T
>(
selectors: [
Selector<S1, R1>,
Selector<S2, R2>,
Selector<S3, R3>,
Selector<S4, R4>,
Selector<S5, R5>,
Selector<S6, R6>,
Selector<S7, R7>,
Selector<S8, R8>,
Selector<S9, R9>,
Selector<S10, R10>,
Selector<S11, R11>,
Selector<S12, R12>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12
) => T
): OutputSelector<
S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9 & S10 & S11 & S12,
T,
(
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12
) => T
>
<
S1,
S2,
S3,
S4,
S5,
S6,
S7,
S8,
S9,
S10,
S11,
S12,
P1,
P2,
P3,
P4,
P5,
P6,
P7,
P8,
P9,
P10,
P11,
P12,
R1,
R2,
R3,
R4,
R5,
R6,
R7,
R8,
R9,
R10,
R11,
R12,
T
>(
selectors: [
ParametricSelector<S1, P1, R1>,
ParametricSelector<S2, P2, R2>,
ParametricSelector<S3, P3, R3>,
ParametricSelector<S4, P4, R4>,
ParametricSelector<S5, P5, R5>,
ParametricSelector<S6, P6, R6>,
ParametricSelector<S7, P7, R7>,
ParametricSelector<S8, P8, R8>,
ParametricSelector<S9, P9, R9>,
ParametricSelector<S10, P10, R10>,
ParametricSelector<S11, P11, R11>,
ParametricSelector<S12, P12, R12>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12
) => T
): OutputParametricSelector<
S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9 & S10 & S11 & S12,
P1 & P2 & P3 & P4 & P5 & P6 & P7 & P8 & P9 & P10 & P11 & P12,
T,
(
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12
) => T
>
/* thirteen selectors */
<
S1,
S2,
S3,
S4,
S5,
S6,
S7,
S8,
S9,
S10,
S11,
S12,
S13,
R1,
R2,
R3,
R4,
R5,
R6,
R7,
R8,
R9,
R10,
R11,
R12,
R13,
T
>(
selectors: [
Selector<S1, R1>,
Selector<S2, R2>,
Selector<S3, R3>,
Selector<S4, R4>,
Selector<S5, R5>,
Selector<S6, R6>,
Selector<S7, R7>,
Selector<S8, R8>,
Selector<S9, R9>,
Selector<S10, R10>,
Selector<S11, R11>,
Selector<S12, R12>,
Selector<S13, R13>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12,
res13: R13
) => T
): OutputSelector<
S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9 & S10 & S11 & S12 & S13,
T,
(
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12,
res13: R13
) => T
>
<
S1,
S2,
S3,
S4,
S5,
S6,
S7,
S8,
S9,
S10,
S11,
S12,
S13,
P1,
P2,
P3,
P4,
P5,
P6,
P7,
P8,
P9,
P10,
P11,
P12,
P13,
R1,
R2,
R3,
R4,
R5,
R6,
R7,
R8,
R9,
R10,
R11,
R12,
R13,
T
>(
selectors: [
ParametricSelector<S1, P1, R1>,
ParametricSelector<S2, P2, R2>,
ParametricSelector<S3, P3, R3>,
ParametricSelector<S4, P4, R4>,
ParametricSelector<S5, P5, R5>,
ParametricSelector<S6, P6, R6>,
ParametricSelector<S7, P7, R7>,
ParametricSelector<S8, P8, R8>,
ParametricSelector<S9, P9, R9>,
ParametricSelector<S10, P10, R10>,
ParametricSelector<S11, P11, R11>,
ParametricSelector<S12, P12, R12>,
ParametricSelector<S13, P13, R13>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12,
res13: R13
) => T
): OutputParametricSelector<
S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9 & S10 & S11 & S12 & S13,
P1 & P2 & P3 & P4 & P5 & P6 & P7 & P8 & P9 & P10 & P11 & P12 & P13,
T,
(
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12,
res13: R13
) => T
>
/* fourteen selectors */
<
S1,
S2,
S3,
S4,
S5,
S6,
S7,
S8,
S9,
S10,
S11,
S12,
S13,
S14,
R1,
R2,
R3,
R4,
R5,
R6,
R7,
R8,
R9,
R10,
R11,
R12,
R13,
R14,
T
>(
selectors: [
Selector<S1, R1>,
Selector<S2, R2>,
Selector<S3, R3>,
Selector<S4, R4>,
Selector<S5, R5>,
Selector<S6, R6>,
Selector<S7, R7>,
Selector<S8, R8>,
Selector<S9, R9>,
Selector<S10, R10>,
Selector<S11, R11>,
Selector<S12, R12>,
Selector<S13, R13>,
Selector<S14, R14>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12,
res13: R13,
res14: R14
) => T
): OutputSelector<
S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9 & S10 & S11 & S12 & S13 & S14,
T,
(
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12,
res13: R13,
res14: R14
) => T
>
<
S1,
S2,
S3,
S4,
S5,
S6,
S7,
S8,
S9,
S10,
S11,
S12,
S13,
S14,
P1,
P2,
P3,
P4,
P5,
P6,
P7,
P8,
P9,
P10,
P11,
P12,
P13,
P14,
R1,
R2,
R3,
R4,
R5,
R6,
R7,
R8,
R9,
R10,
R11,
R12,
R13,
R14,
T
>(
selectors: [
ParametricSelector<S1, P1, R1>,
ParametricSelector<S2, P2, R2>,
ParametricSelector<S3, P3, R3>,
ParametricSelector<S4, P4, R4>,
ParametricSelector<S5, P5, R5>,
ParametricSelector<S6, P6, R6>,
ParametricSelector<S7, P7, R7>,
ParametricSelector<S8, P8, R8>,
ParametricSelector<S9, P9, R9>,
ParametricSelector<S10, P10, R10>,
ParametricSelector<S11, P11, R11>,
ParametricSelector<S12, P12, R12>,
ParametricSelector<S13, P13, R13>,
ParametricSelector<S14, P14, R14>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12,
res13: R13,
res14: R14
) => T
): OutputParametricSelector<
S1 & S2 & S3 & S4 & S5 & S6 & S7 & S8 & S9 & S10 & S11 & S12 & S13 & S14,
P1 & P2 & P3 & P4 & P5 & P6 & P7 & P8 & P9 & P10 & P11 & P12 & P13 & P14,
T,
(
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12,
res13: R13,
res14: R14
) => T
>
/* fifteen selectors */
<
S1,
S2,
S3,
S4,
S5,
S6,
S7,
S8,
S9,
S10,
S11,
S12,
S13,
S14,
S15,
R1,
R2,
R3,
R4,
R5,
R6,
R7,
R8,
R9,
R10,
R11,
R12,
R13,
R14,
R15,
T
>(
selectors: [
Selector<S1, R1>,
Selector<S2, R2>,
Selector<S3, R3>,
Selector<S4, R4>,
Selector<S5, R5>,
Selector<S6, R6>,
Selector<S7, R7>,
Selector<S8, R8>,
Selector<S9, R9>,
Selector<S10, R10>,
Selector<S11, R11>,
Selector<S12, R12>,
Selector<S13, R13>,
Selector<S14, R14>,
Selector<S15, R15>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12,
res13: R13,
res14: R14,
res15: R15
) => T
): OutputSelector<
S1 &
S2 &
S3 &
S4 &
S5 &
S6 &
S7 &
S8 &
S9 &
S10 &
S11 &
S12 &
S13 &
S14 &
S15,
T,
(
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12,
res13: R13,
res14: R14,
res15: R15
) => T
>
<
S1,
S2,
S3,
S4,
S5,
S6,
S7,
S8,
S9,
S10,
S11,
S12,
S13,
S14,
S15,
P1,
P2,
P3,
P4,
P5,
P6,
P7,
P8,
P9,
P10,
P11,
P12,
P13,
P14,
P15,
R1,
R2,
R3,
R4,
R5,
R6,
R7,
R8,
R9,
R10,
R11,
R12,
R13,
R14,
R15,
T
>(
selectors: [
ParametricSelector<S1, P1, R1>,
ParametricSelector<S2, P2, R2>,
ParametricSelector<S3, P3, R3>,
ParametricSelector<S4, P4, R4>,
ParametricSelector<S5, P5, R5>,
ParametricSelector<S6, P6, R6>,
ParametricSelector<S7, P7, R7>,
ParametricSelector<S8, P8, R8>,
ParametricSelector<S9, P9, R9>,
ParametricSelector<S10, P10, R10>,
ParametricSelector<S11, P11, R11>,
ParametricSelector<S12, P12, R12>,
ParametricSelector<S13, P13, R13>,
ParametricSelector<S14, P14, R14>,
ParametricSelector<S15, P15, R15>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12,
res13: R13,
res14: R14,
res15: R15
) => T
): OutputParametricSelector<
S1 &
S2 &
S3 &
S4 &
S5 &
S6 &
S7 &
S8 &
S9 &
S10 &
S11 &
S12 &
S13 &
S14 &
S15,
P1 &
P2 &
P3 &
P4 &
P5 &
P6 &
P7 &
P8 &
P9 &
P10 &
P11 &
P12 &
P13 &
P14 &
P15,
T,
(
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12,
res13: R13,
res14: R14,
res15: R15
) => T
>
/* sixteen selectors */
<
S1,
S2,
S3,
S4,
S5,
S6,
S7,
S8,
S9,
S10,
S11,
S12,
S13,
S14,
S15,
S16,
R1,
R2,
R3,
R4,
R5,
R6,
R7,
R8,
R9,
R10,
R11,
R12,
R13,
R14,
R15,
R16,
T
>(
selectors: [
Selector<S1, R1>,
Selector<S2, R2>,
Selector<S3, R3>,
Selector<S4, R4>,
Selector<S5, R5>,
Selector<S6, R6>,
Selector<S7, R7>,
Selector<S8, R8>,
Selector<S9, R9>,
Selector<S10, R10>,
Selector<S11, R11>,
Selector<S12, R12>,
Selector<S13, R13>,
Selector<S14, R14>,
Selector<S15, R15>,
Selector<S16, R16>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12,
res13: R13,
res14: R14,
res15: R15,
res16: R16
) => T
): OutputSelector<
S1 &
S2 &
S3 &
S4 &
S5 &
S6 &
S7 &
S8 &
S9 &
S10 &
S11 &
S12 &
S13 &
S14 &
S15 &
S16,
T,
(
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12,
res13: R13,
res14: R14,
res15: R15,
res16: R16
) => T
>
<
S1,
S2,
S3,
S4,
S5,
S6,
S7,
S8,
S9,
S10,
S11,
S12,
S13,
S14,
S15,
S16,
P1,
P2,
P3,
P4,
P5,
P6,
P7,
P8,
P9,
P10,
P11,
P12,
P13,
P14,
P15,
P16,
R1,
R2,
R3,
R4,
R5,
R6,
R7,
R8,
R9,
R10,
R11,
R12,
R13,
R14,
R15,
R16,
T
>(
selectors: [
ParametricSelector<S1, P1, R1>,
ParametricSelector<S2, P2, R2>,
ParametricSelector<S3, P3, R3>,
ParametricSelector<S4, P4, R4>,
ParametricSelector<S5, P5, R5>,
ParametricSelector<S6, P6, R6>,
ParametricSelector<S7, P7, R7>,
ParametricSelector<S8, P8, R8>,
ParametricSelector<S9, P9, R9>,
ParametricSelector<S10, P10, R10>,
ParametricSelector<S11, P11, R11>,
ParametricSelector<S12, P12, R12>,
ParametricSelector<S13, P13, R13>,
ParametricSelector<S14, P14, R14>,
ParametricSelector<S15, P15, R15>,
ParametricSelector<S16, P16, R16>
],
combiner: (
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12,
res13: R13,
res14: R14,
res15: R15,
res16: R16
) => T
): OutputParametricSelector<
S1 &
S2 &
S3 &
S4 &
S5 &
S6 &
S7 &
S8 &
S9 &
S10 &
S11 &
S12 &
S13 &
S14 &
S15 &
S16,
P1 &
P2 &
P3 &
P4 &
P5 &
P6 &
P7 &
P8 &
P9 &
P10 &
P11 &
P12 &
P13 &
P14 &
P15 &
P16,
T,
(
res1: R1,
res2: R2,
res3: R3,
res4: R4,
res5: R5,
res6: R6,
res7: R7,
res8: R8,
res9: R9,
res10: R10,
res11: R11,
res12: R12,
res13: R13,
res14: R14,
res15: R15,
res16: R16
) => T
>
/* any number of uniform selectors */
<S, R, T>(
selectors: Selector<S, R>[],
combiner: (...res: R[]) => T,
equalityFn?: EqualityFn<T>
): OutputSelector<S, T, (...res: R[]) => T>
<S, P, R, T>(
selectors: ParametricSelector<S, P, R>[],
combiner: (...res: R[]) => T,
equalityFn?: EqualityFn<T>
): OutputParametricSelector<S, P, T, (...res: R[]) => T>
}
export {}
export const createSelector: SelectorCreator
////////////////////////////////
/// createStructuredSelector ///
////////////////////////////////
export function createStructuredSelector<S, T>(
selectors: { [K in keyof T]: Selector<S, T[K]> }
): OutputSelector<S, T, never>
export function createStructuredSelector<S, P, T>(
selectors: { [K in keyof T]: ParametricSelector<S, P, T[K]> }
): OutputParametricSelector<S, P, T, never> | the_stack |
(function () {
try {
let decoder = new TextDecoder();
let encoder = new TextEncoder();
let liveChatOld: any; // 对旧播放器建立的ws对象的引用
let liveChat: any;
// 为了获取ws对象的引用,hook WebSocket.send
let wsHookRunOnce = true;
const wssend = WebSocket.prototype.send;
WebSocket.prototype.send = function (...arg) {
if (wsHookRunOnce && this.url == 'wss://broadcast.chat.bilibili.com:4095/sub') {
liveChatOld = this;
// 切p和掉线之后需要重新启动hook,获得新的引用
let onclose = liveChatOld.onclose;
liveChatOld.onclose = function () {
wsHookRunOnce = true;
clearTimeout(liveChat.heatTimer);
liveChat.close();
onclose.call(this);
}
// 从bilibiliPlayer.js > b.prototype.xx复制过来
// 编码一个数据包
// body[Object] : 要发送的信息
// option[Number] : 数据包对应的行为
// =5 一条弹幕数据
// =7 首个数据包,建立与服务器的连接
// return[Buffer] : 包装好的数据
liveChatOld.convertToArrayBuffer = function (body: any, option: any) {
let header = [{ "name": "Header Length", "key": "headerLen", "qg": 2, "offset": 4, "value": 16 }, { "name": "Protocol Version", "key": "ver", "qg": 2, "offset": 6, "value": 1 }, { "name": "Operation", "key": "op", "qg": 4, "offset": 8, "value": option }, { "name": "Sequence Id", "key": "seq", "qg": 4, "offset": 12, "value": 1 }];
let headerBuf = new ArrayBuffer(16);
let viewer = new DataView(headerBuf, 0);
let bodyBuf = encoder.encode(JSON.stringify(body));
viewer.setInt32(0, 16 + bodyBuf.byteLength);
header.forEach(function (b) {
4 === b.qg ? viewer.setInt32(b.offset, b.value) : 2 === b.qg && viewer.setInt16(b.offset, b.value)
})
return mergeArrayBuffer(headerBuf, bodyBuf);
}
wsHookRunOnce = false;
initLiveChat();
}
wssend.call(this, ...arg);
}
// 原函数位于bilibiliPlayer.js > c.a.eK 和 jsc-player > Dl.mergeArrayBuffer
// 连接两个buffer
function mergeArrayBuffer(headerBuf: any, bodyBuf: any) {
headerBuf = new Uint8Array(headerBuf);
bodyBuf = new Uint8Array(bodyBuf);
var d = new Uint8Array(headerBuf.byteLength + bodyBuf.byteLength);
d.set(headerBuf, 0);
d.set(bodyBuf, headerBuf.byteLength);
return d.buffer;
}
function initLiveChat() {
// 数据包对应的Operation常量表
let Pl = { "WS_OP_HEARTBEAT": 2, "WS_OP_HEARTBEAT_REPLY": 3, "WS_OP_DATA": 1000, "WS_OP_BATCH_DATA": 9, "WS_OP_DISCONNECT_REPLY": 6, "WS_OP_USER_AUTHENTICATION": 7, "WS_OP_CONNECT_SUCCESS": 8, "WS_OP_CHANGEROOM": 12, "WS_OP_CHANGEROOM_REPLY": 13, "WS_OP_REGISTER": 14, "WS_OP_REGISTER_REPLY": 15, "WS_OP_UNREGISTER": 16, "WS_OP_UNREGISTER_REPLY": 17, "WS_OP_OGVCMD_REPLY": 1015, "WS_PACKAGE_HEADER_TOTAL_LENGTH": 18, "WS_PACKAGE_OFFSET": 0, "WS_HEADER_OFFSET": 4, "WS_VERSION_OFFSET": 6, "WS_OPERATION_OFFSET": 8, "WS_SEQUENCE_OFFSET": 12, "WS_COMPRESS_OFFSET": 16, "WS_CONTENTTYPE_OFFSET": 17, "WS_BODY_PROTOCOL_VERSION": 1, "WS_HEADER_DEFAULT_VERSION": 1, "WS_HEADER_DEFAULT_OPERATION": 1, "ws_header_default_sequence": 1, "WS_HEADER_DEFAULT_COMPRESS": 0, "WS_HEADER_DEFAULT_CONTENTTYPE": 0 };
// 请求头的参数表
let wsBinaryHeaderList = [{ "name": "Header Length", "key": "headerLen", "bytes": 2, "offset": 4, "value": 18 }, { "name": "Protocol Version", "key": "ver", "bytes": 2, "offset": 6, "value": 1 }, { "name": "Operation", "key": "op", "bytes": 4, "offset": 8, "value": 7 }, { "name": "Sequence Id", "key": "seq", "bytes": 4, "offset": 12, "value": 2 }, { "name": "Compress", "key": "compress", "bytes": 1, "offset": 16, "value": 0 }, { "name": "ContentType", "key": "contentType", "bytes": 1, "offset": 17, "value": 0 }]
liveChat = new WebSocket('wss://broadcast.chat.bilibili.com:7823/sub');
liveChat.binaryType = "arraybuffer";
liveChat.heatTimer = -1;
// 每30秒一个心跳包
liveChat.heartBeat = function () {
var i = this;
clearTimeout(this.heatTimer);
var e = this.convertToArrayBuffer({}, Pl.WS_OP_HEARTBEAT);
this.send(e);
this.heatTimer = window.setTimeout((function () {
i.heartBeat();
}), 1e3 * 30);
}
liveChat.onopen = function () {
let body = {
"room_id": "video://" + API.aid + "/" + API.cid,
"platform": "web",
"accepts": [1000, 1015]
};
return this.send(this.convertToArrayBuffer(body, 7));
}
liveChat.onmessage = function (i: any) {
try {
var t = this.convertToObject(i.data);
if (t) {
switch (t.op) {
case Pl.WS_OP_HEARTBEAT_REPLY:
// 接收到心跳包后,服务器响应当前在线人数的数据
// 旧播放器连接的4095端口,虽然不再下发实时弹幕,但依然照常响应在线人数
// 所以暂时不用替换成新版
// this.onHeartBeatReply(t.body);
break;
case Pl.WS_OP_CONNECT_SUCCESS:
this.heartBeat();
break;
// 旧播放器只能处理(连接成功,心跳响应,实时弹幕)三种响应信息
// 新播放器新增的指令和功能就不管了
case Pl.WS_OP_CHANGEROOM_REPLY:
//0 === Number(t.body.code) && this.options.onChangeRoomReply({ data : t && t.body });
break;
case Pl.WS_OP_REGISTER_REPLY:
//0 === Number(t.body.code) && this.options.onRegisterReply({ data : t && t.body });
break;
case Pl.WS_OP_UNREGISTER_REPLY:
//0 === Number(t.body.code) && this.options.onUnRegisterReply({ data : t && t.body });
break;
case Pl.WS_OP_DATA:
case Pl.WS_OP_BATCH_DATA:
t.body.forEach(function (v: any) {
liveChatOld.onmessage({
data: liveChatOld.convertToArrayBuffer({
cmd: 'DM',
info: [v[0], v[1]]
}, 5)
});
});
break;
case Pl.WS_OP_OGVCMD_REPLY:
//this.onOgvCmdReply(t);
break;
default:
//this.msgReply(t)
}
}
} catch (i) {
console.error("WebSocket Error : ", i)
}
return this;
}
// jsc-player > i.prototype.convertToArrayBuffer,新版播放器的请求头信息更多,需要18字节
// 基本与liveChatOld.convertToArrayBuffer相同
liveChat.convertToArrayBuffer = function (body: any, option: any) {
let headerBuf = new ArrayBuffer(Pl.WS_PACKAGE_HEADER_TOTAL_LENGTH);
let viewer = new DataView(headerBuf, Pl.WS_PACKAGE_OFFSET);
let bodyBuf = encoder.encode(JSON.stringify(body));
viewer.setInt32(Pl.WS_PACKAGE_OFFSET, Pl.WS_PACKAGE_HEADER_TOTAL_LENGTH + bodyBuf.byteLength);
wsBinaryHeaderList[2].value = option;
wsBinaryHeaderList.forEach((function (i) {
4 === i.bytes ? (viewer.setInt32(i.offset, i.value),
"seq" === i.key && ++i.value) : 2 === i.bytes ? viewer.setInt16(i.offset, i.value) : 1 === i.bytes && viewer.setInt8(i.offset, i.value)
}));
return mergeArrayBuffer(headerBuf, bodyBuf);
}
// jsc-player > i.prototype.convertToObject
// convertToArrayBuffer对应的解码函数
liveChat.convertToObject = function (i: any) {
var e = new DataView(i), t: any = {};
t.packetLen = e.getInt32(Pl.WS_PACKAGE_OFFSET);
wsBinaryHeaderList.forEach((function (i) {
4 === i.bytes ? t[i.key] = e.getInt32(i.offset) : 2 === i.bytes ? t[i.key] = e.getInt16(i.offset) : 1 === i.bytes && (t[i.key] = e.getInt8(i.offset))
}));
if (t.op && t.op === Pl.WS_OP_BATCH_DATA) {
t.body = this.parseDanmaku(i, e, Pl.WS_PACKAGE_HEADER_TOTAL_LENGTH, t.packetLen);
}
else if (t.op && Pl.WS_OP_DATA === t.op) {
t.body = this.parseDanmaku(i, e, Pl.WS_PACKAGE_OFFSET, t.packetLen);
}
else if (t.op && t.op === Pl.WS_OP_OGVCMD_REPLY) {
t.body = ""; // this.parseOgvCmd(i, e, Pl.WS_PACKAGE_OFFSET, t.packetLen);
}
else if (t.op) {
t.body = [];
for (var a = Pl.WS_PACKAGE_OFFSET, r = t.packetLen, n: any = "", l = ""; a < i.byteLength; a += r) {
r = e.getInt32(a);
n = e.getInt16(a + Pl.WS_HEADER_OFFSET);
try {
l = JSON.parse(decoder.decode(i.slice(a + n, a + r)));
t.body = l;
} catch (e) {
l = decoder.decode(i.slice(a + n, a + r));
console.error("decode body error:", new Uint8Array(i), t);
}
}
}
return t;
}
// jsc-player > i.prototype.parseDanmaku
liveChat.parseDanmaku = function (i: any, e: any, t: any, a: any) {
for (var r, n = [], l = t; l < i.byteLength; l += a) {
a = e.getInt32(l);
r = e.getInt16(l + Pl.WS_HEADER_OFFSET);
try {
n.push(JSON.parse(decoder.decode(i.slice(l + r, l + a))));
} catch (e) {
n.push(decoder.decode(i.slice(l + r, l + a)));
console.error("decode body error:", new Uint8Array(i));
}
}
return n;
}
}
} catch (e) { toast.error("webSocket.js", e) }
})(); | the_stack |
import { decimalStr, fromWei } from '../utils/Converter';
import { logGas } from '../utils/Log';
import { VDODOContext, getVDODOContext } from '../utils/VDODOContext';
import { assert } from 'chai';
let dodoTeam: string;
let account0: string;
let account1: string;
let account2: string;
let account3: string;
let account4: string;
async function init(ctx: VDODOContext): Promise<void> {
dodoTeam = ctx.Deployer;
account0 = ctx.SpareAccounts[0];
account1 = ctx.SpareAccounts[1];
account2 = ctx.SpareAccounts[2];
account3 = ctx.SpareAccounts[3];
account4 = ctx.SpareAccounts[4];
await ctx.mintTestToken(account0, decimalStr("100000"));
await ctx.mintTestToken(account1, decimalStr("1000"));
await ctx.mintTestToken(account2, decimalStr("1000"));
await ctx.mintTestToken(account3, decimalStr("1000"));
await ctx.mintTestToken(account4, decimalStr("1000"));
await ctx.approveProxy(account0);
await ctx.approveProxy(account1);
await ctx.approveProxy(account2);
await ctx.approveProxy(account3);
await ctx.approveProxy(account4);
}
async function getGlobalState(ctx: VDODOContext, logInfo?: string) {
let [alpha,] = await ctx.VDODO.methods.getLatestAlpha().call();
var lastRewardBlock = await ctx.VDODO.methods._LAST_REWARD_BLOCK_().call();
var totalSuppy = await ctx.VDODO.methods.totalSupply().call();
console.log(logInfo + " alpha:" + fromWei(alpha, 'ether') + " lastRewardBlock:" + lastRewardBlock + " totalSuppy:" + fromWei(totalSuppy, 'ether'));
return [alpha, lastRewardBlock]
}
async function dodoBalance(ctx: VDODOContext, user: string, logInfo?: string) {
var dodo_contract = await ctx.DODO.methods.balanceOf(ctx.VDODO.options.address).call();
var dodo_account = await ctx.DODO.methods.balanceOf(user).call();
console.log(logInfo + " DODO:" + fromWei(dodo_contract, 'ether') + " account:" + fromWei(dodo_account, 'ether'));
return [dodo_contract, dodo_account]
}
async function getUserInfo(ctx: VDODOContext, user: string, logInfo?: string) {
var info = await ctx.VDODO.methods.userInfo(user).call();
var res = {
"stakingPower": info.stakingPower,
"superiorSP": info.superiorSP,
"superior": info.superior,
"credit": info.credit
}
console.log(logInfo + " stakingPower:" + fromWei(info.stakingPower, 'ether') + " superiorSP:" + fromWei(info.superiorSP, 'ether') + " superior:" + info.superior + " credit:" + fromWei(info.credit, 'ether'));
return res
}
async function mint(ctx: VDODOContext, user: string, mintAmount: string, superior: string) {
await ctx.VDODO.methods.mint(
mintAmount,
superior
).send(ctx.sendParam(user));
}
describe("VDODO", () => {
let snapshotId: string;
let ctx: VDODOContext;
before(async () => {
ctx = await getVDODOContext();
await init(ctx);
});
beforeEach(async () => {
snapshotId = await ctx.EVM.snapshot();
});
afterEach(async () => {
await ctx.EVM.reset(snapshotId);
});
describe("vdodo", () => {
it("vdodo-mint-first", async () => {
await getGlobalState(ctx, "before");
await getUserInfo(ctx, account0, "User before");
await getUserInfo(ctx, dodoTeam, "Superior before")
await dodoBalance(ctx, account0, "before")
await logGas(await ctx.VDODO.methods.mint(
decimalStr("100"),
dodoTeam
), ctx.sendParam(account0), "mint-fisrt");
//增加两个区块
await ctx.mintTestToken(account0, decimalStr("0"));
await ctx.mintTestToken(account0, decimalStr("0"));
let [alpha,] = await getGlobalState(ctx, "after");
let userInfo = await getUserInfo(ctx, account0, "User after");
let superiorInfo = await getUserInfo(ctx, dodoTeam, "Superior after")
let [, dodo_u] = await dodoBalance(ctx, account0, "after")
assert.equal(alpha, "1018181818181818181");
assert.equal(userInfo.stakingPower, "100000000000000000000");
assert.equal(userInfo.superiorSP, "10000000000000000000");
assert.equal(userInfo.credit, "0");
assert.equal(userInfo.superior, dodoTeam);
assert.equal(superiorInfo.stakingPower, "10000000000000000000");
assert.equal(superiorInfo.superiorSP, "0");
assert.equal(superiorInfo.credit, "10000000000000000000");
assert.equal(superiorInfo.superior, "0x0000000000000000000000000000000000000000");
assert.equal(dodo_u, "99900000000000000000000")
});
it("vdodo-mint-second", async () => {
await mint(ctx, account0, decimalStr("100"), dodoTeam)
await getGlobalState(ctx, "before");
await getUserInfo(ctx, account0, "User before");
await getUserInfo(ctx, dodoTeam, "Superior before")
await dodoBalance(ctx, account0, "before")
await logGas(await ctx.VDODO.methods.mint(
decimalStr("100"),
dodoTeam
), ctx.sendParam(account0), "mint-second");
//增加一个区块
await ctx.mintTestToken(account0, decimalStr("0"));
let [alpha,] = await getGlobalState(ctx, "after");
let userInfo = await getUserInfo(ctx, account0, "User after");
let superiorInfo = await getUserInfo(ctx, dodoTeam, "Superior after")
let [, dodo_u] = await dodoBalance(ctx, account0, "after")
assert.equal(alpha, "1013656931303990126");
assert.equal(userInfo.stakingPower, "199099099099099099188");
assert.equal(userInfo.superiorSP, "19909909909909909918");
assert.equal(userInfo.credit, "0");
assert.equal(userInfo.superior, dodoTeam);
assert.equal(superiorInfo.stakingPower, "19909909909909909918");
assert.equal(superiorInfo.superiorSP, "0");
assert.equal(superiorInfo.credit, "19999999999999999999");
assert.equal(superiorInfo.superior, "0x0000000000000000000000000000000000000000");
assert.equal(dodo_u, "99800000000000000000000")
});
it("vdodo-mint-second-otherSuperior", async () => {
await mint(ctx, account0, decimalStr("100"), dodoTeam)
await mint(ctx, account1, decimalStr("100"), dodoTeam)
await getGlobalState(ctx, "before");
await getUserInfo(ctx, account0, "User before");
await getUserInfo(ctx, dodoTeam, "Superior before")
await dodoBalance(ctx, account0, "before")
await logGas(await ctx.VDODO.methods.mint(
decimalStr("100"),
account1
), ctx.sendParam(account0), "mint-second");
//增加一个区块
await ctx.mintTestToken(account0, decimalStr("0"));
let [alpha,] = await getGlobalState(ctx, "after");
let userInfo = await getUserInfo(ctx, account0, "User after");
let superiorInfo = await getUserInfo(ctx, dodoTeam, "Superior after")
let [, dodo_u] = await dodoBalance(ctx, account0, "after")
assert.equal(alpha, "1016710114832014192");
assert.equal(userInfo.stakingPower, "198652706760814869070");
assert.equal(userInfo.superiorSP, "19865270676081486907");
assert.equal(userInfo.credit, "0");
assert.equal(userInfo.superior, dodoTeam);
assert.equal(superiorInfo.stakingPower, "29775180585991396825");
assert.equal(superiorInfo.superiorSP, "0");
assert.equal(superiorInfo.credit, "29999999999999999998");
assert.equal(superiorInfo.superior, "0x0000000000000000000000000000000000000000")
assert.equal(dodo_u, "99800000000000000000000")
let otherInfo = await getUserInfo(ctx, account1, "Superior after")
assert.equal(otherInfo.stakingPower, "99099099099099099188");
assert.equal(otherInfo.superiorSP, "9909909909909909918");
assert.equal(otherInfo.credit, "0");
assert.equal(otherInfo.superior, dodoTeam)
assert.equal(dodo_u, "99800000000000000000000")
});
it("redeem-amount-read", async () => {
await mint(ctx, account0, decimalStr("100"), dodoTeam)
let [dodoReceive, burnDodoAmount, withdrawFeeDodoAmount] = await ctx.VDODO.methods.getWithdrawResult(decimalStr("1")).call();
assert.equal(dodoReceive, decimalStr("0.85"));
assert.equal(burnDodoAmount, decimalStr("0"));
assert.equal(withdrawFeeDodoAmount, decimalStr("0.15"));
});
it("redeem-partial-haveMint", async () => {
await mint(ctx, account0, decimalStr("10000"), dodoTeam)
await getGlobalState(ctx, "before");
await getUserInfo(ctx, account0, "User before");
await getUserInfo(ctx, dodoTeam, "Superior before")
await dodoBalance(ctx, account0, "before")
await logGas(await ctx.VDODO.methods.redeem(decimalStr("10"), false), ctx.sendParam(account0), "redeem-partial-haveMint");
let [alpha,] = await getGlobalState(ctx, "after");
let userInfo = await getUserInfo(ctx, account0, "User after");
let superiorInfo = await getUserInfo(ctx, dodoTeam, "Superior after")
let [, dodo_u] = await dodoBalance(ctx, account0, "after")
assert.equal(alpha, "1015242271212274241");
assert.equal(userInfo.stakingPower, "9000090900827197526589");
assert.equal(userInfo.superiorSP, "900009090082719752659");
assert.equal(userInfo.credit, "0");
assert.equal(userInfo.superior, dodoTeam);
assert.equal(superiorInfo.stakingPower, "900009090082719752659");
assert.equal(superiorInfo.superiorSP, "0");
assert.equal(superiorInfo.credit, "900000000000000000001");
assert.equal(superiorInfo.superior, "0x0000000000000000000000000000000000000000");
assert.equal(dodo_u, "90850000000000000000000")
});
it("redeem-partial-NotMint", async () => {
//多个下级引用
await mint(ctx, account1, decimalStr("100"), dodoTeam)
await mint(ctx, account2, decimalStr("100"), dodoTeam)
await mint(ctx, account3, decimalStr("100"), dodoTeam)
await mint(ctx, account4, decimalStr("100"), dodoTeam)
await getGlobalState(ctx, "before");
await getUserInfo(ctx, dodoTeam, "User before");
await getUserInfo(ctx, account3, "One of referer before");
await dodoBalance(ctx, dodoTeam, "before")
let dodoTeamVdodoAmount = await ctx.VDODO.methods.balanceOf(dodoTeam).call()
await logGas(await ctx.VDODO.methods.redeem((dodoTeamVdodoAmount - 3000) + "", false), ctx.sendParam(dodoTeam), "redeem-partial-NotMint");
let [alpha,] = await getGlobalState(ctx, "after");
let userInfo = await getUserInfo(ctx, dodoTeam, "User after");
let superiorInfo = await getUserInfo(ctx, account3, "One of referer after")
let [, dodo_u] = await dodoBalance(ctx, dodoTeam, "after")
assert.equal(alpha, "1019099117914144640");
assert.equal(userInfo.stakingPower, "39343185109576338546");
assert.equal(userInfo.superiorSP, "0");
assert.equal(userInfo.credit, "39999999999999999997");
assert.equal(userInfo.superior, "0x0000000000000000000000000000000000000000");
assert.equal(superiorInfo.stakingPower, "98652706760814869070");
assert.equal(superiorInfo.superiorSP, "9865270676081486907");
assert.equal(superiorInfo.credit, "0");
assert.equal(superiorInfo.superior, dodoTeam);
assert.equal(dodo_u, "231818181817926710")
});
it("redeem-all-haveMint", async () => {
//第一笔mint不动,防止totalSupply过小
await mint(ctx, account0, decimalStr("10000"), dodoTeam)
await mint(ctx, account1, decimalStr("100"), dodoTeam)
await getGlobalState(ctx, "before");
await getUserInfo(ctx, account1, "User before");
await getUserInfo(ctx, dodoTeam, "Superior before")
await dodoBalance(ctx, account1, "before")
await logGas(await ctx.VDODO.methods.redeem(0, true), ctx.sendParam(account1), "redeem-all-haveMint");
let [alpha,] = await getGlobalState(ctx, "after");
let userInfo = await getUserInfo(ctx, account1, "User after");
let superiorInfo = await getUserInfo(ctx, dodoTeam, "Superior after")
let [, dodo_u] = await dodoBalance(ctx, account1, "after")
assert.equal(alpha, "1001544677264954465");
assert.equal(userInfo.stakingPower, "0");
assert.equal(userInfo.superiorSP, "0");
assert.equal(userInfo.credit, "0");
assert.equal(userInfo.superior, dodoTeam);
assert.equal(superiorInfo.stakingPower, "1000000000000000000000");
assert.equal(superiorInfo.superiorSP, "0");
assert.equal(superiorInfo.credit, "999999099990999910008");
assert.equal(superiorInfo.superior, "0x0000000000000000000000000000000000000000");
assert.equal(dodo_u, "985007650076500764931")
});
it("redeem-all-NoMint", async () => {
//多个下级引用
await mint(ctx, account1, decimalStr("100"), dodoTeam)
await mint(ctx, account2, decimalStr("100"), dodoTeam)
await mint(ctx, account3, decimalStr("100"), dodoTeam)
await mint(ctx, account4, decimalStr("100"), dodoTeam)
await getGlobalState(ctx, "before");
await getUserInfo(ctx, dodoTeam, "User before");
await getUserInfo(ctx, account3, "One of referer before");
await dodoBalance(ctx, dodoTeam, "before")
await logGas(await ctx.VDODO.methods.redeem(0, true), ctx.sendParam(dodoTeam), "redeem-all-NotMint");
let [alpha,] = await getGlobalState(ctx, "after");
let userInfo = await getUserInfo(ctx, dodoTeam, "User after");
let superiorInfo = await getUserInfo(ctx, account3, "One of referer after")
let [, dodo_u] = await dodoBalance(ctx, dodoTeam, "after")
assert.equal(alpha, "1019130459045726342");
assert.equal(userInfo.stakingPower, "39253971537899000903");
assert.equal(userInfo.superiorSP, "0");
assert.equal(userInfo.credit, "39999999999999999997");
assert.equal(userInfo.superior, "0x0000000000000000000000000000000000000000");
assert.equal(superiorInfo.stakingPower, "98652706760814869070");
assert.equal(superiorInfo.superiorSP, "9865270676081486907");
assert.equal(superiorInfo.credit, "0");
assert.equal(superiorInfo.superior, dodoTeam);
assert.equal(dodo_u, "309090909090909029")
});
})
}); | the_stack |
import * as evaluator from "../utils/evaluator"
import { validators } from './validators'
import { allErrors, detachAllErrors, ValidationError, getErrors } from "./error"
import { DotvvmEvent } from '../events'
import * as spaEvents from '../spa/events'
import { postbackHandlers } from "../postback/handlers"
import { DotvvmValidationContext, ErrorsPropertyName } from "./common"
import { isPrimitive, keys } from "../utils/objects"
import { elementActions } from "./actions"
import { DotvvmPostbackError } from "../shared-classes"
import { getObjectTypeInfo } from "../metadata/typeMap"
import { tryCoerce } from "../metadata/coercer"
import { primitiveTypes } from "../metadata/primitiveTypes"
import { lastSetErrorSymbol } from "../state-manager"
import { logError } from "../utils/logging"
type ValidationSummaryBinding = {
target: KnockoutObservable<any>,
includeErrorsFromChildren: boolean,
includeErrorsFromTarget: boolean,
hideWhenValid: boolean
}
type DotvvmValidationErrorsChangedEventArgs = PostbackOptions & {
readonly allErrors: ValidationError[]
}
const validationErrorsChanged = new DotvvmEvent<DotvvmValidationErrorsChangedEventArgs>("dotvvm.validation.events.validationErrorsChanged");
export const events = {
validationErrorsChanged
};
export const globalValidationObject = {
rules: validators,
errors: allErrors,
events
}
const createValidationHandler = (path: string) => ({
name: "validate",
execute: (callback: () => Promise<PostbackCommitFunction>, options: PostbackOptions) => {
if (path) {
options.validationTargetPath = path;
// resolve target
const context = ko.contextFor(options.sender);
const validationTarget = evaluator.evaluateOnViewModel(context, path);
watchAndTriggerValidationErrorChanged(options, () => {
detachAllErrors();
validateViewModel(validationTarget);
});
if (allErrors.length > 0) {
logError("validation", "Validation failed: postback aborted; errors: ", allErrors);
return Promise.reject(new DotvvmPostbackError({ type: "handler", handlerName: "validation", message: "Validation failed" }))
}
}
return callback()
}
})
export function init() {
postbackHandlers["validate"] = (opt) => createValidationHandler(opt.path);
postbackHandlers["validate-root"] = () => createValidationHandler("dotvvm.viewModelObservables['root']");
postbackHandlers["validate-this"] = () => createValidationHandler("$data");
if (compileConstants.isSpa) {
spaEvents.spaNavigating.subscribe(args => {
watchAndTriggerValidationErrorChanged(args, () => {
detachAllErrors();
});
});
}
// Validator
ko.bindingHandlers["dotvvm-validation"] = {
init: (element: HTMLElement, valueAccessor: () => any, allBindingsAccessor?: KnockoutAllBindingsAccessor) => {
validationErrorsChanged.subscribe(_ => {
applyValidatorActions(element, valueAccessor(), allBindingsAccessor!.get("dotvvm-validationOptions"));
});
},
update: (element: HTMLElement, valueAccessor: () => any, allBindingsAccessor?: KnockoutAllBindingsAccessor) => {
applyValidatorActions(element, valueAccessor(), allBindingsAccessor!.get("dotvvm-validationOptions"));
}
};
// ValidationSummary
ko.bindingHandlers["dotvvm-validationSummary"] = {
init: (element: HTMLElement, valueAccessor: () => ValidationSummaryBinding) => {
const binding = valueAccessor();
validationErrorsChanged.subscribe(_ => {
element.innerHTML = "";
const errors = getValidationErrors(
binding.target,
binding.includeErrorsFromChildren,
binding.includeErrorsFromTarget
);
for (const error of errors) {
const item = document.createElement("li");
item.innerText = error.errorMessage;
element.appendChild(item);
}
if (binding.hideWhenValid) {
element.style.display = errors.length > 0 ? "" : "none";
}
});
}
}
}
function validateViewModel(viewModel: any): void {
if (ko.isObservable(viewModel)) {
viewModel = ko.unwrap(viewModel);
}
if (!viewModel || typeof viewModel !== "object") {
return;
}
// find validation rules for the property type
const typeId = ko.unwrap(viewModel.$type);
let typeInfo;
if (typeId) {
typeInfo = getObjectTypeInfo(typeId);
}
// validate all properties
for (const propertyName of keys(viewModel)) {
if (propertyName[0] == '$') {
continue;
}
const observable = viewModel[propertyName];
if (!ko.isObservable(observable)) {
continue;
}
const propertyValue = observable();
// run validators
const propInfo = typeInfo?.properties[propertyName];
if (propInfo?.validationRules) {
validateProperty(viewModel, observable, propertyValue, propInfo.validationRules);
}
validateRecursive(propertyName, observable, propertyValue, propInfo?.type || { type: "dynamic" });
}
}
function validateRecursive(propertyName: string, observable: KnockoutObservable<any>, propertyValue: any, type: TypeDefinition) {
const lastSetError: CoerceResult = (observable as any)[lastSetErrorSymbol];
if (lastSetError && lastSetError.isError) {
ValidationError.attach(lastSetError.message, observable);
}
if (Array.isArray(type)) {
if (!propertyValue) return;
let i = 0;
for (const item of propertyValue) {
validateRecursive("[" + i + "]", item, ko.unwrap(item), type[0]);
i++;
}
} else if (typeof type === "string") {
if (!(type in primitiveTypes)) {
validateViewModel(propertyValue);
}
} else if (typeof type === "object") {
if (type.type === "dynamic") {
if (Array.isArray(propertyValue)) {
let i = 0;
for (const item of propertyValue) {
validateRecursive("[" + i + "]", item, ko.unwrap(item), { type: "dynamic" });
i++;
}
} else if (propertyValue && typeof propertyValue === "object") {
if (propertyValue["$type"]) {
validateViewModel(propertyValue);
} else {
for (const k of keys(propertyValue)) {
validateRecursive(k, ko.unwrap(propertyValue[k]), propertyValue[k], { type: "dynamic" });
}
}
}
}
}
}
function validateArray(propertyValue: any[], type: TypeDefinition) {
// handle collections
for (const item of propertyValue) {
validateViewModel(item);
}
}
/** validates the specified property in the viewModel */
function validateProperty(viewModel: any, property: KnockoutObservable<any>, value: any, propertyRules: PropertyValidationRuleInfo[]) {
for (const rule of propertyRules) {
// validate the rules
const validator = validators[rule.ruleName];
const context: DotvvmValidationContext = {
valueToValidate: value,
parentViewModel: viewModel,
parameters: rule.parameters
};
if (!validator.isValid(value, context, property)) {
ValidationError.attach(rule.errorMessage, property);
}
}
}
/**
* Gets validation errors from the passed object and its children.
* @param targetObservable Object that is supposed to contain the errors or properties with the errors
* @param includeErrorsFromGrandChildren Is called "IncludeErrorsFromChildren" in ValidationSummary.cs
* @returns By default returns only errors from the viewModel's immediate children
*/
function getValidationErrors<T>(
targetObservable: KnockoutObservable<T> | T | null,
includeErrorsFromGrandChildren: boolean,
includeErrorsFromTarget: boolean,
includeErrorsFromChildren = true): ValidationError[] {
if (!targetObservable) {
return [];
}
let errors: ValidationError[] = [];
if (includeErrorsFromTarget && ko.isObservable(targetObservable) && ErrorsPropertyName in targetObservable) {
errors = errors.concat(targetObservable[ErrorsPropertyName]);
}
if (!includeErrorsFromChildren) {
return errors;
}
const validationTarget = ko.unwrap(targetObservable);
if (isPrimitive(validationTarget)) {
return errors;
}
if (Array.isArray(validationTarget)) {
for (const item of validationTarget) {
// the next children are grandchildren
errors = errors.concat(getValidationErrors(
item,
includeErrorsFromGrandChildren,
true,
includeErrorsFromGrandChildren));
}
return errors;
}
for (const propertyName of keys(validationTarget)) {
if (propertyName[0] == '$') {
continue;
}
const property = (validationTarget as any)[propertyName];
if (!ko.isObservable(property)) {
continue;
}
// consider nested properties to be children
errors = errors.concat(getValidationErrors(
property,
includeErrorsFromGrandChildren,
true,
includeErrorsFromGrandChildren));
}
return errors;
}
/**
* Adds validation errors from the server to the appropriate arrays
*/
export function showValidationErrorsFromServer(dataContext: any, path: string, serverResponseObject: any, options: PostbackOptions) {
watchAndTriggerValidationErrorChanged(options, () => {
detachAllErrors()
// resolve validation target
const validationTarget = <KnockoutObservable<any>> evaluator.evaluateOnViewModel(
dataContext,
path!);
if (!validationTarget) {
return;
}
// add validation errors
for (const prop of serverResponseObject.modelState) {
// find the property
const propertyPath = prop.propertyPath;
const property =
propertyPath ?
evaluator.evaluateOnViewModel(ko.unwrap(validationTarget), propertyPath) :
validationTarget;
ValidationError.attach(prop.errorMessage, property);
}
});
}
function applyValidatorActions(
validator: HTMLElement,
observable: any,
validatorOptions: any): void {
const errors = getErrors(observable);
const errorMessages = errors.map(v => v.errorMessage);
for (const option of keys(validatorOptions)) {
elementActions[option](
validator,
errorMessages,
validatorOptions[option]);
}
}
function watchAndTriggerValidationErrorChanged(options: PostbackOptions, action: () => void) {
const originalErrorsCount = allErrors.length;
action();
const currentErrorsCount = allErrors.length;
if (originalErrorsCount == 0 && currentErrorsCount == 0) {
// no errors before, no errors now
return;
}
validationErrorsChanged.trigger({ ...options, allErrors });
} | the_stack |
import Graph from'./Graph';
/** A class encapsulating the functionality to find the smallest set of smallest rings in a graph. */
class SSSR {
public d: any;
public pe: any;
public pe_prime: any;
/**
* Returns an array containing arrays, each representing a ring from the smallest set of smallest rings in the graph.
*
* @param {Graph} graph A Graph object.
* @param {Boolean} [experimental=false] Whether or not to use experimental SSSR.
* @returns {Array[]} An array containing arrays, each representing a ring from the smallest set of smallest rings in the group.
*/
static getRings(graph, experimental=false) {
let adjacencyMatrix = graph.getComponentsAdjacencyMatrix();
if (adjacencyMatrix.length === 0) {
return null;
}
let connectedComponents = Graph.getConnectedComponents(adjacencyMatrix);
let rings = Array();
for (var i = 0; i < connectedComponents.length; i++) {
let connectedComponent = connectedComponents[i];
let ccAdjacencyMatrix = graph.getSubgraphAdjacencyMatrix([...connectedComponent]);
let arrBondCount = new Uint16Array(ccAdjacencyMatrix.length);
let arrRingCount = new Uint16Array(ccAdjacencyMatrix.length);
for (var j = 0; j < ccAdjacencyMatrix.length; j++) {
arrRingCount[j] = 0;
arrBondCount[j] = 0;
for (var k = 0; k < ccAdjacencyMatrix[j].length; k++) {
arrBondCount[j] += ccAdjacencyMatrix[j][k];
}
}
// Get the edge number and the theoretical number of rings in SSSR
let nEdges = 0;
for (var j = 0; j < ccAdjacencyMatrix.length; j++) {
for (var k = j + 1; k < ccAdjacencyMatrix.length; k++) {
nEdges += ccAdjacencyMatrix[j][k];
}
}
let nSssr = nEdges - ccAdjacencyMatrix.length + 1;
// console.log(nEdges, ccAdjacencyMatrix.length, nSssr);
// console.log(SSSR.getEdgeList(ccAdjacencyMatrix));
// console.log(ccAdjacencyMatrix);
// If all vertices have 3 incident edges, calculate with different formula (see Euler)
let allThree = true;
for (var j = 0; j < arrBondCount.length; j++) {
if (arrBondCount[j] !== 3) {
allThree = false;
}
}
if (allThree) {
nSssr = 2.0 + nEdges - ccAdjacencyMatrix.length;
}
// All vertices are part of one ring if theres only one ring.
if (nSssr === 1) {
rings.push([...connectedComponent]);
continue;
}
if (experimental) {
nSssr = 999;
}
let { d, pe, pe_prime } = SSSR.getPathIncludedDistanceMatrices(ccAdjacencyMatrix);
let c = SSSR.getRingCandidates(d, pe, pe_prime);
let sssr = SSSR.getSSSR(c, d, ccAdjacencyMatrix, pe, pe_prime, arrBondCount, arrRingCount, nSssr);
for (var j = 0; j < sssr.length; j++) {
let ring = Array(sssr[j].size);
let index = 0;
for (let val of sssr[j]) {
// Get the original id of the vertex back
ring[index++] = connectedComponent[val];
}
rings.push(ring);
}
}
// So, for some reason, this would return three rings for C1CCCC2CC1CCCC2, which is wrong
// As I don't have time to fix this properly, it will stay in. I'm sorry next person who works
// on it. At that point it might be best to reimplement the whole SSSR thing...
return rings;
}
/**
* Creates a printable string from a matrix (2D array).
*
* @param {Array[]} matrix A 2D array.
* @returns {String} A string representing the matrix.
*/
static matrixToString(matrix) {
let str = '';
for (var i = 0; i < matrix.length; i++) {
for (var j = 0; j < matrix[i].length; j++) {
str += matrix[i][j] + ' ';
}
str += '\n';
}
return str;
}
/**
* Returnes the two path-included distance matrices used to find the sssr.
*
* @param {Array[]} adjacencyMatrix An adjacency matrix.
* @returns {Object} The path-included distance matrices. { p1, p2 }
*/
static getPathIncludedDistanceMatrices(adjacencyMatrix) {
let length = adjacencyMatrix.length;
let d = Array(length);
let pe = Array(length);
let pe_prime = Array(length);
var l = 0;
var m = 0;
var n = 0;
var i = length;
while (i--) {
d[i] = Array(length);
pe[i] = Array(length);
pe_prime[i] = Array(length);
var j = length;
while (j--) {
d[i][j] = (i === j || adjacencyMatrix[i][j] === 1) ? adjacencyMatrix[i][j] : Number.POSITIVE_INFINITY;
if (d[i][j] === 1) {
pe[i][j] = [[[i, j]]];
} else {
pe[i][j] = Array();
}
pe_prime[i][j] = Array();
}
}
var k = length;
var j;
while (k--) {
i = length;
while (i--) {
j = length;
while (j--) {
const previousPathLength = d[i][j];
const newPathLength = d[i][k] + d[k][j];
if (previousPathLength > newPathLength) {
var l: number, m: number, n: number;
if (previousPathLength === newPathLength + 1) {
pe_prime[i][j] = [pe[i][j].length];
l = pe[i][j].length
while (l--) {
pe_prime[i][j][l] = [pe[i][j][l].length];
m = pe[i][j][l].length
while (m--) {
pe_prime[i][j][l][m] = [pe[i][j][l][m].length];
n = pe[i][j][l][m].length;
while (n--) {
pe_prime[i][j][l][m][n] = [pe[i][j][l][m][0], pe[i][j][l][m][1]];
}
}
}
} else {
pe_prime[i][j] = Array();
}
d[i][j] = newPathLength;
pe[i][j] = [[]];
l = pe[i][k][0].length;
while (l--) {
pe[i][j][0].push(pe[i][k][0][l]);
}
l = pe[k][j][0].length;
while (l--) {
pe[i][j][0].push(pe[k][j][0][l]);
}
} else if (previousPathLength === newPathLength) {
if (pe[i][k].length && pe[k][j].length) {
var l: number;
if (pe[i][j].length) {
let tmp = Array();
l = pe[i][k][0].length;
while (l--) {
tmp.push(pe[i][k][0][l]);
}
l = pe[k][j][0].length;
while (l--) {
tmp.push(pe[k][j][0][l]);
}
pe[i][j].push(tmp);
} else {
let tmp = Array();
l = pe[i][k][0].length;
while (l--) {
tmp.push(pe[i][k][0][l]);
}
l = pe[k][j][0].length;
while (l--) {
tmp.push(pe[k][j][0][l]);
}
pe[i][j][0] = tmp
}
}
} else if (previousPathLength === newPathLength - 1) {
var l: number;
if (pe_prime[i][j].length) {
let tmp = Array();
l = pe[i][k][0].length;
while (l--) {
tmp.push(pe[i][k][0][l]);
}
l = pe[k][j][0].length;
while (l--) {
tmp.push(pe[k][j][0][l]);
}
pe_prime[i][j].push(tmp);
} else {
let tmp = Array();
l = pe[i][k][0].length;
while (l--) {
tmp.push(pe[i][k][0][l]);
}
l = pe[k][j][0].length;
while (l--) {
tmp.push(pe[k][j][0][l]);
}
pe_prime[i][j][0] = tmp;
}
}
}
}
}
return {
d: d,
pe: pe,
pe_prime: pe_prime
};
}
/**
* Get the ring candidates from the path-included distance matrices.
*
* @param {Array[]} d The distance matrix.
* @param {Array[]} pe A matrix containing the shortest paths.
* @param {Array[]} pe_prime A matrix containing the shortest paths + one vertex.
* @returns {Array[]} The ring candidates.
*/
static getRingCandidates(d, pe, pe_prime) {
let length = d.length;
let candidates = Array();
let c = 0;
for (let i = 0; i < length; i++) {
for (let j = 0; j < length; j++) {
if (d[i][j] === 0 || (pe[i][j].length === 1 && pe_prime[i][j] === 0)) {
continue;
} else {
// c is the number of vertices in the cycle.
if (pe_prime[i][j].length !== 0) {
c = 2 * (d[i][j] + 0.5);
} else {
c = 2 * d[i][j];
}
if (c !== Infinity) {
candidates.push([c, pe[i][j], pe_prime[i][j]]);
}
}
}
}
// Candidates have to be sorted by c
candidates.sort(function (a, b) {
return a[0] - b[0];
});
return candidates;
}
/**
* Searches the candidates for the smallest set of smallest rings.
*
* @param {Array[]} c The candidates.
* @param {Array[]} d The distance matrix.
* @param {Array[]} adjacencyMatrix An adjacency matrix.
* @param {Array[]} pe A matrix containing the shortest paths.
* @param {Array[]} pe_prime A matrix containing the shortest paths + one vertex.
* @param {Uint16Array} arrBondCount A matrix containing the bond count of each vertex.
* @param {Uint16Array} arrRingCount A matrix containing the number of rings associated with each vertex.
* @param {Number} nsssr The theoretical number of rings in the graph.
* @returns {Set[]} The smallest set of smallest rings.
*/
static getSSSR(c, d, adjacencyMatrix, pe, pe_prime, arrBondCount, arrRingCount, nsssr) {
let cSssr = Array();
let allBonds = Array();
for (let i = 0; i < c.length; i++) {
if (c[i][0] % 2 !== 0) {
for (let j = 0; j < c[i][2].length; j++) {
let bonds = c[i][1][0].concat(c[i][2][j]);
// Some bonds are added twice, resulting in [[u, v], [u, v]] instead of [u, v].
// TODO: This is a workaround, fix later. Probably should be a set rather than an array, however the computational overhead
// is probably bigger compared to leaving it like this.
for (var k = 0; k < bonds.length; k++) {
if (bonds[k][0].constructor === Array) bonds[k] = bonds[k][0];
}
let atoms = SSSR.bondsToAtoms(bonds);
if (SSSR.getBondCount(atoms, adjacencyMatrix) === atoms.size && !SSSR.pathSetsContain(cSssr, atoms, bonds, allBonds, arrBondCount, arrRingCount)) {
cSssr.push(atoms);
allBonds = allBonds.concat(bonds);
}
if (cSssr.length > nsssr) {
return cSssr;
}
}
} else {
for (let j = 0; j < c[i][1].length - 1; j++) {
let bonds = c[i][1][j].concat(c[i][1][j + 1]);
// Some bonds are added twice, resulting in [[u, v], [u, v]] instead of [u, v].
// TODO: This is a workaround, fix later. Probably should be a set rather than an array, however the computational overhead
// is probably bigger compared to leaving it like this.
for (var k = 0; k < bonds.length; k++) {
if (bonds[k][0].constructor === Array) bonds[k] = bonds[k][0];
}
let atoms = SSSR.bondsToAtoms(bonds);
if (SSSR.getBondCount(atoms, adjacencyMatrix) === atoms.size && !SSSR.pathSetsContain(cSssr, atoms, bonds, allBonds, arrBondCount, arrRingCount)) {
cSssr.push(atoms);
allBonds = allBonds.concat(bonds);
}
if (cSssr.length > nsssr) {
return cSssr;
}
}
}
}
return cSssr;
}
/**
* Returns the number of edges in a graph defined by an adjacency matrix.
*
* @param {Array[]} adjacencyMatrix An adjacency matrix.
* @returns {Number} The number of edges in the graph defined by the adjacency matrix.
*/
static getEdgeCount(adjacencyMatrix) {
let edgeCount = 0;
let length = adjacencyMatrix.length;
var i = length - 1;
while (i--) {
var j = length;
while (j--) {
if (adjacencyMatrix[i][j] === 1) {
edgeCount++;
}
}
}
return edgeCount;
}
/**
* Returns an edge list constructed form an adjacency matrix.
*
* @param {Array[]} adjacencyMatrix An adjacency matrix.
* @returns {Array[]} An edge list. E.g. [ [ 0, 1 ], ..., [ 16, 2 ] ]
*/
static getEdgeList(adjacencyMatrix) {
let length = adjacencyMatrix.length;
let edgeList = Array();
var i = length - 1;
while (i--) {
var j = length;
while (j--) {
if (adjacencyMatrix[i][j] === 1) {
edgeList.push([i, j]);
}
}
}
return edgeList;
}
/**
* Return a set of vertex indices contained in an array of bonds.
*
* @param {Array} bonds An array of bonds. A bond is defined as [ sourceVertexId, targetVertexId ].
* @returns {Set<Number>} An array of vertices.
*/
static bondsToAtoms(bonds) {
let atoms = new Set();
var i = bonds.length;
while (i--) {
atoms.add(bonds[i][0]);
atoms.add(bonds[i][1]);
}
return atoms;
}
/**
* Returns the number of bonds within a set of atoms.
*
* @param {Set<Number>} atoms An array of atom ids.
* @param {Array[]} adjacencyMatrix An adjacency matrix.
* @returns {Number} The number of bonds in a set of atoms.
*/
static getBondCount(atoms, adjacencyMatrix) {
let count = 0;
for (let u of atoms) {
for (let v of atoms) {
if (u === v) {
continue;
}
count += adjacencyMatrix[u][v]
}
}
return count / 2;
}
/**
* Checks whether or not a given path already exists in an array of paths.
*
* @param {Set[]} pathSets An array of sets each representing a path.
* @param {Set<Number>} pathSet A set representing a path.
* @param {Array[]} bonds The bonds associated with the current path.
* @param {Array[]} allBonds All bonds currently associated with rings in the SSSR set.
* @param {Uint16Array} arrBondCount A matrix containing the bond count of each vertex.
* @param {Uint16Array} arrRingCount A matrix containing the number of rings associated with each vertex.
* @returns {Boolean} A boolean indicating whether or not a give path is contained within a set.
*/
static pathSetsContain(pathSets, pathSet, bonds, allBonds, arrBondCount, arrRingCount) {
var i = pathSets.length;
while (i--) {
if (SSSR.isSupersetOf(pathSet, pathSets[i])) {
return true;
}
if (pathSets[i].size !== pathSet.size) {
continue;
}
if (SSSR.areSetsEqual(pathSets[i], pathSet)) {
return true;
}
}
// Check if the edges from the candidate are already all contained within the paths of the set of paths.
// TODO: For some reason, this does not replace the isSupersetOf method above -> why?
let count = 0;
let allContained = false;
i = bonds.length;
while (i--) {
var j = allBonds.length;
while (j--) {
if (bonds[i][0] === allBonds[j][0] && bonds[i][1] === allBonds[j][1] ||
bonds[i][1] === allBonds[j][0] && bonds[i][0] === allBonds[j][1]) {
count++;
}
if (count === bonds.length) {
allContained = true;
}
}
}
// If all the bonds and thus vertices are already contained within other rings
// check if there's one vertex with ringCount < bondCount
let specialCase = false;
if (allContained) {
for (let element of pathSet) {
if (arrRingCount[element] < arrBondCount[element]) {
specialCase = true;
break;
}
}
}
if (allContained && !specialCase) {
return true;
}
// Update the ring counts for the vertices
for (let element of pathSet) {
arrRingCount[element]++;
}
return false;
}
/**
* Checks whether or not two sets are equal (contain the same elements).
*
* @param {Set<Number>} setA A set.
* @param {Set<Number>} setB A set.
* @returns {Boolean} A boolean indicating whether or not the two sets are equal.
*/
static areSetsEqual(setA, setB) {
if (setA.size !== setB.size) {
return false;
}
for (let element of setA) {
if (!setB.has(element)) {
return false;
}
}
return true;
}
/**
* Checks whether or not a set (setA) is a superset of another set (setB).
*
* @param {Set<Number>} setA A set.
* @param {Set<Number>} setB A set.
* @returns {Boolean} A boolean indicating whether or not setB is a superset of setA.
*/
static isSupersetOf(setA, setB) {
for (var element of setB) {
if (!setA.has(element)) {
return false;
}
}
return true;
}
}
export default SSSR; | the_stack |
import _ from 'lodash';
import React from 'react';
import createClass from 'create-react-class';
import {
Button,
Dialog,
CheckboxLabeled,
SearchField,
SearchableMultiSelect,
SingleSelect,
} from './../../index';
export default {
title: 'Layout/Dialog',
component: Dialog,
parameters: {
docs: {
description: {
component: (Dialog as any).peek.description,
},
},
},
};
/* Small */
export const Small = () => {
const Component = createClass({
getInitialState() {
return {
isShown: false,
};
},
handleShow(isShown: any) {
this.setState({ isShown });
},
render() {
return (
<div>
<Button onClick={_.partial(this.handleShow, !this.state.isShown)}>
Toggle
</Button>
<Dialog
isShown={this.state.isShown}
handleClose={_.partial(this.handleShow, !this.state.isShown)}
Header='Header'
size='small'
>
<div key={'info'}>
For better UX, we recommend NOT handling onEscape and
onBackgroundClick when isModal is true. The term "modal" implies
that the user needs to interact with one of the buttons in the
footer to exit the dialog.
</div>
{_.times(10).map((i) => {
return <div key={i}>Body</div>;
})}
<Dialog.Footer>
<Button
kind='invisible'
onClick={_.partial(this.handleShow, false)}
style={{ marginRight: '9px' }}
>
Cancel
</Button>
<Button kind='primary'>Save</Button>
</Dialog.Footer>
</Dialog>
</div>
);
},
});
return <Component />;
};
Small.storyName = 'Small';
/* Medium */
export const Medium = () => {
const Component = createClass({
getInitialState() {
return {
isShown: false,
};
},
handleShow(isShown: any) {
this.setState({ isShown });
},
render() {
return (
<div>
<Button onClick={_.partial(this.handleShow, !this.state.isShown)}>
Toggle
</Button>
<Dialog
isShown={this.state.isShown}
handleClose={_.partial(this.handleShow, !this.state.isShown)}
Header='Header'
size='medium'
>
<div key={'info'}>
For better UX, we recommend NOT handling onEscape and
onBackgroundClick when isModal is true. The term "modal" implies
that the user needs to interact with one of the buttons in the
footer to exit the dialog.
</div>
{_.times(50).map((i) => {
return <div key={i}>Body</div>;
})}
<Dialog.Footer>
<Button
kind='invisible'
onClick={_.partial(this.handleShow, false)}
style={{ marginRight: '9px' }}
>
Cancel
</Button>
<Button kind='primary'>Save</Button>
</Dialog.Footer>
</Dialog>
</div>
);
},
});
return <Component />;
};
Medium.storyName = 'Medium';
/* Large With Rich Header */
export const LargeWithRichHeader = () => {
const Component = createClass({
getInitialState() {
return {
isShown: false,
};
},
handleShow(isShown: any) {
this.setState({ isShown });
},
render() {
return (
<div>
<Button onClick={_.partial(this.handleShow, !this.state.isShown)}>
Toggle
</Button>
<Dialog
isShown={this.state.isShown}
handleClose={_.partial(this.handleShow, !this.state.isShown)}
size='large'
>
<Dialog.Header>
<i>Rich Header</i>
</Dialog.Header>
<div key={'info'}>
For better UX, we recommend NOT handling onEscape and
onBackgroundClick when isModal is true. The term "modal" implies
that the user needs to interact with one of the buttons in the
footer to exit the dialog.
</div>
{_.times(50).map((i) => {
return <div key={i}>Body</div>;
})}
<Dialog.Footer>
<Button
kind='invisible'
onClick={_.partial(this.handleShow, false)}
style={{ marginRight: '9px' }}
>
Cancel
</Button>
<Button kind='primary'>Save</Button>
</Dialog.Footer>
</Dialog>
</div>
);
},
});
return <Component />;
};
LargeWithRichHeader.storyName = 'LargeWithRichHeader';
/* Complex */
export const Complex = () => {
const style = {
marginBottom: '3px',
};
const { Option } = SearchableMultiSelect;
const { Placeholder, Option: SingleOption } = SingleSelect;
const Component = createClass({
getInitialState() {
return {
isShown: false,
flavors: ['chocolate'],
};
},
handleShow(isShown: any) {
this.setState({ isShown });
},
handleSelectedChocolate(isSelected: any) {
this.setState({
flavors: isSelected
? _.concat(this.state.flavors, 'chocolate')
: _.without(this.state.flavors, 'chocolate'),
});
},
handleSelectedStrawberry(isSelected: any) {
this.setState({
flavors: isSelected
? _.concat(this.state.flavors, 'strawberry')
: _.without(this.state.flavors, 'strawberry'),
});
},
render() {
return (
<div>
<Button onClick={_.partial(this.handleShow, !this.state.isShown)}>
Toggle
</Button>
<Dialog
isComplex
isShown={this.state.isShown}
handleClose={_.partial(this.handleShow, !this.state.isShown)}
Header='Advanced Filters'
size='medium'
>
<p style={{ fontSize: '16px' }}>Flavor</p>
<CheckboxLabeled
isSelected={_.includes(this.state.flavors, 'chocolate')}
name='interactive-checkboxes'
onSelect={this.handleSelectedChocolate}
style={style}
>
<CheckboxLabeled.Label>Chocolate</CheckboxLabeled.Label>
</CheckboxLabeled>
<CheckboxLabeled
isSelected={_.includes(this.state.flavors, 'strawberry')}
name='interactive-checkboxes'
onSelect={this.handleSelectedStrawberry}
style={style}
>
<CheckboxLabeled.Label>Strawberry</CheckboxLabeled.Label>
</CheckboxLabeled>
<p style={{ fontSize: '16px', marginTop: '25px' }}>
Flavor Combination Research
</p>
<SearchField placeholder='Sundae school...' />
<p style={{ fontSize: '16px', marginTop: '25px' }}>Toppings</p>
<SearchableMultiSelect responsiveMode='large'>
<Option>cookie dough</Option>
<Option>more ice cream</Option>
<Option>mochi</Option>
<Option>peanut butter cups</Option>
</SearchableMultiSelect>
<p style={{ fontSize: '16px', marginTop: '25px' }}>
Ice Cream Breaks
</p>
<SingleSelect onSelect={this.handleSelect}>
<Placeholder>You must select a break...</Placeholder>
<SingleOption>10am</SingleOption>
<SingleOption>11am</SingleOption>
<SingleOption>1pm</SingleOption>
<SingleOption>2pm</SingleOption>
</SingleSelect>
<Dialog.Footer>
<Button
kind='invisible'
onClick={_.partial(this.handleShow, false)}
style={{ marginRight: '9px' }}
>
Cancel
</Button>
<Button kind='primary'>Save</Button>
</Dialog.Footer>
</Dialog>
</div>
);
},
});
return <Component />;
};
Complex.storyName = 'Complex';
/* No Modal */
export const NoModal = () => {
const Component = createClass({
getInitialState() {
return {
isShown: false,
};
},
handleShow(isShown: any) {
this.setState({ isShown });
},
render() {
return (
<div>
<Button onClick={_.partial(this.handleShow, !this.state.isShown)}>
Toggle
</Button>
<Dialog
isModal={false}
isShown={this.state.isShown}
handleClose={_.partial(this.handleShow, !this.state.isShown)}
onBackgroundClick={_.partial(this.handleShow, false)}
onEscape={_.partial(this.handleShow, false)}
Header='Header'
size='small'
>
In most cases, you'll probably just use an isModal Dialog, but this
example shows that the Dialog doesn't have to be a modal. Try
pressing "escape" to close this Dialog.
<Dialog.Footer>
<Button
kind='invisible'
onClick={_.partial(this.handleShow, false)}
style={{ marginRight: '9px' }}
>
Cancel
</Button>
<Button kind='primary'>Save</Button>
</Dialog.Footer>
</Dialog>
</div>
);
},
});
return <Component />;
};
NoModal.storyName = 'NoModal';
/* No Footer */
export const NoFooter = () => {
const Component = createClass({
getInitialState() {
return {
isShown: false,
};
},
handleShow(isShown: any) {
this.setState({ isShown });
},
render() {
return (
<div>
<Button onClick={_.partial(this.handleShow, !this.state.isShown)}>
Toggle
</Button>
<Dialog
isShown={this.state.isShown}
handleClose={_.partial(this.handleShow, !this.state.isShown)}
onBackgroundClick={_.partial(this.handleShow, false)}
onEscape={_.partial(this.handleShow, false)}
Header='Header'
size='medium'
>
This `Dialog` has no footer!
</Dialog>
</div>
);
},
});
return <Component />;
};
NoFooter.storyName = 'NoFooter';
/* No Gutters */
export const NoGutters = () => {
const Component = createClass({
getInitialState() {
return {
isShown: false,
};
},
handleShow(isShown: any) {
this.setState({ isShown });
},
render() {
return (
<div>
<Button onClick={_.partial(this.handleShow, !this.state.isShown)}>
Toggle
</Button>
<Dialog
isShown={this.state.isShown}
handleClose={_.partial(this.handleShow, !this.state.isShown)}
onBackgroundClick={_.partial(this.handleShow, false)}
onEscape={_.partial(this.handleShow, false)}
Header='Header'
size='medium'
hasGutters={false}
>
This `Dialog` has no gutters!
</Dialog>
</div>
);
},
});
return <Component />;
};
NoGutters.storyName = 'NoGutters';
/* No Close Button */
export const NoCloseButton = () => {
const Component = createClass({
getInitialState() {
return {
isShown: false,
};
},
handleShow(isShown: any) {
this.setState({ isShown });
},
render() {
return (
<div>
<Button onClick={_.partial(this.handleShow, !this.state.isShown)}>
Toggle
</Button>
<Dialog isShown={this.state.isShown} Header='Header' size='medium'>
<div key={'info'}>
For better UX, we recommend NOT handling onEscape and
onBackgroundClick when isModal is true. The term "modal" implies
that the user needs to interact with one of the buttons in the
footer to exit the dialog.
</div>
{_.times(50).map((i) => {
return <div key={i}>Body</div>;
})}
<Dialog.Footer>
<Button
kind='invisible'
onClick={_.partial(this.handleShow, false)}
style={{ marginRight: '9px' }}
>
Cancel
</Button>
<Button kind='primary'>Save</Button>
</Dialog.Footer>
</Dialog>
</div>
);
},
});
return <Component />;
};
NoCloseButton.storyName = 'NoCloseButton'; | the_stack |
import * as _ from "underscore";
import {FeedFieldPolicyDialogData} from "./feed-field-policy-dialog-data";
import {FieldPolicyOptionsService} from "../field-policies-angular2/field-policy-options.service";
import {Component, Inject, OnDestroy, OnInit, ChangeDetectionStrategy, Output, EventEmitter, ViewChild} from "@angular/core";
import {PolicyInputFormService} from "../../../../lib/feed-mgr/shared/field-policies-angular2/policy-input-form.service";
import {FormGroup} from "@angular/forms";
import {TableFieldPolicy} from "../../model/TableFieldPolicy";
import {MAT_DIALOG_DATA, MatDialogRef} from "@angular/material/dialog";
import {MatRadioChange} from "@angular/material/radio";
import {MatSelectChange} from "@angular/material/select";
import {CloneUtil} from "../../../common/utils/clone-util";
import {PolicyInputFormComponent} from "../field-policies-angular2/policy-input-form.component";
interface ViewText {
modeText:string;
title:string;
titleText:string;
addText:string;
cancelText:string;
}
enum EditMode {
NEW=1, EDIT=2
}
@Component({
selector:"feed-field-policy-rules-dialog",
templateUrl: "./feed-field-policy-rules-dialog.component.html"
})
export class FeedFieldPolicyRulesDialogComponent implements OnInit,OnDestroy{
loading = false;
@ViewChild(PolicyInputFormComponent)
policyInputForm:PolicyInputFormComponent
/**
* Rule Type options for the std or vaidators
* @type {any[]}
*/
public options:any[] = [];
/**
* The select option/ruleType to use
* default to standardization
* @type {string}
*/
public selectedOptionType = FieldPolicyOptionsService.STANDARDIZATION;
optionTypes = [{ type: FieldPolicyOptionsService.STANDARDIZATION, name: 'Standardization' }, { type: FieldPolicyOptionsService.VALIDATION, name: 'Validation' }]
/**
* The list of available validators
* @type {Array}
*/
validators: any = [];
/**
* The list of available standardizers
* @type {Array}
*/
standardizers: any = [];
/**
* Array of all standardizers and validators
* @type {Array}
*/
validatorsAndStandardizers: any = [];
/**
* The field policies associated with the field
* @type {null}
*/
policyRules: any[]= null;
public policyForm:FormGroup;
/**
* Any pending changes
* @type {boolean}
*/
pendingEdits :boolean = false;
/**
* The rule currently editing
* @type {any}
*/
editRule:any = this.emptyRule();
/**
* is this needed? dup of selectedOptionType?
* @type {null}
*/
ruleType :any = null;
editIndex :number = null;
editMode:EditMode = EditMode.NEW;
/**
* Flag to indicate the options have been moved/reordered
* @type {boolean}
*/
moved = false;
editRuleSelected:boolean;
selectedRuleTypeName:string;
/**
* flag to determine if the form is valid or not
* @type {boolean}
*/
policyFormIsValid = false;
viewText :ViewText = {modeText:"Add",title:"Field Policies",titleText:"Add a new policy", addText:"Add Rule", cancelText:"Cancel Add"}
constructor(
public fieldPolicyOptionsService: FieldPolicyOptionsService,
public dialogRef: MatDialogRef<FeedFieldPolicyRulesDialogComponent>,
private policyInputFormService :PolicyInputFormService,
@Inject(MAT_DIALOG_DATA) public data: FeedFieldPolicyDialogData) {
this.policyForm = new FormGroup({});
this.policyForm.statusChanges.debounceTime(10).subscribe(status => {
this.policyFormIsValid = status == "VALID";
})
}
ngOnInit(){
this.buildStandardizersAndValidators();
this.setupPoliciesForFeed();
}
ngOnDestroy() {
}
/**
* When the rule select drop down changes
* Clone the rule and show the dynamic form
* @param {MatSelectChange} change
*/
onRuleTypeChange(change:MatSelectChange) {
if(this.selectedRuleTypeName && this.selectedOptionType) {
let ruleType :any = this.findRuleType(this.selectedRuleTypeName, this.selectedOptionType);
if(ruleType) {
var rule :any = CloneUtil.deepCopy(ruleType);
rule.groups = this.policyInputFormService.groupProperties(rule);
this.policyInputFormService.updatePropertyIndex(rule);
//make all rules editable
rule.editable = true;
this.editRule = rule;
this.editRuleSelected = true;
}
else {
this.editRule = this.emptyRule();
this.editRuleSelected = false;
}
}
}
/**
* react to when the form controls are painted on the screen
* @param controls
*/
onFormControlsAdded(controls:any){
this.policyForm.updateValueAndValidity();
}
/**
* When the std/validator changes
* @param {MatRadioChange} event
*/
onChangedOptionType(event:MatRadioChange){
let type:string = event.value;
this._changedOptionType(type);
}
/**
* When a policy is reordered
* @param $index
*/
onMovedPolicyRule(r: any, list: any[]) {
list.splice(list.indexOf(r), 1);
this.moved = true;
this.pendingEdits = true;
//resequence
list.forEach((rule:any,index:number) =>rule.sequence = index);
this.policyRules = list;
}
/**
* When a user deletes a given policy
* @param {number} $index
*/
deletePolicy($index?: number) {
if($index == undefined){
$index = this.editIndex;
}
if (this.policyRules != null && $index != null) {
this.policyRules.splice($index, 1);
}
this.pendingEdits = true;
this.cancelEdit();
}
/**
* When a user adds a new policy
*/
addPolicy(){
var validForm = this.validateForm();
if (validForm == true) {
if (this.policyRules == null) {
this.policyRules = [];
}
// buildDisplayString();
this.editRule.ruleType = this.ruleType;
if (this.editMode == EditMode.NEW) {
this.policyRules.push(this.editRule);
}
else if (this.editMode == EditMode.EDIT) {
this.policyRules[this.editIndex] = this.editRule;
}
this.pendingEdits = true;
this.cancelEdit();
}
}
/**
* When a user edits a policy
* @param {number} index
* @param rule
*/
editPolicy(index: number, rule: any) {
if (this.editMode == EditMode.EDIT) {
this.cancelEdit();
}
this.editMode = EditMode.EDIT;
this.viewText.addText ='SAVE EDIT';
this.viewText.titleText='Edit the policy';
this.editIndex = index;
//get a copy of the saved rule
var editRule = Object.assign({},this.policyRules[index]);
//copy the rule from options with all the select options
var startingRule = Object.assign({},this.findRuleType(editRule.name, editRule.type));
//reset the values
startingRule.properties.forEach((ruleProperty: any) => {
var editRuleProperty = _.find(editRule.properties, (editProperty: any) => {
return editProperty.name == ruleProperty.name;
});
if (editRuleProperty != null && editRuleProperty != undefined) {
//assign the values
ruleProperty.value = editRuleProperty.value;
ruleProperty.values = editRuleProperty.values;
}
});
//reassign the editRule object to the one that has all the select values
editRule = startingRule;
editRule.groups = this.policyInputFormService.groupProperties(editRule);
this.policyInputFormService.updatePropertyIndex(editRule);
//make all rules editable
editRule.editable = true;
this.editRule = editRule;
var match = this.findRuleType(rule.name, rule.type)
this.ruleType = Object.assign({},match);
if (this.ruleType && this.ruleType.type != this.selectedOptionType) {
this._changedOptionType(this.ruleType.type);
}
this.selectedOptionType = editRule.type;
this.selectedRuleTypeName = this.editRule.name;
}
/**
* When the user is done adding/editing save the changes back to the model
*/
done(){
var validators: any = [];
var standardizers: any = [];
this.policyRules.forEach((rule: any, i: any) => {
rule.sequence = i;
if (rule.type == 'validation') {
validators.push(rule);
}
else if (rule.type == 'standardization') {
standardizers.push(rule);
}
})
this.data.field['validation'] = validators;
this.data.field['standardization'] = standardizers;
this.dialogRef.close('done');
}
/**
* when a user cancels the entire edit of the form
*/
onCancelClick(): void {
this.cancelEdit();
this.dialogRef.close();
}
private emptyRule():any {
return {name:"",groups:[],editable:false};
}
private _changedOptionType(type: string) {
this.options = type == FieldPolicyOptionsService.STANDARDIZATION ? this.standardizers : this.validators;
this.selectedOptionType = type;
this.policyInputForm.resetForm();
}
/**
* when canceling a pending edit
*/
cancelEdit() {
this.editMode = EditMode.NEW;
this.viewText.addText = 'Add Rule';
this.viewText.cancelText = 'Cancel Add';
this.viewText.titleText = 'Add a new policy';
this.ruleType = null;
this.editRule = this.emptyRule();
this.editRuleSelected = false;
this.selectedRuleTypeName = null;
}
private validateForm(){
return true;
}
private buildStandardizersAndValidators(){
this.loading = true;
this.fieldPolicyOptionsService.getStandardizersAndValidators().subscribe((response: any[]) => {
var currentFeedValue = null;
if (this.data.feed != null) {
currentFeedValue = this.policyInputFormService.currentFeedValue(this.data.feed);
currentFeedValue = currentFeedValue.toLowerCase();
}
var standardizationResults = [];
var validationResults = [];
if (response ) {
standardizationResults = _.sortBy(response[0], (r) => {
return r.name;
});
_.each(standardizationResults, (result) => {
result.type = 'standardization';
})
}
if (response) {
validationResults = _.sortBy(response[1], (r) => {
return r.name;
});
_.each(validationResults, (result) => {
result.type = 'validation';
})
}
this.standardizers = this.policyInputFormService.groupPolicyOptions(standardizationResults, currentFeedValue);
this.validators = this.policyInputFormService.groupPolicyOptions(validationResults, currentFeedValue);
this.validatorsAndStandardizers = _.union(this.validators, this.standardizers);
//set the correct options in the drop down
this._changedOptionType(this.selectedOptionType);
this.ruleTypesAvailable();
this.loading = false;
})
}
private setupPoliciesForFeed() {
var arr = this.getAllPolicyRules(this.data.field);
if (arr != null && arr != undefined) {
this.policyRules = CloneUtil.deepCopy(arr);
}
}
private findRuleType(ruleName: any, type: any) {
return _.find(this.validatorsAndStandardizers, (opt: any) => {
return opt.name == ruleName && opt.type == type;
});
}
private ruleTypesAvailable() {
if (this.editRule != null) {
this.ruleType = this.findRuleType(this.editRule.name, this.editRule.type);
if (this.ruleType && this.ruleType.type != this.selectedOptionType) {
this._changedOptionType(this.ruleType.type);
}
}
}
private getAllPolicyRules(field: TableFieldPolicy) {
if (field === undefined) {
return [];
}
var arr = [];
var standardizers = field['standardization'];
var validators = field['validation'];
//add in the type so we know what we are dealing with
let tmpArr :any[] = [];
if (standardizers) {
standardizers.forEach((item:any,i:number) => {
item.type = 'standardization';
tmpArr[i] = item;
})
}
let idx = tmpArr.length>0 ? tmpArr.length-1 : 0;
if (validators) {
validators.forEach((item: any, i: number) => {
item.type = 'validation';
tmpArr[idx+i] = item;
});
}
var hasSequence = _.find(tmpArr, (item: any) => {
return item.sequence != null && item.sequence != undefined;
}) !== undefined;
//if we dont have a sequence, add it in
if (!hasSequence) {
_.each(tmpArr, (item: any, idx: any) => {
item.sequence = idx;
});
}
arr = _.sortBy(tmpArr, 'sequence');
return arr;
}
} | the_stack |
import { Component, ComponentFactoryResolver, Injector, OnDestroy } from '@angular/core';
import { FormBuilder } from '@angular/forms';
import { Store } from '@ngrx/store';
import { BehaviorSubject, Observable, of as observableOf, Subscription } from 'rxjs';
import { distinctUntilChanged, filter, first, map, pairwise, startWith, withLatestFrom } from 'rxjs/operators';
import { EndpointsService } from '../../../../../core/src/core/endpoints.service';
import { safeUnsubscribe } from '../../../../../core/src/core/utils.service';
import {
ConnectEndpointConfig,
ConnectEndpointData,
ConnectEndpointService,
} from '../../../../../core/src/features/endpoints/connect.service';
import {
IActionMonitorComponentState,
} from '../../../../../core/src/shared/components/app-action-monitor-icon/app-action-monitor-icon.component';
import {
ITableListDataSource,
RowState,
} from '../../../../../core/src/shared/components/list/data-sources-controllers/list-data-source-types';
import { ITableColumn } from '../../../../../core/src/shared/components/list/list-table/table.types';
import { StepOnNextFunction } from '../../../../../core/src/shared/components/stepper/step/step.component';
import { AppState } from '../../../../../store/src/public-api';
import { ActionState } from '../../../../../store/src/reducers/api-request-reducer/types';
import { stratosEntityCatalog } from '../../../../../store/src/stratos-entity-catalog';
import { KUBERNETES_ENDPOINT_TYPE } from '../../kubernetes-entity-factory';
import { KubeConfigAuthHelper } from '../kube-config-auth.helper';
import { KubeConfigFileCluster, KubeConfigImportAction, KubeImportState } from '../kube-config.types';
import {
KubeConfigTableImportStatusComponent,
} from './kube-config-table-import-status/kube-config-table-import-status.component';
const REGISTER_ACTION = 'Register endpoint';
const CONNECT_ACTION = 'Connect endpoint';
@Component({
selector: 'app-kube-config-import',
templateUrl: './kube-config-import.component.html',
styleUrls: ['./kube-config-import.component.scss']
})
export class KubeConfigImportComponent implements OnDestroy {
done = new BehaviorSubject<boolean>(false);
done$ = this.done.asObservable();
busy = new BehaviorSubject<boolean>(false);
busy$ = this.busy.asObservable();
data = new BehaviorSubject<KubeConfigImportAction[]>([]);
data$ = this.data.asObservable();
public dataSource: ITableListDataSource<KubeConfigImportAction> = {
connect: () => this.data$,
disconnect: () => { },
// Ensure unique per entry to step (in case user went back step and updated)
trackBy: (index, item) => item.cluster.name + this.iteration,
isTableLoading$: this.data$.pipe(map(data => !(data && data.length > 0))),
getRowState: (row: KubeConfigImportAction): Observable<RowState> => {
return row ? row.state.asObservable() : observableOf({});
}
};
public columns: ITableColumn<KubeConfigImportAction>[] = [
{
columnId: 'action', headerCell: () => 'Action',
cellDefinition: {
valuePath: 'action'
},
cellFlex: '1',
},
{
columnId: 'description', headerCell: () => 'Description',
cellDefinition: {
valuePath: 'description'
},
cellFlex: '4',
},
// Right-hand column to show the action progress
{
columnId: 'monitorState',
cellComponent: KubeConfigTableImportStatusComponent,
cellConfig: (row) => row.actionState.asObservable(),
cellFlex: '0 0 24px'
}
];
subs: Subscription[] = [];
applyStarted: boolean;
private iteration = 0;
private connectService: ConnectEndpointService;
constructor(
public store: Store<AppState>,
public resolver: ComponentFactoryResolver,
private injector: Injector,
private fb: FormBuilder,
private endpointsService: EndpointsService,
) {
}
// Process the next action in the list
private processAction(actions: KubeConfigImportAction[]) {
if (actions.length === 0) {
// We are done
this.done.next(true);
this.busy.next(false);
return;
}
// Get the next action
const i = actions.shift();
if (i.action === REGISTER_ACTION) {
this.doRegister(i, actions);
} else if (i.action === CONNECT_ACTION) {
this.doConnect(i, actions);
} else {
// Do the next action
this.processAction(actions);
}
}
private doRegister(reg: KubeConfigImportAction, next: KubeConfigImportAction[]) {
const obs$ = this.registerEndpoint(
reg.cluster.name,
reg.cluster.cluster.server,
reg.cluster.cluster['insecure-skip-tls-verify'],
reg.cluster._subType
);
const mainObs$ = this.getUpdatingState(obs$).pipe(
startWith({ busy: true, error: false, completed: false })
);
this.subs.push(mainObs$.subscribe(reg.actionState));
const sub = reg.actionState.subscribe(progress => {
// Not sure what the status is used for?
reg.status = progress;
if (progress.error && progress.message) {
// Mark all dependency jobs as skip
next.forEach(action => {
if (action.depends === reg) {
// Mark it as skipped by setting the action to null
action.action = null;
action.state.next({ message: 'Skipping action as endpoint could not be registered', warning: true });
}
});
reg.state.next({ message: progress.message, error: true });
}
if (progress.completed) {
if (!progress.error) {
// If we created okay, then guid is in the message
reg.cluster._guid = progress.message;
}
sub.unsubscribe();
// Do the next one
this.processAction(next);
}
});
this.subs.push(sub);
}
private doConnect(connect: KubeConfigImportAction, next: KubeConfigImportAction[]) {
if (!connect.user) {
connect.state.next({ message: 'Can not connect - no user specified', error: true });
return;
}
const helper = new KubeConfigAuthHelper();
const data = helper.getAuthDataForConnect(this.resolver, this.injector, this.fb, connect.user);
if (data) {
const obs$ = this.connectEndpoint(connect, data);
// Echo obs$ to the behaviour subject
this.subs.push(obs$.subscribe(connect.actionState));
this.subs.push(connect.actionState.pipe(filter(status => status.completed), first()).subscribe(status => {
if (status.error) {
connect.state.next({ message: status.message, error: true });
}
this.processAction(next);
}));
} else {
connect.state.next({ message: 'Can not connect - could not get user auth data', error: true });
}
}
ngOnDestroy() {
safeUnsubscribe(...this.subs);
if (this.connectService) {
this.connectService.destroy();
}
}
// Register the endpoint
private registerEndpoint(name: string, url: string, skipSslValidation: boolean, subType: string) {
return stratosEntityCatalog.endpoint.api.register<ActionState>(
KUBERNETES_ENDPOINT_TYPE,
subType,
name,
url,
skipSslValidation,
'',
'',
false
).pipe(
filter(update => !!update)
);
}
// Connect to an endpoint
private connectEndpoint(action: KubeConfigImportAction, pData: ConnectEndpointData): Observable<IActionMonitorComponentState> {
const config: ConnectEndpointConfig = {
name: action.cluster.name,
guid: action.depends.cluster._guid || action.cluster._guid,
type: KUBERNETES_ENDPOINT_TYPE,
subType: action.user._authData.subType,
ssoAllowed: false
};
if (this.connectService) {
this.connectService.destroy();
}
this.connectService = new ConnectEndpointService(this.endpointsService, config);
this.connectService.setData(pData);
return this.connectService.submit().pipe(
map(updateSection => ({
busy: false,
error: !updateSection.success,
completed: true,
message: updateSection.errorMessage
})),
startWith({
message: '',
busy: true,
completed: false,
error: false
})
);
}
// Enter the step - process the list of clusters to import
onEnter = (data: KubeConfigFileCluster[]) => {
this.applyStarted = false;
this.iteration += 1;
const imports: KubeConfigImportAction[] = [];
data.forEach(item => {
if (item._selected) {
const register = {
action: REGISTER_ACTION,
description: `Register "${item.name}" with the URL "${item.cluster.server}"`,
cluster: item,
state: new BehaviorSubject<RowState>({}),
actionState: new BehaviorSubject<any>({}),
};
// Only include if the endpoint does not already exist
if (!item._guid) {
imports.push(register);
}
if (item._additionalUserInfo) {
return;
}
const user = item._users.find(u => u.name === item._user);
if (user) {
imports.push({
action: CONNECT_ACTION,
description: `Connect "${item.name}" with the user "${user.name}"`,
cluster: item,
user,
state: new BehaviorSubject<RowState>({}),
depends: register,
actionState: new BehaviorSubject<any>({}),
});
}
}
});
this.data.next(imports);
};
// Finish - go back to the endpoints view
onNext: StepOnNextFunction = () => {
if (this.applyStarted) {
// this.store.dispatch(new RouterNav({ path: ['endpoints'] }));
return observableOf({ success: true, redirect: true });
} else {
this.applyStarted = true;
this.busy.next(true);
this.data$.pipe(
filter((data => data && data.length > 0)),
first()
).subscribe(imports => {
// Go through the imports and dispatch the actions to perform them in sequence
this.processAction([...imports]);
});
return observableOf({ success: true, ignoreSuccess: true });
}
};
// These two should be somewhere else
private getUpdatingState(actionState$: Observable<ActionState>): Observable<KubeImportState> {
const completed$ = this.getHasCompletedObservable(actionState$.pipe(map(requestState => requestState.busy)));
return actionState$.pipe(
pairwise(),
withLatestFrom(completed$),
map(([[, requestState], completed]) => {
return {
busy: requestState.busy,
error: requestState.error,
completed,
message: requestState.message,
};
})
);
}
private getHasCompletedObservable(busy$: Observable<boolean>) {
return busy$.pipe(
distinctUntilChanged(),
pairwise(),
map(([oldBusy, newBusy]) => oldBusy && !newBusy),
startWith(false),
);
}
} | the_stack |
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { AbstractClient } from "../../../common/abstract_client"
import { ClientConfig } from "../../../common/interface"
import {
DuplicateImagePersonalRequest,
ManageExternalEndpointRequest,
DescribeImagePersonalResponse,
DescribeUserQuotaPersonalRequest,
WebhookTarget,
DescribeReplicationInstancesResponse,
DescribeReplicationInstanceCreateTasksResponse,
WebhookTriggerLog,
AccessVpc,
ModifyTagRetentionRuleRequest,
ModifyRepositoryResponse,
TriggerInvokePara,
DescribeNamespacesResponse,
TriggerLogResp,
DownloadHelmChartRequest,
RetentionRule,
CreateInstanceResponse,
DeleteInstanceTokenRequest,
TaskDetail,
ModifyRepositoryRequest,
RegistryCondition,
DescribeInternalEndpointDnsStatusRequest,
CreateApplicationTriggerPersonalRequest,
AutoDelStrategyInfo,
DeleteInternalEndpointDnsRequest,
ValidateNamespaceExistPersonalRequest,
ModifyInstanceRequest,
RenewInstanceResponse,
CreateImmutableTagRulesRequest,
DescribeRepositoriesResponse,
VpcAndDomainInfo,
DeleteInstanceTokenResponse,
DescribeInstancesResponse,
CreateReplicationInstanceRequest,
ModifyInstanceTokenResponse,
DescribeApplicationTriggerPersonalRequest,
FavorResp,
DeleteNamespacePersonalRequest,
NamespaceInfo,
CreateMultipleSecurityPolicyResponse,
CreateTagRetentionRuleResponse,
Limit,
DescribeChartDownloadInfoResponse,
DescribeExternalEndpointStatusRequest,
DeleteRepositoryResponse,
DeleteImagePersonalResponse,
DescribeWebhookTriggerLogResponse,
DownloadHelmChartResponse,
ManageReplicationRequest,
DeleteWebhookTriggerResponse,
DeleteImageLifecycleGlobalPersonalResponse,
ModifySecurityPolicyRequest,
DescribeReplicationInstanceSyncStatusResponse,
ModifyImmutableTagRulesResponse,
Tag,
DupImageTagResp,
DeleteApplicationTriggerPersonalResponse,
DescribeRepositoryFilterPersonalRequest,
DescribeTagRetentionExecutionTaskResponse,
DescribeInternalEndpointsResponse,
DeleteImmutableTagRulesResponse,
DescribeRepositoryPersonalRequest,
AutoDelStrategyInfoResp,
TriggerResp,
DeleteApplicationTriggerPersonalRequest,
SearchUserRepositoryResp,
CreateTagRetentionRuleRequest,
DuplicateImagePersonalResponse,
DescribeImageLifecyclePersonalResponse,
DescribeInstanceStatusResponse,
ModifyInstanceTokenRequest,
DeleteImageLifecyclePersonalResponse,
CreateNamespaceResponse,
ModifyImmutableTagRulesRequest,
DescribeRepositoryOwnerPersonalResponse,
VpcPrivateDomainStatus,
DescribeSecurityPoliciesResponse,
DescribeReplicationInstancesRequest,
CreateImageLifecyclePersonalResponse,
RepoIsExistResp,
TcrImageInfo,
DescribeImageLifecycleGlobalPersonalResponse,
CreateNamespacePersonalResponse,
DescribeReplicationInstanceSyncStatusRequest,
DeleteInstanceResponse,
DeleteImageLifecycleGlobalPersonalRequest,
DescribeInstanceStatusRequest,
ModifyWebhookTriggerRequest,
CheckInstanceNameRequest,
DeleteNamespaceResponse,
TagInfoResp,
Favors,
CreateWebhookTriggerRequest,
DescribeRepositoryPersonalResponse,
CreateSecurityPolicyResponse,
DescribeRepositoriesRequest,
CreateUserPersonalRequest,
ModifyNamespaceResponse,
ValidateRepositoryExistPersonalRequest,
ModifyUserPasswordPersonalResponse,
TcrNamespaceInfo,
DescribeImagesResponse,
ModifyRepositoryInfoPersonalResponse,
DescribeWebhookTriggerLogRequest,
RenewInstanceRequest,
DescribeImageFilterPersonalRequest,
DescribeTagRetentionExecutionTaskRequest,
ReplicationRule,
RepoInfoResp,
DeleteTagRetentionRuleResponse,
DeleteMultipleSecurityPolicyRequest,
DeleteSecurityPolicyResponse,
DescribeInternalEndpointDnsStatusResponse,
WebhookTrigger,
RegistryStatus,
SecurityPolicy,
DescribeNamespacePersonalRequest,
DeleteRepositoryPersonalResponse,
CreateInstanceTokenResponse,
DescribeApplicationTriggerLogPersonalResp,
DeleteImagePersonalRequest,
DescribeApplicationTriggerPersonalResponse,
RetentionTask,
NamespaceInfoResp,
CreateRepositoryPersonalRequest,
DescribeImageFilterPersonalResponse,
CreateImageLifecyclePersonalRequest,
DeleteWebhookTriggerRequest,
TriggerInvokeResult,
CreateUserPersonalResponse,
DescribeWebhookTriggerResponse,
DescribeImageManifestsRequest,
RegistryChargePrepaid,
ModifyNamespaceRequest,
ModifyRepositoryAccessPersonalRequest,
TagSpecification,
CreateMultipleSecurityPolicyRequest,
DescribeNamespacesRequest,
DescribeImageLifecycleGlobalPersonalRequest,
DescribeImageLifecyclePersonalRequest,
DeleteSecurityPolicyRequest,
RepositoryInfoResp,
CreateInstanceRequest,
DescribeInstanceTokenRequest,
BatchDeleteRepositoryPersonalResponse,
CreateNamespaceRequest,
BatchDeleteRepositoryPersonalRequest,
Registry,
DescribeChartDownloadInfoRequest,
ValidateRepositoryExistPersonalResponse,
DescribeExternalEndpointStatusResponse,
CheckInstanceResponse,
NamespaceIsExistsResp,
DescribeInstancesRequest,
CreateInternalEndpointDnsRequest,
TriggerInvokeCondition,
DescribeImmutableTagRulesRequest,
Filter,
RetentionExecution,
ManageReplicationResponse,
DescribeReplicationInstanceCreateTasksRequest,
ModifyWebhookTriggerResponse,
RepoInfo,
ManageImageLifecycleGlobalPersonalRequest,
DescribeUserQuotaPersonalResponse,
DescribeImagePersonalRequest,
ModifySecurityPolicyResponse,
DeleteImageLifecyclePersonalRequest,
ModifyApplicationTriggerPersonalResponse,
DeleteInstanceRequest,
DescribeImageManifestsResponse,
DescribeNamespacePersonalResponse,
DeleteNamespacePersonalResponse,
ImmutableTagRule,
Header,
RetentionPolicy,
CreateSecurityPolicyRequest,
DeleteImageRequest,
DescribeRepositoryOwnerPersonalRequest,
ModifyRepositoryInfoPersonalRequest,
DescribeApplicationTriggerLogPersonalRequest,
DescribeFavorRepositoryPersonalRequest,
DescribeApplicationTriggerLogPersonalResponse,
DeleteMultipleSecurityPolicyResponse,
ManageInternalEndpointResponse,
CreateRepositoryPersonalResponse,
DescribeRepositoryFilterPersonalResponse,
CreateTagRetentionExecutionResponse,
DescribeFavorRepositoryPersonalResponse,
CheckInstanceNameResponse,
ManageImageLifecycleGlobalPersonalResponse,
DescribeTagRetentionRulesResponse,
ModifyRepositoryAccessPersonalResponse,
ManageExternalEndpointResponse,
DescribeImmutableTagRulesResponse,
ModifyApplicationTriggerPersonalRequest,
CreateReplicationInstanceResponse,
CreateInstanceTokenRequest,
ModifyUserPasswordPersonalRequest,
PeerReplicationOption,
DescribeSecurityPoliciesRequest,
ModifyInstanceResponse,
ReplicationRegistry,
DescribeInternalEndpointsRequest,
ValidateNamespaceExistPersonalResponse,
CheckInstanceRequest,
DescribeApplicationTriggerPersonalResp,
TagInfo,
CreateRepositoryRequest,
DeleteImageResponse,
DescribeWebhookTriggerRequest,
DeleteNamespaceRequest,
BatchDeleteImagePersonalRequest,
DescribeImagesRequest,
ModifyTagRetentionRuleResponse,
DescribeTagRetentionExecutionRequest,
CreateRepositoryResponse,
DescribeTagRetentionRulesRequest,
RespLimit,
CreateImmutableTagRulesResponse,
DescribeInstanceTokenResponse,
SameImagesResp,
DescribeTagRetentionExecutionResponse,
CreateNamespacePersonalRequest,
DeleteImmutableTagRulesRequest,
CreateWebhookTriggerResponse,
ReplicationFilter,
DeleteTagRetentionRuleRequest,
TcrRepositoryInfo,
TcrInstanceToken,
DeleteRepositoryRequest,
CreateInternalEndpointDnsResponse,
CreateTagRetentionExecutionRequest,
ReplicationLog,
CreateApplicationTriggerPersonalResponse,
ManageInternalEndpointRequest,
BatchDeleteImagePersonalResponse,
DeleteInternalEndpointDnsResponse,
DeleteRepositoryPersonalRequest,
} from "./tcr_models"
/**
* tcr client
* @class
*/
export class Client extends AbstractClient {
constructor(clientConfig: ClientConfig) {
super("tcr.tencentcloudapi.com", "2019-09-24", clientConfig)
}
/**
* 用于获取个人版全局镜像版本自动清理策略
*/
async DescribeImageLifecycleGlobalPersonal(
req?: DescribeImageLifecycleGlobalPersonalRequest,
cb?: (error: string, rep: DescribeImageLifecycleGlobalPersonalResponse) => void
): Promise<DescribeImageLifecycleGlobalPersonalResponse> {
return this.request("DescribeImageLifecycleGlobalPersonal", req, cb)
}
/**
* 用于在个人版中创建清理策略
*/
async CreateImageLifecyclePersonal(
req: CreateImageLifecyclePersonalRequest,
cb?: (error: string, rep: CreateImageLifecyclePersonalResponse) => void
): Promise<CreateImageLifecyclePersonalResponse> {
return this.request("CreateImageLifecyclePersonal", req, cb)
}
/**
* 删除实例公网访问白名单策略
*/
async DeleteSecurityPolicy(
req: DeleteSecurityPolicyRequest,
cb?: (error: string, rep: DeleteSecurityPolicyResponse) => void
): Promise<DeleteSecurityPolicyResponse> {
return this.request("DeleteSecurityPolicy", req, cb)
}
/**
* 用于获取个人版镜像仓库tag列表
*/
async DescribeImagePersonal(
req: DescribeImagePersonalRequest,
cb?: (error: string, rep: DescribeImagePersonalResponse) => void
): Promise<DescribeImagePersonalResponse> {
return this.request("DescribeImagePersonal", req, cb)
}
/**
* 用于在企业版中创建命名空间
*/
async CreateNamespace(
req: CreateNamespaceRequest,
cb?: (error: string, rep: CreateNamespaceResponse) => void
): Promise<CreateNamespaceResponse> {
return this.request("CreateNamespace", req, cb)
}
/**
* 查询从实例列表
*/
async DescribeReplicationInstances(
req: DescribeReplicationInstancesRequest,
cb?: (error: string, rep: DescribeReplicationInstancesResponse) => void
): Promise<DescribeReplicationInstancesResponse> {
return this.request("DescribeReplicationInstances", req, cb)
}
/**
* 查询镜像仓库列表或指定镜像仓库信息
*/
async DescribeRepositories(
req: DescribeRepositoriesRequest,
cb?: (error: string, rep: DescribeRepositoriesResponse) => void
): Promise<DescribeRepositoriesResponse> {
return this.request("DescribeRepositories", req, cb)
}
/**
* 管理实例同步
*/
async ManageReplication(
req: ManageReplicationRequest,
cb?: (error: string, rep: ManageReplicationResponse) => void
): Promise<ManageReplicationResponse> {
return this.request("ManageReplication", req, cb)
}
/**
* 获取触发器日志
*/
async DescribeWebhookTriggerLog(
req: DescribeWebhookTriggerLogRequest,
cb?: (error: string, rep: DescribeWebhookTriggerLogResponse) => void
): Promise<DescribeWebhookTriggerLogResponse> {
return this.request("DescribeWebhookTriggerLog", req, cb)
}
/**
* 查询容器镜像Manifest信息
*/
async DescribeImageManifests(
req: DescribeImageManifestsRequest,
cb?: (error: string, rep: DescribeImageManifestsResponse) => void
): Promise<DescribeImageManifestsResponse> {
return this.request("DescribeImageManifests", req, cb)
}
/**
* 用于设置个人版全局镜像版本自动清理策略
*/
async ManageImageLifecycleGlobalPersonal(
req: ManageImageLifecycleGlobalPersonalRequest,
cb?: (error: string, rep: ManageImageLifecycleGlobalPersonalResponse) => void
): Promise<ManageImageLifecycleGlobalPersonalResponse> {
return this.request("ManageImageLifecycleGlobalPersonal", req, cb)
}
/**
* 删除镜像不可变规则
*/
async DeleteImmutableTagRules(
req: DeleteImmutableTagRulesRequest,
cb?: (error: string, rep: DeleteImmutableTagRulesResponse) => void
): Promise<DeleteImmutableTagRulesResponse> {
return this.request("DeleteImmutableTagRules", req, cb)
}
/**
* 用于在个人版中删除tag
*/
async DeleteImagePersonal(
req: DeleteImagePersonalRequest,
cb?: (error: string, rep: DeleteImagePersonalResponse) => void
): Promise<DeleteImagePersonalResponse> {
return this.request("DeleteImagePersonal", req, cb)
}
/**
* 更新触发器
*/
async ModifyWebhookTrigger(
req: ModifyWebhookTriggerRequest,
cb?: (error: string, rep: ModifyWebhookTriggerResponse) => void
): Promise<ModifyWebhookTriggerResponse> {
return this.request("ModifyWebhookTrigger", req, cb)
}
/**
* 用于个人版镜像仓库中批量删除镜像仓库
*/
async BatchDeleteRepositoryPersonal(
req: BatchDeleteRepositoryPersonalRequest,
cb?: (error: string, rep: BatchDeleteRepositoryPersonalResponse) => void
): Promise<BatchDeleteRepositoryPersonalResponse> {
return this.request("BatchDeleteRepositoryPersonal", req, cb)
}
/**
* 删除触发器
*/
async DeleteWebhookTrigger(
req: DeleteWebhookTriggerRequest,
cb?: (error: string, rep: DeleteWebhookTriggerResponse) => void
): Promise<DeleteWebhookTriggerResponse> {
return this.request("DeleteWebhookTrigger", req, cb)
}
/**
* 查询创建从实例任务状态
*/
async DescribeReplicationInstanceCreateTasks(
req: DescribeReplicationInstanceCreateTasksRequest,
cb?: (error: string, rep: DescribeReplicationInstanceCreateTasksResponse) => void
): Promise<DescribeReplicationInstanceCreateTasksResponse> {
return this.request("DescribeReplicationInstanceCreateTasks", req, cb)
}
/**
* 用于获取个人版仓库中自动清理策略
*/
async DescribeImageLifecyclePersonal(
req: DescribeImageLifecyclePersonalRequest,
cb?: (error: string, rep: DescribeImageLifecyclePersonalResponse) => void
): Promise<DescribeImageLifecyclePersonalResponse> {
return this.request("DescribeImageLifecyclePersonal", req, cb)
}
/**
* 查询个人收藏仓库
*/
async DescribeFavorRepositoryPersonal(
req: DescribeFavorRepositoryPersonalRequest,
cb?: (error: string, rep: DescribeFavorRepositoryPersonalResponse) => void
): Promise<DescribeFavorRepositoryPersonalResponse> {
return this.request("DescribeFavorRepositoryPersonal", req, cb)
}
/**
* 用于在TCR实例中,创建多个白名单策略
*/
async CreateMultipleSecurityPolicy(
req: CreateMultipleSecurityPolicyRequest,
cb?: (error: string, rep: CreateMultipleSecurityPolicyResponse) => void
): Promise<CreateMultipleSecurityPolicyResponse> {
return this.request("CreateMultipleSecurityPolicy", req, cb)
}
/**
* 查询版本保留规则
*/
async DescribeTagRetentionRules(
req: DescribeTagRetentionRulesRequest,
cb?: (error: string, rep: DescribeTagRetentionRulesResponse) => void
): Promise<DescribeTagRetentionRulesResponse> {
return this.request("DescribeTagRetentionRules", req, cb)
}
/**
* 用于在个人版镜像仓库中复制镜像版本
*/
async DuplicateImagePersonal(
req: DuplicateImagePersonalRequest,
cb?: (error: string, rep: DuplicateImagePersonalResponse) => void
): Promise<DuplicateImagePersonalResponse> {
return this.request("DuplicateImagePersonal", req, cb)
}
/**
* 创建版本保留规则
*/
async CreateTagRetentionRule(
req: CreateTagRetentionRuleRequest,
cb?: (error: string, rep: CreateTagRetentionRuleResponse) => void
): Promise<CreateTagRetentionRuleResponse> {
return this.request("CreateTagRetentionRule", req, cb)
}
/**
* 用于删除个人版全局镜像版本自动清理策略
*/
async DeleteImageLifecycleGlobalPersonal(
req?: DeleteImageLifecycleGlobalPersonalRequest,
cb?: (error: string, rep: DeleteImageLifecycleGlobalPersonalResponse) => void
): Promise<DeleteImageLifecycleGlobalPersonalResponse> {
return this.request("DeleteImageLifecycleGlobalPersonal", req, cb)
}
/**
* 查询从实例同步状态
*/
async DescribeReplicationInstanceSyncStatus(
req: DescribeReplicationInstanceSyncStatusRequest,
cb?: (error: string, rep: DescribeReplicationInstanceSyncStatusResponse) => void
): Promise<DescribeReplicationInstanceSyncStatusResponse> {
return this.request("DescribeReplicationInstanceSyncStatus", req, cb)
}
/**
* 删除共享版命名空间
*/
async DeleteNamespacePersonal(
req: DeleteNamespacePersonalRequest,
cb?: (error: string, rep: DeleteNamespacePersonalResponse) => void
): Promise<DeleteNamespacePersonalResponse> {
return this.request("DeleteNamespacePersonal", req, cb)
}
/**
* 用于更新个人版镜像仓库的访问属性
*/
async ModifyRepositoryAccessPersonal(
req: ModifyRepositoryAccessPersonalRequest,
cb?: (error: string, rep: ModifyRepositoryAccessPersonalResponse) => void
): Promise<ModifyRepositoryAccessPersonalResponse> {
return this.request("ModifyRepositoryAccessPersonal", req, cb)
}
/**
* 用于在个人版镜像仓库中删除仓库Tag自动清理策略
*/
async DeleteImageLifecyclePersonal(
req: DeleteImageLifecyclePersonalRequest,
cb?: (error: string, rep: DeleteImageLifecyclePersonalResponse) => void
): Promise<DeleteImageLifecyclePersonalResponse> {
return this.request("DeleteImageLifecyclePersonal", req, cb)
}
/**
* 更新实例信息
*/
async ModifyInstance(
req: ModifyInstanceRequest,
cb?: (error: string, rep: ModifyInstanceResponse) => void
): Promise<ModifyInstanceResponse> {
return this.request("ModifyInstance", req, cb)
}
/**
* 用于查询应用更新触发器
*/
async DescribeApplicationTriggerPersonal(
req: DescribeApplicationTriggerPersonalRequest,
cb?: (error: string, rep: DescribeApplicationTriggerPersonalResponse) => void
): Promise<DescribeApplicationTriggerPersonalResponse> {
return this.request("DescribeApplicationTriggerPersonal", req, cb)
}
/**
* 查询版本保留执行记录
*/
async DescribeTagRetentionExecution(
req: DescribeTagRetentionExecutionRequest,
cb?: (error: string, rep: DescribeTagRetentionExecutionResponse) => void
): Promise<DescribeTagRetentionExecutionResponse> {
return this.request("DescribeTagRetentionExecution", req, cb)
}
/**
* 用于个人版镜像仓库中删除
*/
async DeleteRepositoryPersonal(
req: DeleteRepositoryPersonalRequest,
cb?: (error: string, rep: DeleteRepositoryPersonalResponse) => void
): Promise<DeleteRepositoryPersonalResponse> {
return this.request("DeleteRepositoryPersonal", req, cb)
}
/**
* 用于在个人版镜像仓库中更新容器镜像描述
*/
async ModifyRepositoryInfoPersonal(
req: ModifyRepositoryInfoPersonalRequest,
cb?: (error: string, rep: ModifyRepositoryInfoPersonalResponse) => void
): Promise<ModifyRepositoryInfoPersonalResponse> {
return this.request("ModifyRepositoryInfoPersonal", req, cb)
}
/**
* 手动执行版本保留
*/
async CreateTagRetentionExecution(
req: CreateTagRetentionExecutionRequest,
cb?: (error: string, rep: CreateTagRetentionExecutionResponse) => void
): Promise<CreateTagRetentionExecutionResponse> {
return this.request("CreateTagRetentionExecution", req, cb)
}
/**
* 检查待创建的实例名称是否符合规范
*/
async CheckInstanceName(
req: CheckInstanceNameRequest,
cb?: (error: string, rep: CheckInstanceNameResponse) => void
): Promise<CheckInstanceNameResponse> {
return this.request("CheckInstanceName", req, cb)
}
/**
* 用于校验企业版实例信息
*/
async CheckInstance(
req: CheckInstanceRequest,
cb?: (error: string, rep: CheckInstanceResponse) => void
): Promise<CheckInstanceResponse> {
return this.request("CheckInstance", req, cb)
}
/**
* 查询个人版命名空间信息
*/
async DescribeNamespacePersonal(
req: DescribeNamespacePersonalRequest,
cb?: (error: string, rep: DescribeNamespacePersonalResponse) => void
): Promise<DescribeNamespacePersonalResponse> {
return this.request("DescribeNamespacePersonal", req, cb)
}
/**
* 查询个人版仓库信息
*/
async DescribeRepositoryPersonal(
req: DescribeRepositoryPersonalRequest,
cb?: (error: string, rep: DescribeRepositoryPersonalResponse) => void
): Promise<DescribeRepositoryPersonalResponse> {
return this.request("DescribeRepositoryPersonal", req, cb)
}
/**
* 预付费实例续费,同时支持按量计费转包年包月
*/
async RenewInstance(
req: RenewInstanceRequest,
cb?: (error: string, rep: RenewInstanceResponse) => void
): Promise<RenewInstanceResponse> {
return this.request("RenewInstance", req, cb)
}
/**
* 创建实例
*/
async CreateInstance(
req: CreateInstanceRequest,
cb?: (error: string, rep: CreateInstanceResponse) => void
): Promise<CreateInstanceResponse> {
return this.request("CreateInstance", req, cb)
}
/**
* 查询实例公网访问白名单策略
*/
async DescribeSecurityPolicies(
req: DescribeSecurityPoliciesRequest,
cb?: (error: string, rep: DescribeSecurityPoliciesResponse) => void
): Promise<DescribeSecurityPoliciesResponse> {
return this.request("DescribeSecurityPolicies", req, cb)
}
/**
* 用于在个人版镜像仓库中批量删除Tag
*/
async BatchDeleteImagePersonal(
req: BatchDeleteImagePersonalRequest,
cb?: (error: string, rep: BatchDeleteImagePersonalResponse) => void
): Promise<BatchDeleteImagePersonalResponse> {
return this.request("BatchDeleteImagePersonal", req, cb)
}
/**
* 创建从实例
*/
async CreateReplicationInstance(
req: CreateReplicationInstanceRequest,
cb?: (error: string, rep: CreateReplicationInstanceResponse) => void
): Promise<CreateReplicationInstanceResponse> {
return this.request("CreateReplicationInstance", req, cb)
}
/**
* 用于企业版创建镜像仓库
*/
async CreateRepository(
req: CreateRepositoryRequest,
cb?: (error: string, rep: CreateRepositoryResponse) => void
): Promise<CreateRepositoryResponse> {
return this.request("CreateRepository", req, cb)
}
/**
* 管理实例公网访问
*/
async ManageExternalEndpoint(
req: ManageExternalEndpointRequest,
cb?: (error: string, rep: ManageExternalEndpointResponse) => void
): Promise<ManageExternalEndpointResponse> {
return this.request("ManageExternalEndpoint", req, cb)
}
/**
* 更新实例公网访问白名单
*/
async ModifySecurityPolicy(
req: ModifySecurityPolicyRequest,
cb?: (error: string, rep: ModifySecurityPolicyResponse) => void
): Promise<ModifySecurityPolicyResponse> {
return this.request("ModifySecurityPolicy", req, cb)
}
/**
* 查询版本保留执行任务
*/
async DescribeTagRetentionExecutionTask(
req: DescribeTagRetentionExecutionTaskRequest,
cb?: (error: string, rep: DescribeTagRetentionExecutionTaskResponse) => void
): Promise<DescribeTagRetentionExecutionTaskResponse> {
return this.request("DescribeTagRetentionExecutionTask", req, cb)
}
/**
* 用于删除实例多个公网访问白名单策略
*/
async DeleteMultipleSecurityPolicy(
req: DeleteMultipleSecurityPolicyRequest,
cb?: (error: string, rep: DeleteMultipleSecurityPolicyResponse) => void
): Promise<DeleteMultipleSecurityPolicyResponse> {
return this.request("DeleteMultipleSecurityPolicy", req, cb)
}
/**
* 用于在个人版镜像仓库中,获取满足输入搜索条件的用户镜像仓库
*/
async DescribeRepositoryFilterPersonal(
req: DescribeRepositoryFilterPersonalRequest,
cb?: (error: string, rep: DescribeRepositoryFilterPersonalResponse) => void
): Promise<DescribeRepositoryFilterPersonalResponse> {
return this.request("DescribeRepositoryFilterPersonal", req, cb)
}
/**
* 创建个人用户
*/
async CreateUserPersonal(
req: CreateUserPersonalRequest,
cb?: (error: string, rep: CreateUserPersonalResponse) => void
): Promise<CreateUserPersonalResponse> {
return this.request("CreateUserPersonal", req, cb)
}
/**
* 更新命名空间信息,当前仅支持修改命名空间访问级别
*/
async ModifyNamespace(
req: ModifyNamespaceRequest,
cb?: (error: string, rep: ModifyNamespaceResponse) => void
): Promise<ModifyNamespaceResponse> {
return this.request("ModifyNamespace", req, cb)
}
/**
* 列出镜像不可变规则
*/
async DescribeImmutableTagRules(
req: DescribeImmutableTagRulesRequest,
cb?: (error: string, rep: DescribeImmutableTagRulesResponse) => void
): Promise<DescribeImmutableTagRulesResponse> {
return this.request("DescribeImmutableTagRules", req, cb)
}
/**
* 创建实例公网访问白名单策略
*/
async CreateSecurityPolicy(
req: CreateSecurityPolicyRequest,
cb?: (error: string, rep: CreateSecurityPolicyResponse) => void
): Promise<CreateSecurityPolicyResponse> {
return this.request("CreateSecurityPolicy", req, cb)
}
/**
* 删除镜像仓库企业版实例
*/
async DeleteInstance(
req: DeleteInstanceRequest,
cb?: (error: string, rep: DeleteInstanceResponse) => void
): Promise<DeleteInstanceResponse> {
return this.request("DeleteInstance", req, cb)
}
/**
* 更新镜像仓库信息,可修改仓库描述信息
*/
async ModifyRepository(
req: ModifyRepositoryRequest,
cb?: (error: string, rep: ModifyRepositoryResponse) => void
): Promise<ModifyRepositoryResponse> {
return this.request("ModifyRepository", req, cb)
}
/**
* 用于在企业版中返回Chart的下载信息
*/
async DescribeChartDownloadInfo(
req: DescribeChartDownloadInfoRequest,
cb?: (error: string, rep: DescribeChartDownloadInfoResponse) => void
): Promise<DescribeChartDownloadInfoResponse> {
return this.request("DescribeChartDownloadInfo", req, cb)
}
/**
* 查询个人用户配额
*/
async DescribeUserQuotaPersonal(
req?: DescribeUserQuotaPersonalRequest,
cb?: (error: string, rep: DescribeUserQuotaPersonalResponse) => void
): Promise<DescribeUserQuotaPersonalResponse> {
return this.request("DescribeUserQuotaPersonal", req, cb)
}
/**
* 创建镜像不可变规则
*/
async CreateImmutableTagRules(
req: CreateImmutableTagRulesRequest,
cb?: (error: string, rep: CreateImmutableTagRulesResponse) => void
): Promise<CreateImmutableTagRulesResponse> {
return this.request("CreateImmutableTagRules", req, cb)
}
/**
* 查询长期访问凭证信息
*/
async DescribeInstanceToken(
req: DescribeInstanceTokenRequest,
cb?: (error: string, rep: DescribeInstanceTokenResponse) => void
): Promise<DescribeInstanceTokenResponse> {
return this.request("DescribeInstanceToken", req, cb)
}
/**
* 用于在TCR中下载helm chart
*/
async DownloadHelmChart(
req: DownloadHelmChartRequest,
cb?: (error: string, rep: DownloadHelmChartResponse) => void
): Promise<DownloadHelmChartResponse> {
return this.request("DownloadHelmChart", req, cb)
}
/**
* 更新镜像不可变规则
*/
async ModifyImmutableTagRules(
req: ModifyImmutableTagRulesRequest,
cb?: (error: string, rep: ModifyImmutableTagRulesResponse) => void
): Promise<ModifyImmutableTagRulesResponse> {
return this.request("ModifyImmutableTagRules", req, cb)
}
/**
* 用于删除应用更新触发器
*/
async DeleteApplicationTriggerPersonal(
req: DeleteApplicationTriggerPersonalRequest,
cb?: (error: string, rep: DeleteApplicationTriggerPersonalResponse) => void
): Promise<DeleteApplicationTriggerPersonalResponse> {
return this.request("DeleteApplicationTriggerPersonal", req, cb)
}
/**
* 创建tcr内网私有域名解析
*/
async CreateInternalEndpointDns(
req: CreateInternalEndpointDnsRequest,
cb?: (error: string, rep: CreateInternalEndpointDnsResponse) => void
): Promise<CreateInternalEndpointDnsResponse> {
return this.request("CreateInternalEndpointDns", req, cb)
}
/**
* 更新实例内指定长期访问凭证的启用状态
*/
async ModifyInstanceToken(
req: ModifyInstanceTokenRequest,
cb?: (error: string, rep: ModifyInstanceTokenResponse) => void
): Promise<ModifyInstanceTokenResponse> {
return this.request("ModifyInstanceToken", req, cb)
}
/**
* 创建触发器
*/
async CreateWebhookTrigger(
req: CreateWebhookTriggerRequest,
cb?: (error: string, rep: CreateWebhookTriggerResponse) => void
): Promise<CreateWebhookTriggerResponse> {
return this.request("CreateWebhookTrigger", req, cb)
}
/**
* 用于创建应用更新触发器
*/
async CreateApplicationTriggerPersonal(
req: CreateApplicationTriggerPersonalRequest,
cb?: (error: string, rep: CreateApplicationTriggerPersonalResponse) => void
): Promise<CreateApplicationTriggerPersonalResponse> {
return this.request("CreateApplicationTriggerPersonal", req, cb)
}
/**
* 用于判断个人版仓库是否存在
*/
async ValidateRepositoryExistPersonal(
req: ValidateRepositoryExistPersonalRequest,
cb?: (error: string, rep: ValidateRepositoryExistPersonalResponse) => void
): Promise<ValidateRepositoryExistPersonalResponse> {
return this.request("ValidateRepositoryExistPersonal", req, cb)
}
/**
* 用于修改应用更新触发器
*/
async ModifyApplicationTriggerPersonal(
req: ModifyApplicationTriggerPersonalRequest,
cb?: (error: string, rep: ModifyApplicationTriggerPersonalResponse) => void
): Promise<ModifyApplicationTriggerPersonalResponse> {
return this.request("ModifyApplicationTriggerPersonal", req, cb)
}
/**
* 查询命名空间列表或指定命名空间信息
*/
async DescribeNamespaces(
req: DescribeNamespacesRequest,
cb?: (error: string, rep: DescribeNamespacesResponse) => void
): Promise<DescribeNamespacesResponse> {
return this.request("DescribeNamespaces", req, cb)
}
/**
* 删除tcr内网私有域名解析
*/
async DeleteInternalEndpointDns(
req: DeleteInternalEndpointDnsRequest,
cb?: (error: string, rep: DeleteInternalEndpointDnsResponse) => void
): Promise<DeleteInternalEndpointDnsResponse> {
return this.request("DeleteInternalEndpointDns", req, cb)
}
/**
* 更新版本保留规则
*/
async ModifyTagRetentionRule(
req: ModifyTagRetentionRuleRequest,
cb?: (error: string, rep: ModifyTagRetentionRuleResponse) => void
): Promise<ModifyTagRetentionRuleResponse> {
return this.request("ModifyTagRetentionRule", req, cb)
}
/**
* 用于在个人版中查询与指定tag镜像内容相同的tag列表
*/
async DescribeImageFilterPersonal(
req: DescribeImageFilterPersonalRequest,
cb?: (error: string, rep: DescribeImageFilterPersonalResponse) => void
): Promise<DescribeImageFilterPersonalResponse> {
return this.request("DescribeImageFilterPersonal", req, cb)
}
/**
* 删除镜像仓库
*/
async DeleteRepository(
req: DeleteRepositoryRequest,
cb?: (error: string, rep: DeleteRepositoryResponse) => void
): Promise<DeleteRepositoryResponse> {
return this.request("DeleteRepository", req, cb)
}
/**
* 用于在个人版中获取用户全部的镜像仓库列表
*/
async DescribeRepositoryOwnerPersonal(
req: DescribeRepositoryOwnerPersonalRequest,
cb?: (error: string, rep: DescribeRepositoryOwnerPersonalResponse) => void
): Promise<DescribeRepositoryOwnerPersonalResponse> {
return this.request("DescribeRepositoryOwnerPersonal", req, cb)
}
/**
* 查询镜像版本列表或指定容器镜像信息
*/
async DescribeImages(
req: DescribeImagesRequest,
cb?: (error: string, rep: DescribeImagesResponse) => void
): Promise<DescribeImagesResponse> {
return this.request("DescribeImages", req, cb)
}
/**
* 删除版本保留规则
*/
async DeleteTagRetentionRule(
req: DeleteTagRetentionRuleRequest,
cb?: (error: string, rep: DeleteTagRetentionRuleResponse) => void
): Promise<DeleteTagRetentionRuleResponse> {
return this.request("DeleteTagRetentionRule", req, cb)
}
/**
* 删除命名空间
*/
async DeleteNamespace(
req: DeleteNamespaceRequest,
cb?: (error: string, rep: DeleteNamespaceResponse) => void
): Promise<DeleteNamespaceResponse> {
return this.request("DeleteNamespace", req, cb)
}
/**
* 查询实例信息
*/
async DescribeInstances(
req: DescribeInstancesRequest,
cb?: (error: string, rep: DescribeInstancesResponse) => void
): Promise<DescribeInstancesResponse> {
return this.request("DescribeInstances", req, cb)
}
/**
* 用于查询应用更新触发器触发日志
*/
async DescribeApplicationTriggerLogPersonal(
req: DescribeApplicationTriggerLogPersonalRequest,
cb?: (error: string, rep: DescribeApplicationTriggerLogPersonalResponse) => void
): Promise<DescribeApplicationTriggerLogPersonalResponse> {
return this.request("DescribeApplicationTriggerLogPersonal", req, cb)
}
/**
* 删除长期访问凭证
*/
async DeleteInstanceToken(
req: DeleteInstanceTokenRequest,
cb?: (error: string, rep: DeleteInstanceTokenResponse) => void
): Promise<DeleteInstanceTokenResponse> {
return this.request("DeleteInstanceToken", req, cb)
}
/**
* 修改个人用户登录密码
*/
async ModifyUserPasswordPersonal(
req: ModifyUserPasswordPersonalRequest,
cb?: (error: string, rep: ModifyUserPasswordPersonalResponse) => void
): Promise<ModifyUserPasswordPersonalResponse> {
return this.request("ModifyUserPasswordPersonal", req, cb)
}
/**
* 查询触发器
*/
async DescribeWebhookTrigger(
req: DescribeWebhookTriggerRequest,
cb?: (error: string, rep: DescribeWebhookTriggerResponse) => void
): Promise<DescribeWebhookTriggerResponse> {
return this.request("DescribeWebhookTrigger", req, cb)
}
/**
* 查询实例内网访问VPC链接
*/
async DescribeInternalEndpoints(
req: DescribeInternalEndpointsRequest,
cb?: (error: string, rep: DescribeInternalEndpointsResponse) => void
): Promise<DescribeInternalEndpointsResponse> {
return this.request("DescribeInternalEndpoints", req, cb)
}
/**
* 查询实例当前状态以及过程信息
*/
async DescribeInstanceStatus(
req: DescribeInstanceStatusRequest,
cb?: (error: string, rep: DescribeInstanceStatusResponse) => void
): Promise<DescribeInstanceStatusResponse> {
return this.request("DescribeInstanceStatus", req, cb)
}
/**
* 用于在个人版仓库中创建镜像仓库
*/
async CreateRepositoryPersonal(
req: CreateRepositoryPersonalRequest,
cb?: (error: string, rep: CreateRepositoryPersonalResponse) => void
): Promise<CreateRepositoryPersonalResponse> {
return this.request("CreateRepositoryPersonal", req, cb)
}
/**
* 删除指定镜像
*/
async DeleteImage(
req: DeleteImageRequest,
cb?: (error: string, rep: DeleteImageResponse) => void
): Promise<DeleteImageResponse> {
return this.request("DeleteImage", req, cb)
}
/**
* 查询个人版用户命名空间是否存在
*/
async ValidateNamespaceExistPersonal(
req: ValidateNamespaceExistPersonalRequest,
cb?: (error: string, rep: ValidateNamespaceExistPersonalResponse) => void
): Promise<ValidateNamespaceExistPersonalResponse> {
return this.request("ValidateNamespaceExistPersonal", req, cb)
}
/**
* 创建个人版镜像仓库命名空间,此命名空间全局唯一
*/
async CreateNamespacePersonal(
req: CreateNamespacePersonalRequest,
cb?: (error: string, rep: CreateNamespacePersonalResponse) => void
): Promise<CreateNamespacePersonalResponse> {
return this.request("CreateNamespacePersonal", req, cb)
}
/**
* 查询实例公网访问入口状态
*/
async DescribeExternalEndpointStatus(
req: DescribeExternalEndpointStatusRequest,
cb?: (error: string, rep: DescribeExternalEndpointStatusResponse) => void
): Promise<DescribeExternalEndpointStatusResponse> {
return this.request("DescribeExternalEndpointStatus", req, cb)
}
/**
* 管理实例内网访问VPC链接
*/
async ManageInternalEndpoint(
req: ManageInternalEndpointRequest,
cb?: (error: string, rep: ManageInternalEndpointResponse) => void
): Promise<ManageInternalEndpointResponse> {
return this.request("ManageInternalEndpoint", req, cb)
}
/**
* 批量查询vpc是否已经添加私有域名解析
*/
async DescribeInternalEndpointDnsStatus(
req: DescribeInternalEndpointDnsStatusRequest,
cb?: (error: string, rep: DescribeInternalEndpointDnsStatusResponse) => void
): Promise<DescribeInternalEndpointDnsStatusResponse> {
return this.request("DescribeInternalEndpointDnsStatus", req, cb)
}
/**
* 创建实例的临时或长期访问凭证
*/
async CreateInstanceToken(
req: CreateInstanceTokenRequest,
cb?: (error: string, rep: CreateInstanceTokenResponse) => void
): Promise<CreateInstanceTokenResponse> {
return this.request("CreateInstanceToken", req, cb)
}
} | the_stack |
import { Command } from "commander";
import { log } from "console";
import * as fs from "fs";
import { retry } from "../..";
import { EdgeAppInstanceModels, MindSphereSdk } from "../../api/sdk";
import { throwError } from "../../api/utils";
import {
adjustColor,
errorLog,
getColor,
getSdk,
homeDirLog,
printObjectInfo,
proxyLog,
serviceCredentialLog,
verboseLog,
} from "./command-utils";
import path = require("path");
let color = getColor("magenta");
export default (program: Command) => {
program
.command("oe-app-inst")
.alias("oeai")
.option(
"-m, --mode [list|create|config|delete|template|info]",
"list | create | config | delete | template | info",
"list"
)
.option("-i, --id <id>", "the app instance id")
.option("-d, --deviceid <id>", "the device id")
.option("-f, --file <file>", ".mdsp.json file with app inst data")
.option("-o, --overwrite", "overwrite template file if it already exists")
.option("-k, --passkey <passkey>", "passkey")
.option("-y, --retry <number>", "retry attempts before giving up", "3")
.option("-v, --verbose", "verbose output")
.description(color("list, create, configure or delete app instance (open edge) *"))
.action((options) => {
(async () => {
try {
checkRequiredParameters(options);
const sdk = getSdk(options);
color = adjustColor(color, options);
homeDirLog(options.verbose, color);
proxyLog(options.verbose, color);
switch (options.mode) {
case "list":
await listApps(sdk, options);
break;
case "template":
await createTemplateApp(options, sdk);
await createTemplateAppConfig(options, sdk);
console.log("Edit the file(s) before submitting it to MindSphere.");
break;
case "delete":
await deleteAppInst(options, sdk);
break;
case "create":
await createAppInstance(options, sdk);
break;
case "config":
await createAppInstanceConfiguration(options, sdk);
break;
case "info":
await appInstanceInfo(options, sdk);
break;
default:
throw Error(`no such option: ${options.mode}`);
}
} catch (err) {
errorLog(err, options.verbose);
}
})();
})
.on("--help", () => {
log("\n Examples:\n");
log(
` mc oe-app-inst --mode list --deviceid <deviceid> \tlist all app instances of device with deviceId.`
);
log(` mc oe-app-inst --mode template \t\t\tcreate a template file for new app instance data.`);
log(
` mc oe-app-inst --mode create --file edge.app.mdsp.json \n\tcreates a new app instance from template file.`
);
log(
` mc oe-app-inst --mode config --id <appinstid> --file edge.appconfig.mdsp.json \n\tconfigure an app instance from template file.`
);
log(` mc oe-app-inst --mode info --id <appinstid>\t\tget details of an app instance.`);
log(` mc oe-app-inst --mode delete --id <appinstid>\tdelete app instance configuration.`);
serviceCredentialLog();
});
};
async function createAppInstance(options: any, sdk: MindSphereSdk) {
const filePath = path.resolve(options.file);
const file = fs.readFileSync(filePath);
const data = JSON.parse(file.toString());
const name = data.deviceId ? data.deviceId : `${sdk.GetTenant()}.${data.appInstanceId}`;
await sdk.GetEdgeAppInstanceManagementClient().PostAppInstance(data);
console.log(`created new app instance for deviceid ${color(name)}`);
}
async function createAppInstanceConfiguration(options: any, sdk: MindSphereSdk) {
const filePath = path.resolve(options.file);
const file = fs.readFileSync(filePath);
const config = JSON.parse(file.toString());
const name = config.deviceId ? config.deviceId : `${sdk.GetTenant()}.${config.appInstanceId}`;
await sdk.GetEdgeAppInstanceManagementClient().PostAppInstanceConfigurations(config);
console.log(`created new configuration for deviceid ${color(name)}`);
}
async function createTemplateApp(options: any, sdk: MindSphereSdk) {
const tenant = sdk.GetTenant();
const template = {
name: `${tenant}.myAppName`,
appInstanceId: "718ca5ad0...",
deviceId: "718ca5ad0...",
releaseId: "718ca5ad0...",
applicationId: "718ca5ad0...",
};
verboseLog(template, options.verbose);
writeAppTemplateToFile(options, template);
}
async function createTemplateAppConfig(options: any, sdk: MindSphereSdk) {
const templateType = {
deviceId: "718ca5ad0...",
appId: "718ca5ad0...",
appReleaseId: "718ca5ad0...",
appInstanceId: "718ca5ad0...",
configuration: {
sampleKey1: "sampleValue1",
sampleKey2: "sampleValue2",
},
};
verboseLog(templateType, options.verbose);
writeAppInstConfigToFile(options, templateType);
}
function writeAppTemplateToFile(options: any, templateType: any) {
const fileName = options.file || `edge.app.mdsp.json`;
const filePath = path.resolve(fileName);
fs.existsSync(filePath) &&
!options.overwrite &&
throwError(`The ${filePath} already exists. (use --overwrite to overwrite) `);
fs.writeFileSync(filePath, JSON.stringify(templateType, null, 2));
console.log(
`The app data template was written into ${color(
filePath
)} run \n\n\tmc oe-app-inst --mode create --file ${fileName} \n\nto create a new app instance.\n`
);
}
function writeAppInstConfigToFile(options: any, templateType: any) {
const fileName = options.file || `edge.appconfig.mdsp.json`;
const filePath = path.resolve(fileName);
fs.existsSync(filePath) &&
!options.overwrite &&
throwError(`The ${filePath} already exists. (use --overwrite to overwrite) `);
fs.writeFileSync(filePath, JSON.stringify(templateType, null, 2));
console.log(
`The app config template was written into ${color(
filePath
)} run \n\n\tmc oe-app-inst --mode config --id <appinstid> --file ${fileName} \n\nto create a new app inst. configuration\n`
);
}
// // @Jupiter are these methods not ment to be used?
// async function configureAppInstance(options: any, sdk: MindSphereSdk) {
// const id = (options.id! as string) ? options.id : `${options.id}`;
// const filePath = path.resolve(options.file);
// const file = fs.readFileSync(filePath);
// const data = JSON.parse(file.toString());
// await sdk.GetEdgeAppInstanceManagementClient().PatchAppInstanceConfigurationData(id, data);
// console.log(`configured app instance with id ${color(id)}`);
// }
async function deleteAppInst(options: any, sdk: MindSphereSdk) {
const id = (options.id! as string) ? options.id : `${options.id}`;
await sdk.GetEdgeAppInstanceManagementClient().DeleteAppInstance(id);
console.log(`Application instance with id ${color(id)} deleted.`);
}
// // @Jupiter are these methods not ment to be used?
// async function deleteAppInstConfiguration(options: any, sdk: MindSphereSdk) {
// const id = (options.id! as string) ? options.id : `${options.id}`;
// await sdk.GetEdgeAppInstanceManagementClient().DeleteAppInstanceConfiguration(id);
// console.log(`Application instance configuration with id ${color(id)} deleted.`);
// }
async function listApps(sdk: MindSphereSdk, options: any) {
const edgeAppInstanceClient = sdk.GetEdgeAppInstanceManagementClient();
let page = 0;
console.log(`name \tStatus \tappInstanceId \tdeviceId \treleaseId \tapplicationId \tconfiguration`);
let appCount = 0;
let appPage;
do {
appPage = (await retry(options.retry, () =>
edgeAppInstanceClient.GetAppInstances(options.deviceid, 100, page)
)) as EdgeAppInstanceModels.PaginatedApplicationInstance;
appPage.content = appPage.content || [];
appPage.page = appPage.page || { totalPages: 0 };
for (const app of appPage.content || []) {
appCount++;
// read the configuration of these app
try {
const config = (await retry(options.retry, () =>
edgeAppInstanceClient.GetAppInstanceConfiguration(app.appInstanceId)
)) as EdgeAppInstanceModels.InstanceConfigurationResource;
const status = (await retry(options.retry, () =>
edgeAppInstanceClient.GetAppInstanceLifecycle(app.appInstanceId)
)) as EdgeAppInstanceModels.ApplicationInstanceLifeCycleResource;
console.log(
`${color(app.name)} \t${color(status.status)} \t${app.appInstanceId} \t${app.deviceId} \t${
app.applicationId
} \t${app.releaseId} \t${JSON.stringify(config)}`
);
verboseLog(JSON.stringify(app, null, 2), options.verbose);
} catch (e) {}
}
} while (page++ < (appPage.page.totalPages || 0));
console.log(`${color(appCount)} app instance(s) listed.\n`);
}
async function appInstanceInfo(options: any, sdk: MindSphereSdk) {
const id = (options.id! as string) ? options.id : `${options.id}`;
const appInstConfig = (await retry(options.retry, () =>
sdk.GetEdgeAppInstanceManagementClient().GetAppInstanceConfiguration(id)
)) as EdgeAppInstanceModels.InstanceConfigurationResource;
printObjectInfo(
"App Instance Configuration",
appInstConfig,
options,
["deviceId", "appId", "appReleaseId", "appInstanceId", "configuration"],
color
);
}
// async function appInstanceConfigInfo(options: any, sdk: MindSphereSdk) {
// const id = (options.id! as string) ? options.id : `${options.id}`;
// const appInstConfig = await sdk.GetEdgeAppInstanceManagementClient().GetAppInstanceConfiguration(id);
// printObjectInfo(
// "App Instance Configuration",
// appInstConfig,
// options,
// ["deviceId", "appId", "appReleaseId", "appInstanceId", "configuration"],
// color
// );
// }
function checkRequiredParameters(options: any) {
options.mode === "create" &&
!options.file &&
errorLog(
"you have to provide a file with the app data to create a new application instance (see mc oe-app-inst --help for more details)",
true
);
options.mode === "list" &&
!options.deviceid &&
errorLog(
"you have to provide the deviceid of the target device (see mc oe-app-inst --help for more details)",
true
);
options.mode === "info" &&
!options.id &&
errorLog("you have to provide the id app instance (see mc oe-app-inst --help for more details)", true);
options.mode === "delete" &&
!options.id &&
errorLog(
"you have to provide the id of the app instance to delete it (see mc oe-app-inst --help for more details)",
true
);
options.mode === "config" &&
!options.file &&
errorLog(
"you have to provide a file with the config data to configure the application instance (see mc oe-app-inst --help for more details)",
true
);
options.mode === "config" &&
!options.id &&
errorLog(
"you have to provide the id of the app instance to configure (see mc oe-app-inst --help for more details)",
true
);
} | the_stack |
import { OnDestroy, Directive, Component } from '@angular/core';
import {
AbstractControl,
AbstractControlOptions,
ControlValueAccessor,
FormGroup,
ValidationErrors,
Validator,
FormArray,
FormControl,
} from '@angular/forms';
import { merge, Observable, Subscription } from 'rxjs';
import { delay, filter, map, startWith, withLatestFrom } from 'rxjs/operators';
import {
ControlMap,
Controls,
ControlsNames,
FormUpdate,
MissingFormControlsError,
FormErrors,
isNullOrUndefined,
ControlsType,
ArrayPropertyKey,
TypedAbstractControl,
TypedFormGroup,
} from './ngx-sub-form-utils';
import { FormGroupOptions, NgxFormWithArrayControls, OnFormUpdate } from './ngx-sub-form.types';
type MapControlFunction<FormInterface, MapValue> = (
ctrl: TypedAbstractControl<any>,
key: keyof FormInterface,
) => MapValue;
type FilterControlFunction<FormInterface> = (
ctrl: TypedAbstractControl<any>,
key: keyof FormInterface,
isCtrlWithinFormArray: boolean,
) => boolean;
@Directive()
// tslint:disable-next-line: directive-class-suffix
export abstract class NgxSubFormComponent<ControlInterface, FormInterface = ControlInterface>
implements ControlValueAccessor, Validator, OnDestroy, OnFormUpdate<FormInterface> {
public get formGroupControls(): ControlsType<FormInterface> {
// @note form-group-undefined we need the return null here because we do not want to expose the fact that
// the form can be undefined, it's handled internally to contain an Angular bug
if (!this.formGroup) {
return null as any;
}
return (this.formGroup.controls as unknown) as ControlsType<FormInterface>;
}
public get formGroupValues(): Required<FormInterface> {
// see @note form-group-undefined for non-null assertion reason
// tslint:disable-next-line:no-non-null-assertion
return this.mapControls(ctrl => ctrl.value)!;
}
public get formGroupErrors(): FormErrors<FormInterface> {
const errors: FormErrors<FormInterface> = this.mapControls<ValidationErrors | ValidationErrors[] | null>(
ctrl => ctrl.errors,
(ctrl, _, isCtrlWithinFormArray) => (isCtrlWithinFormArray ? true : ctrl.invalid),
true,
) as FormErrors<FormInterface>;
if (!this.formGroup.errors && (!errors || !Object.keys(errors).length)) {
return null;
}
return Object.assign({}, this.formGroup.errors ? { formGroup: this.formGroup.errors } : {}, errors);
}
public get formControlNames(): ControlsNames<FormInterface> {
// see @note form-group-undefined for as syntax
return this.mapControls(
(_, key) => key,
() => true,
false,
) as ControlsNames<FormInterface>;
}
private controlKeys: (keyof FormInterface)[] = [];
// when developing the lib it's a good idea to set the formGroup type
// to current + `| undefined` to catch a bunch of possible issues
// see @note form-group-undefined
public formGroup: TypedFormGroup<FormInterface> = (new FormGroup(
this._getFormControls(),
this.getFormGroupControlOptions() as AbstractControlOptions,
) as unknown) as TypedFormGroup<FormInterface>;
protected onChange: Function | undefined = undefined;
protected onTouched: Function | undefined = undefined;
protected emitNullOnDestroy = true;
protected emitInitialValueOnInit = true;
private subscription: Subscription | undefined = undefined;
// a RootFormComponent with the disabled property set initially to `false`
// will call `setDisabledState` *before* the form is actually available
// and it wouldn't be disabled once available, therefore we use this flag
// to check when the FormGroup is created if we should disable it
private controlDisabled = false;
constructor() {
// if the form has default values, they should be applied straight away
const defaultValues: Partial<FormInterface> | null = this.getDefaultValues();
if (!!defaultValues) {
this.formGroup.reset(defaultValues, { emitEvent: false });
}
// `setTimeout` and `updateValueAndValidity` are both required here
// indeed, if you check the demo you'll notice that without it, if
// you select `Droid` and `Assassin` for example the displayed errors
// are not yet defined for the field `assassinDroid`
// (until you change one of the value in that form)
setTimeout(() => {
if (this.formGroup) {
this.formGroup.updateValueAndValidity({ emitEvent: false });
if (this.controlDisabled) {
this.formGroup.disable();
}
}
}, 0);
}
// can't define them directly
protected abstract getFormControls(): Controls<FormInterface>;
private _getFormControls(): Controls<FormInterface> {
const controls: Controls<FormInterface> = this.getFormControls();
this.controlKeys = (Object.keys(controls) as unknown) as (keyof FormInterface)[];
return controls;
}
private mapControls<MapValue>(
mapControl: MapControlFunction<FormInterface, MapValue>,
filterControl: FilterControlFunction<FormInterface>,
recursiveIfArray: boolean,
): Partial<ControlMap<FormInterface, MapValue | MapValue[]>> | null;
private mapControls<MapValue>(
mapControl: MapControlFunction<FormInterface, MapValue>,
): ControlMap<FormInterface, MapValue | MapValue[]> | null;
private mapControls<MapValue>(
mapControl: MapControlFunction<FormInterface, MapValue>,
filterControl: FilterControlFunction<FormInterface> = () => true,
recursiveIfArray: boolean = true,
): Partial<ControlMap<FormInterface, MapValue | MapValue[]>> | null {
if (!this.formGroup) {
return null;
}
const formControls: ControlsType<FormInterface> = this.formGroup.controls;
const controls: Partial<ControlMap<FormInterface, MapValue | MapValue[]>> = {};
for (const key in formControls) {
if (this.formGroup.controls.hasOwnProperty(key)) {
const control = formControls[key];
if (recursiveIfArray && control instanceof FormArray) {
const values: MapValue[] = [];
for (let i = 0; i < control.length; i++) {
if (filterControl(control.at(i), key, true)) {
values.push(mapControl(control.at(i), key));
}
}
if (values.length > 0 && values.some(x => !isNullOrUndefined(x))) {
controls[key] = values;
}
} else if (control && filterControl(control, key, false)) {
controls[key] = mapControl(control, key);
}
}
}
return controls;
}
public onFormUpdate(formUpdate: FormUpdate<FormInterface>): void {}
/**
* Extend this method to provide custom local FormGroup level validation
*/
protected getFormGroupControlOptions(): FormGroupOptions<FormInterface> {
return {};
}
public validate(): ValidationErrors | null {
if (
// @hack see where defining this.formGroup to undefined
!this.formGroup ||
this.formGroup.valid
) {
return null;
}
return this.formGroupErrors;
}
// @todo could this be removed to avoid an override and just use `takeUntilDestroyed`?
public ngOnDestroy(): void {
// @hack there's a memory leak within Angular and those components
// are not correctly cleaned up which leads to error if a form is defined
// with validators and then it's been removed, the validator would still fail
// `as any` if because we do not want to define the formGroup as FormGroup | undefined
// everything related to undefined is handled internally and shouldn't be exposed to end user
(this.formGroup as any) = undefined;
if (this.subscription) {
this.subscription.unsubscribe();
}
if (this.emitNullOnDestroy && this.onChange) {
this.onChange(null);
}
this.onChange = undefined;
}
// when getDefaultValues is defined, you do not need to specify the default values
// in your form (the ones defined within the `getFormControls` method)
protected getDefaultValues(): Partial<FormInterface> | null {
return null;
}
public writeValue(obj: Required<ControlInterface> | null): void {
// @hack see where defining this.formGroup to undefined
if (!this.formGroup) {
return;
}
const defaultValues: Partial<FormInterface> | null = this.getDefaultValues();
const transformedValue: FormInterface | null = this.transformToFormGroup(
obj === undefined ? null : obj,
defaultValues,
);
if (isNullOrUndefined(transformedValue)) {
this.formGroup.reset(
// calling `reset` on a form with `null` throws an error but if nothing is passed
// (undefined) it will reset all the form values to null (as expected)
defaultValues === null ? undefined : defaultValues,
{ emitEvent: false },
);
} else {
const missingKeys: (keyof FormInterface)[] = this.getMissingKeys(transformedValue);
if (missingKeys.length > 0) {
throw new MissingFormControlsError(missingKeys as string[]);
}
this.handleFormArrayControls(transformedValue);
// The next few lines are weird but it's as workaround.
// There are some shady behavior with the disabled state
// of a form. Apparently, using `setValue` on a disabled
// form does re-enable it *sometimes*, not always.
// related issues:
// https://github.com/angular/angular/issues/31506
// https://github.com/angular/angular/issues/22556
// but if you display `this.formGroup.disabled`
// before and after the `setValue` is called, it's the same
// result which is even weirder
const fgDisabled: boolean = this.formGroup.disabled;
this.formGroup.setValue(transformedValue, {
emitEvent: false,
});
if (fgDisabled) {
this.formGroup.disable();
}
}
this.formGroup.markAsPristine();
this.formGroup.markAsUntouched();
}
private handleFormArrayControls(obj: any) {
Object.entries(obj).forEach(([key, value]) => {
if (this.formGroup.get(key) instanceof FormArray && Array.isArray(value)) {
const formArray: FormArray = this.formGroup.get(key) as FormArray;
// instead of creating a new array every time and push a new FormControl
// we just remove or add what is necessary so that:
// - it is as efficient as possible and do not create unnecessary FormControl every time
// - validators are not destroyed/created again and eventually fire again for no reason
while (formArray.length > value.length) {
formArray.removeAt(formArray.length - 1);
}
for (let i = formArray.length; i < value.length; i++) {
if (this.formIsFormWithArrayControls()) {
formArray.insert(i, this.createFormArrayControl(key as ArrayPropertyKey<FormInterface>, value[i]));
} else {
formArray.insert(i, new FormControl(value[i]));
}
}
}
});
}
private formIsFormWithArrayControls(): this is NgxFormWithArrayControls<FormInterface> {
return typeof ((this as unknown) as NgxFormWithArrayControls<FormInterface>).createFormArrayControl === 'function';
}
private getMissingKeys(transformedValue: FormInterface | null) {
// `controlKeys` can be an empty array, empty forms are allowed
const missingKeys: (keyof FormInterface)[] = this.controlKeys.reduce((keys, key) => {
if (isNullOrUndefined(transformedValue) || transformedValue[key] === undefined) {
keys.push(key);
}
return keys;
}, [] as (keyof FormInterface)[]);
return missingKeys;
}
// when customizing the emission rate of your sub form component, remember not to **mutate** the stream
// it is safe to throttle, debounce, delay, etc but using skip, first, last or mutating data inside
// the stream will cause issues!
protected handleEmissionRate(): (obs$: Observable<FormInterface>) => Observable<FormInterface> {
return obs$ => obs$;
}
// that method can be overridden if the
// shape of the form needs to be modified
protected transformToFormGroup(
obj: ControlInterface | null,
defaultValues: Partial<FormInterface> | null,
): FormInterface | null {
return (obj as any) as FormInterface;
}
// that method can be overridden if the
// shape of the form needs to be modified
protected transformFromFormGroup(formValue: FormInterface): ControlInterface | null {
return (formValue as any) as ControlInterface;
}
public registerOnChange(fn: (_: any) => void): void {
if (!this.formGroup) {
return;
}
this.onChange = fn;
interface KeyValueForm {
key: keyof FormInterface;
value: unknown;
}
const formControlNames: (keyof FormInterface)[] = Object.keys(this.formControlNames) as (keyof FormInterface)[];
const formValues: Observable<KeyValueForm>[] = formControlNames.map(key =>
((this.formGroup.controls[key] as unknown) as AbstractControl).valueChanges.pipe(
startWith(this.formGroup.controls[key].value),
map(value => ({ key, value })),
),
);
const lastKeyEmitted$: Observable<keyof FormInterface> = merge(...formValues.map(obs => obs.pipe(map(x => x.key))));
this.subscription = this.formGroup.valueChanges
.pipe(
// hook to give access to the observable for sub-classes
// this allow sub-classes (for example) to debounce, throttle, etc
this.handleEmissionRate(),
startWith(this.formGroup.value),
// this is required otherwise an `ExpressionChangedAfterItHasBeenCheckedError` will happen
// this is due to the fact that parent component will define a given state for the form that might
// be changed once the children are being initialized
delay(0),
filter(() => !!this.formGroup),
// detect which stream emitted last
withLatestFrom(lastKeyEmitted$),
map(([_, keyLastEmit], index) => {
if (index > 0 && this.onTouched) {
this.onTouched();
}
if (index > 0 || (index === 0 && this.emitInitialValueOnInit)) {
if (this.onChange) {
this.onChange(
this.transformFromFormGroup(
// do not use the changes passed by `this.formGroup.valueChanges` here
// as we've got a delay(0) above, on the next tick the form data might
// be outdated and might result into an inconsistent state where a form
// state is valid (base on latest value) but the previous value
// (the one passed by `this.formGroup.valueChanges` would be the previous one)
this.formGroup.value,
),
);
}
const formUpdate: FormUpdate<FormInterface> = {};
formUpdate[keyLastEmit] = true;
this.onFormUpdate(formUpdate);
}
}),
)
.subscribe();
}
public registerOnTouched(fn: any): void {
this.onTouched = fn;
}
public setDisabledState(shouldDisable: boolean | undefined): void {
this.controlDisabled = !!shouldDisable;
if (!this.formGroup) {
return;
}
if (shouldDisable) {
this.formGroup.disable({ emitEvent: false });
} else {
this.formGroup.enable({ emitEvent: false });
}
}
}
@Directive()
// tslint:disable-next-line: directive-class-suffix
export abstract class NgxSubFormRemapComponent<ControlInterface, FormInterface> extends NgxSubFormComponent<
ControlInterface,
FormInterface
> {
protected abstract transformToFormGroup(
obj: ControlInterface | null,
defaultValues: Partial<FormInterface> | null,
): FormInterface | null;
protected abstract transformFromFormGroup(formValue: FormInterface): ControlInterface | null;
} | the_stack |
interface BoundingBox {
top: number
left: number
width: number
height: number
}
function expectBbox(element: HTMLElement, expectedBbox: Partial<BoundingBox>) {
const bbox = element.getBoundingClientRect()
expect(bbox.left).to.equal(expectedBbox.left)
expect(bbox.top).to.equal(expectedBbox.top)
expectedBbox.width && expect(bbox.width).to.equal(expectedBbox.width)
expectedBbox.height && expect(bbox.height).to.equal(expectedBbox.height)
}
function testNestedDrag(parentLayout: boolean, childLayout: boolean) {
let url = `?test=drag-layout-nested`
if (parentLayout) url += `&parentLayout=true`
if (childLayout) url += `&childLayout=true`
cy.visit(url)
.wait(50)
.get("#parent")
.should(([$parent]: any) => {
expectBbox($parent, {
top: 100,
left: 100,
width: 300,
height: 300,
})
})
.get("#child")
.should(([$child]: any) => {
expectBbox($child, {
top: 150,
left: 150,
width: 600,
height: 200,
})
})
.get("#control")
.should(([$child]: any) => {
expectBbox($child, {
top: 200,
left: 200,
})
})
.get("#parent")
.trigger("pointerdown", 5, 5)
.wait(50)
.trigger("pointermove", 10, 10) // Gesture will start from first move past threshold
.wait(50)
.trigger("pointermove", 50, 50)
.wait(50)
.trigger("pointerup")
.should(([$parent]: any) => {
expectBbox($parent, {
top: 150,
left: 150,
width: 300,
height: 300,
})
})
.get("#control")
.should(([$child]: any) => {
expectBbox($child, { top: 250, left: 250 })
})
.get("#child")
.should(([$child]: any) => {
expectBbox($child, {
top: 200,
left: 200,
width: 600,
height: 200,
})
})
.trigger("pointerdown", 5, 5)
.wait(50)
.trigger("pointermove", 10, 10) // Gesture will start from first move past threshold
.wait(50)
.trigger("pointermove", 50, 50)
.wait(50)
.get("#parent")
.should(([$parent]: any) => {
expectBbox($parent, {
top: 150,
left: 150,
width: 300,
height: 300,
})
})
.get("#child")
.should(([$child]: any) => {
expectBbox($child, {
top: 250,
left: 250,
width: 600,
height: 200,
})
})
.get("#control")
.should(([$child]: any) => {
expectBbox($child, { top: 300, left: 300 })
})
.trigger("pointerup")
.wait(50)
.get("#parent")
.should(([$parent]: any) => {
expectBbox($parent, {
top: 150,
left: 150,
width: 300,
height: 300,
})
})
.get("#child")
.should(([$child]: any) => {
expectBbox($child, {
top: 250,
left: 250,
width: 600,
height: 200,
})
})
.get("#control")
.should(([$child]: any) => {
expectBbox($child, { top: 300, left: 300 })
})
.get("#parent")
.trigger("pointerdown", 5, 5)
.wait(20)
.trigger("pointermove", 10, 10) // Gesture will start from first move past threshold
.wait(50)
.trigger("pointermove", 50, 50)
.wait(50)
.trigger("pointerup")
.get("#parent")
.should(([$parent]: any) => {
expectBbox($parent, {
top: 200,
left: 200,
width: 300,
height: 300,
})
})
.get("#child")
.should(([$child]: any) => {
expectBbox($child, {
top: 300,
left: 300,
width: 600,
height: 200,
})
})
.get("#control")
.should(([$child]: any) => {
expectBbox($child, { top: 350, left: 350 })
})
}
describe("Nested drag", () => {
it("Parent: layout, Child: layout", () => testNestedDrag(true, true))
it("Parent: layout", () => testNestedDrag(true, false))
it("Child: layout", () => testNestedDrag(false, true))
it("Neither", () => testNestedDrag(false, false))
})
function testNestedDragConstraints(
parentLayout: boolean,
childLayout: boolean
) {
let url = `?test=drag-layout-nested&constraints=true`
if (parentLayout) url += `&parentLayout=true`
if (childLayout) url += `&childLayout=true`
cy.visit(url)
.get("#parent")
.trigger("pointerdown", 40, 40)
.wait(50)
.trigger("pointermove", 35, 35) // Gesture will start from first move past threshold
.wait(50)
.trigger("pointermove", 20, 20)
.wait(50)
.trigger("pointerup")
.should(([$parent]: any) => {
// Should have only moved 10 px to the top
expectBbox($parent, {
top: 90,
left: 75,
width: 300,
height: 300,
})
})
.get("#child")
.should(([$child]: any) => {
expectBbox($child, {
top: 140,
left: 125,
width: 600,
height: 200,
})
})
.get("#control")
.should(([$child]: any) => {
expectBbox($child, { top: 190, left: 175 })
})
.get("#parent")
.trigger("pointerdown", 5, 5)
.wait(50)
.trigger("pointermove", 10, 10) // Gesture will start from first move past threshold
.wait(50)
.trigger("pointermove", 200, 100)
.wait(50)
.trigger("pointerup")
.should(([$parent]: any) => {
expectBbox($parent, {
top: 190,
left: 200,
width: 300,
height: 300,
})
})
.get("#control")
.should(([$child]: any) => {
expectBbox($child, { top: 290, left: 300 })
})
.get("#child")
.should(([$child]: any) => {
expectBbox($child, {
top: 240,
left: 250,
width: 600,
height: 200,
})
})
.trigger("pointerdown", 5, 5, { force: true })
.wait(50)
.trigger("pointermove", 10, 10, { force: true }) // Gesture will start from first move past threshold
.wait(50)
.trigger("pointermove", 300, 100, { force: true })
.wait(50)
.trigger("pointerup")
.get("#parent")
.should(([$parent]: any) => {
expectBbox($parent, {
top: 190,
left: 200,
width: 300,
height: 300,
})
})
.get("#child")
.should(([$child]: any) => {
expectBbox($child, {
top: 340,
left: 350,
width: 600,
height: 200,
})
})
.get("#control")
.should(([$child]: any) => {
expectBbox($child, { top: 390, left: 400 })
})
}
describe("Nested drag with constraints", () => {
it("Parent: layout, Child: layout", () =>
testNestedDragConstraints(true, true))
it("Parent: layout", () => testNestedDragConstraints(true, false))
it("Child: layout", () => testNestedDragConstraints(false, true))
it("Neither", () => testNestedDragConstraints(false, false))
})
function testNestedDragConstraintsAndAnimation(
parentLayout: boolean,
childLayout: boolean
) {
let url = `?test=drag-layout-nested&constraints=true&animation=true`
if (parentLayout) url += `&parentLayout=true`
if (childLayout) url += `&childLayout=true`
cy.visit(url)
.get("#parent")
.trigger("pointerdown", 5, 10)
.wait(50)
.trigger("pointermove", 10, 10) // Gesture will start from first move past threshold
.wait(50)
.trigger("pointermove", 200, 10, { force: true })
.wait(50)
.should(([$parent]: any) => {
// Should have only moved 10 px to the top
expectBbox($parent, {
top: 100,
left: 250,
width: 300,
height: 300,
})
})
.get("#child")
.should(([$child]: any) => {
expectBbox($child, {
top: 150,
left: 300,
width: 600,
height: 200,
})
})
.get("#control")
.should(([$child]: any) => {
expectBbox($child, { top: 200, left: 350 })
})
.get("#parent")
.trigger("pointerup")
.wait(2000)
.should(([$parent]: any) => {
// Should have only moved 10 px to the top
expectBbox($parent, {
top: 100,
left: 200,
width: 300,
height: 300,
})
})
.get("#child")
.should(([$child]: any) => {
expectBbox($child, {
top: 150,
left: 250,
width: 600,
height: 200,
})
})
.get("#control")
.should(([$child]: any) => {
expectBbox($child, { top: 200, left: 300 })
})
.get("#child")
.trigger("pointerdown", 5, 10)
.wait(50)
.trigger("pointermove", 10, 10) // Gesture will start from first move past threshold
.wait(50)
.trigger("pointermove", 200, 10, { force: true })
.wait(70)
.should(([$child]: any) => {
expectBbox($child, {
top: 150,
left: 400,
width: 600,
height: 200,
})
})
.trigger("pointerup")
.wait(2000)
.should(([$child]: any) => {
expectBbox($child, {
top: 150,
left: 350,
width: 600,
height: 200,
})
})
}
function testAlternateAxes(parentLayout: boolean, childLayout: boolean) {
let url = `?test=drag-layout-nested&bothAxes=true`
if (parentLayout) url += `&parentLayout=true`
if (childLayout) url += `&childLayout=true`
return cy
.visit(url)
.wait(50)
.get("#child")
.trigger("pointerdown", 5, 5, { force: true })
.wait(50)
.trigger("pointermove", 10, 10, { force: true })
.wait(50)
.trigger("pointermove", 100, 100, { force: true })
.wait(80)
.should(([$child]: any) => {
expectBbox($child, {
top: 245,
left: 250,
width: 600,
height: 200,
})
})
.get("#control")
.should(([$child]: any) => {
expectBbox($child, { top: 295, left: 300 })
})
.get("#parent")
.should(([$parent]: any) => {
expectBbox($parent, {
top: 195,
left: 100,
width: 300,
height: 300,
})
})
.wait(30)
.get("#child")
.trigger("pointerup", { force: true })
.wait(80)
.should(([$child]: any) => {
expectBbox($child, {
top: 245,
left: 250,
width: 600,
height: 200,
})
})
.get("#control")
.should(([$child]: any) => {
expectBbox($child, { top: 295, left: 300 })
})
.get("#parent")
.should(([$parent]: any) => {
expectBbox($parent, {
top: 195,
left: 100,
width: 300,
height: 300,
})
})
}
describe("Nested drag with alternate draggable axes", () => {
/**
* Skipping for now as there are still issues when either draggable
* component is also involved in layout animation
*/
it.skip("Parent: layout, Child: layout", () =>
testAlternateAxes(true, true))
it("Parent: layout", () => testAlternateAxes(true, false))
it.skip("Child: layout", () => testAlternateAxes(false, true))
it("Neither", () => testAlternateAxes(false, false))
})
describe("Nested drag with constraints and animation", () => {
it("Parent: layout, Child: layout", () =>
testNestedDragConstraintsAndAnimation(true, true))
it("Parent: layout", () =>
testNestedDragConstraintsAndAnimation(true, false))
it("Child: layout", () =>
testNestedDragConstraintsAndAnimation(false, true))
it("Neither", () => testNestedDragConstraintsAndAnimation(false, false))
}) | the_stack |
import { Component, OnInit, OnDestroy } from '@angular/core';
import { AssetGroupObservableService } from '../../../../core/services/asset-group-observable.service';
import { CommonResponseService } from '../../../../shared/services/common-response.service';
import { Subscription } from 'rxjs/Subscription';
import { environment } from './../../../../../environments/environment';
import { Router} from '@angular/router';
import { LoggerService } from '../../../../shared/services/logger.service';
import { WorkflowService } from '../../../../core/services/workflow.service';
import { UtilsService } from '../../../../shared/services/utils.service';
import * as _ from 'lodash';
const date = new Date();
@Component({
selector: 'app-patching-projections',
templateUrl: './patching-projections.component.html',
styleUrls: ['./patching-projections.component.css'],
providers: [CommonResponseService, LoggerService, UtilsService]
})
export class PatchingProjectionsComponent implements OnInit, OnDestroy {
pageTitle = 'Patching Projections';
breadcrumbArray: any= ['Compliance'];
breadcrumbLinks: any= ['compliance-dashboard'];
breadcrumbPresent: any;
selectedAssetGroup: string;
subscriptionToAssetGroup: Subscription;
targetSubscription: Subscription;
errorMessage: any;
errorValue = 0;
targetTiles: any = [];
tiles: any = [];
targetDropdown: any = [];
targetTypeSelected: string;
dropdownDisable = true;
urlToRedirect: any = '';
years: any= ['2019', '2018', '2017'];
quarter: any= ['1', '2', '3', '4'];
yearSelected = '2018';
quarterSelected = '1';
weekProjections: any = [];
totalAseets = 0;
index = 0;
totalweeksProjection = 0;
dropdownValue: any;
private pageLevel = 0;
updateState = 0;
startUpdate= false;
enableSaveButton= false;
public backButtonRequired;
numberOfWeeks: number;
weeksArray: any= [];
yearsArray: any= [];
yearsDropdown: any = [];
quarterArray: any= [];
quarterDropdown: any= [];
storeProjectionData: any = [];
constructor(private assetGroupObservableService: AssetGroupObservableService,
private router: Router,
private commonResponseService: CommonResponseService,
private logger: LoggerService,
private workflowService: WorkflowService,
private utilsService: UtilsService) {
this.subscriptionToAssetGroup = this.assetGroupObservableService.getAssetGroup().subscribe(
assetGroupName => {
this.backButtonRequired = this.workflowService.checkIfFlowExistsCurrently(this.pageLevel);
this.selectedAssetGroup = assetGroupName;
this.clickClearDropdown();
this.resetPage();
this.selectYear(this.years);
this.selectQuarter(this.quarter);
this.numberOfWeeks = utilsService.getNumberOfWeeks(this.yearSelected, this.quarterSelected);
this.weekProjections = this.createObjectToIterateUpon(this.numberOfWeeks);
this.storeProjectionData = JSON.parse(JSON.stringify(this.createObjectToIterateUpon(this.numberOfWeeks)));
this.getTargetTypes();
});
}
ngOnInit() {
this.breadcrumbPresent = 'Patching Projections';
}
createObjectToIterateUpon(numberOfWeeks) {
this.weeksArray = [];
for (let i = 1; i <= numberOfWeeks; i++) {
this.weeksArray.push({
'week': i,
'projection': 0
});
}
return this.weeksArray;
}
selectYear(years) {
this.yearsArray = [];
this.index = 0;
this.years.forEach(element => {
this.dropdownValue = {
id: this.index++,
text: element
};
this.yearsArray.push(this.dropdownValue);
});
this.yearsDropdown = _.map(this.yearsArray, 'text');
this.yearSelected = date.getFullYear().toString();
}
selectQuarter(quarter) {
this.quarterArray = [];
this.index = 0;
this.quarter.forEach(element => {
this.dropdownValue = {
id: this.index++,
text: element
};
this.quarterArray.push(this.dropdownValue);
});
this.quarterDropdown = _.map(this.quarterArray, 'text');
this.quarterSelected = Math.ceil((date.getMonth() + 1) / 3).toString();
}
changeTargetFilterTags(val) {
if (this.targetTypeSelected !== val.text) {
this.targetTypeSelected = val.text;
this.getProjections();
}
}
changeYearFilterTags(val) {
if (this.yearSelected !== val.text) {
this.yearSelected = val.text;
this.getProjections();
}
}
changeQuarterFilterTags(val) {
if (this.quarterSelected !== val.text) {
this.quarterSelected = val.text;
this.getProjections();
}
}
getProjections() {
if (this.targetSubscription) {
this.targetSubscription.unsubscribe();
}
this.enableSaveButton = false;
this.dropdownDisable = false;
this.totalAseets = 0;
this.totalweeksProjection = 0;
this.numberOfWeeks = this.utilsService.getNumberOfWeeks(this.yearSelected, this.quarterSelected);
this.weekProjections = this.createObjectToIterateUpon(this.numberOfWeeks);
this.storeProjectionData = JSON.parse(JSON.stringify(this.createObjectToIterateUpon(this.numberOfWeeks)));
const payload = {};
const queryParam = {
'targettype': this.targetTypeSelected,
'year': this.yearSelected,
'quarter': this.quarterSelected
};
this.errorValue = 0;
const url = environment.patchingProjections.url;
const method = environment.patchingProjections.method;
this.targetSubscription = this.commonResponseService.getData( url, method, payload, queryParam).subscribe(
response => {
try {
this.errorValue = 1;
if (response.length === 0 ) {
this.errorValue = -2;
}
this.totalAseets = response.totalAssets;
if (response.projectionByWeek.length === 0) {
this.errorValue = -3;
} else {
this.weekProjections = response.projectionByWeek;
this.weekProjections = this.checkifProjectionEqualsWeeks(this.weekProjections);
this.totalweeksProjection = 0;
this.weekProjections.forEach(element => {
this.totalweeksProjection = this.totalweeksProjection + element.projection;
});
this.storeProjectionData = JSON.parse(JSON.stringify(response.projectionByWeek));
}
} catch (e) {
this.errorValue = -1;
this.logger.log('error', e);
}
},
error => {
this.errorValue = -1;
});
}
getTargetTypes() {
if (this.targetSubscription) {
this.targetSubscription.unsubscribe();
}
const payload = {};
const queryParam = {
'ag': this.selectedAssetGroup
};
this.errorValue = 0;
this.targetTiles = [];
this.tiles = [];
const url = environment.complianceTargetType.url;
const method = environment.complianceTargetType.method;
this.targetSubscription = this.commonResponseService.getData(url, method, payload, queryParam).subscribe(
response => {
try {
this.errorValue = 1;
if (response.resourceType.length === 0) {
this.errorValue = -2;
}
this.index = 0;
this.targetTiles = response.resourceType;
this.targetTiles.forEach(element => {
this.dropdownValue = {
id: this.index++,
text: element
};
this.tiles.push(this.dropdownValue);
});
this.targetDropdown = _.map(this.tiles, 'text');
} catch (e) {
this.errorValue = -4;
this.logger.log('error', e);
}
},
error => {
this.errorValue = -4;
});
}
navigateBack() {
try {
this.workflowService.goBackToLastOpenedPageAndUpdateLevel(this.router.routerState.snapshot.root);
} catch (error) {
this.logger.log('error', error);
}
}
resetToFetchData() {
this.weekProjections = JSON.parse(JSON.stringify(this.storeProjectionData));
}
saveData() {
this.storeProjectionData = JSON.parse(JSON.stringify(this.weekProjections));
this.startUpdate = true;
this.updateState = 0;
const queryParam = {};
const payload = {
'projectionByWeek': this.weekProjections,
'quarter': this.quarterSelected,
'resourceType': this.targetTypeSelected,
'year': this.yearSelected
};
const url = environment.updateProjections.url;
const method = environment.updateProjections.method;
this.targetSubscription = this.commonResponseService.getData( url, method, payload, queryParam).subscribe(
response => {
try {
this.updateState = 1;
} catch (e) {
this.updateState = -1;
this.logger.log('error', e);
}
},
error => {
this.updateState = -1;
});
}
closeUpdateloader() {
this.startUpdate = false;
if (this.updateState === 1 ) {
this.enableSaveButton = false;
}
}
updateTotalAssets(val, index) {
this.enableSaveButton = true;
this.totalweeksProjection = 0;
if (this.weekProjections.length > 0) {
this.weekProjections.forEach(element => {
this.totalweeksProjection = this.totalweeksProjection + element.projection;
});
}
}
resetPage() {
this.enableSaveButton = false;
this.startUpdate = false;
this.errorValue = 0;
this.targetTiles = [];
this.tiles = [];
this.targetTypeSelected = '';
this.dropdownDisable = true;
this.yearSelected = '2018';
this.quarterSelected = '1';
this.weekProjections = [];
this.storeProjectionData = [];
this.totalAseets = 0;
this.totalweeksProjection = 0;
this.getTargetTypes();
}
clearPageLevel() {
this.workflowService.clearAllLevels();
}
// clears target type dropdown
clickClearDropdown() {
setTimeout(function() {
const element = document.getElementById('clear-value');
const clear = element.getElementsByClassName(
'btn btn-xs btn-link pull-right'
);
for (let len = 0; len < clear.length; len++) {
const htmlElement: HTMLElement = clear[len] as HTMLElement;
htmlElement.click();
}
}, 10);
}
checkifProjectionEqualsWeeks(receivedWeekProjections) {
const numOfreceivedProjection = receivedWeekProjections.length;
if ((this.numberOfWeeks - numOfreceivedProjection) > 0 ) {
for (let i = numOfreceivedProjection; i < this.numberOfWeeks; i++) {
receivedWeekProjections.push({
'week': i + 1,
'projection': 0
});
}
}
return receivedWeekProjections;
}
ngOnDestroy() {
try {
if (this.subscriptionToAssetGroup) {
this.subscriptionToAssetGroup.unsubscribe();
}
if (this.targetSubscription) {
this.targetSubscription.unsubscribe();
}
} catch (error) {
this.logger.log('error', '--- Error while unsubscribing ---');
}
}
} | the_stack |
import { defineMessages } from 'react-intl'
export const m = defineMessages({
// navigation
rootName: {
id: 'sp.document-provider:title',
defaultMessage: 'Skjalaveita',
},
documentProviders: {
id: 'sp.document-provider:document-providers',
defaultMessage: 'Skjalaveitur',
},
documentProviderSingle: {
id: 'sp.document-provider:document-provider-single',
defaultMessage: 'Skjalaveitandi',
},
MyCategories: {
id: 'sp.document-provider:my-categories',
defaultMessage: 'Mínir flokkar',
},
Settings: {
id: 'sp.document-provider:settings',
defaultMessage: 'Stillingar',
},
TechnicalInformation: {
id: 'sp.document-provider:technical-information',
defaultMessage: 'Tæknileg útfærsla',
},
Statistics: {
id: 'sp.document-provider:statistics',
defaultMessage: 'Tölfræði',
},
//Screens
//DashBoard
DashBoardTitle: {
id: 'sp.document-provider:dashboard-title',
defaultMessage: 'Skjalaveita',
},
DashBoardDescription: {
id: 'sp.document-provider:dashboard-description',
defaultMessage: 'Á þessari síðu getur þú skoðað tölfræði yfir send skjöl.',
},
DashBoardStatisticsFileName: {
id: 'sp.document-provider:dashboard-statistics-file-name',
defaultMessage: 'Leitaðu eftir skjalaheiti',
},
DashBoardStatisticsCategory: {
id: 'sp.document-provider:dashboard-statistics-category',
defaultMessage: 'Flokkur',
},
DashBoardStatisticsCategoryPlaceHolder: {
id: 'sp.document-provider:dashboard-statistics-category-placeholder',
defaultMessage: 'Veldu flokk',
},
DashBoardStatisticsType: {
id: 'sp.document-provider:dashboard-statistics-type',
defaultMessage: 'Tegund',
},
DashBoardStatisticsTypePlaceHolder: {
id: 'sp.document-provider:dashboard-statistics-type-placeholder',
defaultMessage: 'Veldu tegund',
},
DashBoardStatisticsDateFrom: {
id: 'sp.document-provider:dashboard-statistics-date-from',
defaultMessage: 'Dagsetning frá',
},
DashBoardStatisticsDateFromPlaceHolder: {
id: 'sp.document-provider:dashboard-statistics-date-from-placeholder',
defaultMessage: 'Veldu dagsetningu',
},
DashBoardStatisticsDateTo: {
id: 'sp.document-provider:dashboard-statistics-date-to',
defaultMessage: 'Dagsetning til',
},
DashBoardStatisticsDateToPlaceHolder: {
id: 'sp.document-provider:dashboard-statistics-date-to-placeholder',
defaultMessage: 'Veldu dagsetningu',
},
DashBoardStatisticsSearchButton: {
id: 'sp.document-provider:dashboard-statistics-search-button',
defaultMessage: 'Skoða tölfræði',
},
//DocumentProviders
documentProvidersTitle: {
id: 'sp.document-provider:document-providers-title',
defaultMessage: 'Skjalaveitur',
},
documentProvidersDescription: {
id: 'sp.document-provider:document-providers-description',
defaultMessage:
'Hér getur þú fundið alla þá skjalaveitur sem nota pósthólf á island.is',
},
documentProvidersSearchPlaceholder: {
id: 'sp.document-provider:document-providers-search-placeholder',
defaultMessage: 'Leitaðu að skjalaveitu',
},
documentProvidersNumberOfSearchResultsFoundMessage: {
id:
'sp.document-provider:document-providers-number-of-search-results-found-message',
defaultMessage: 'Skjalaveitur fundust',
},
documentProvidersSearchResultsActionCardLabel: {
id:
'sp.document-provider:document-providers-search-results-action-card-label',
defaultMessage: 'Skoða nánar',
},
documentProvidersDateFromLabel: {
id: 'sp.document-provider:document-providers-datefrom-label',
defaultMessage: 'Dagsetning frá',
},
documentProvidersDateFromPlaceholderText: {
id: 'sp.document-provider:document-providers-datefrom-placeholder-text',
defaultMessage: 'Veldu dagsetningu',
},
documentProvidersDateToLabel: {
id: 'sp.document-provider:document-providers-datefrom-label',
defaultMessage: 'Dagsetning til',
},
documentProvidersDateToPlaceholderText: {
id: 'sp.document-provider:document-providers-dateto-placeholder-text',
defaultMessage: 'Veldu dagsetningu',
},
documentProvidersDateToErrorMessage: {
id: 'sp.document-provider:document-providers-dateto-error-message',
defaultMessage: 'Dagsetning til þarf að vera stærri en dagsetning frá',
},
//DocumentProvidersSingle
//DocumentProvidersSingleInstitution
SingleProviderDescription: {
id: 'sp.document-provider:document-providers-single-description',
defaultMessage: 'Ýtarlegar upplýsingar um skjalaveitu',
},
SingleProviderOrganisationNameNotFoundMessage: {
id:
'sp.document-provider:single-provider-organistion-name-not-found-message',
defaultMessage: 'Heiti stofnunar fannst ekki',
},
SingleProviderInstitutionHeading: {
id: 'sp.document-provider:document-providers-single-institution-name',
defaultMessage: 'Stofnun',
},
SingleProviderInstitutionNameLabel: {
id: 'sp.document-provider:document-providers-single-institution-name-label',
defaultMessage: 'Nafn á stofnun',
},
SingleProviderInstitutionNamePlaceholder: {
id:
'sp.document-provider:document-providers-single-institution-name-placeholder',
defaultMessage: 'Nafn á stofnun',
},
SingleProviderInstitutionNameError: {
id: 'sp.document-provider:document-providers-single-institution-name-error',
defaultMessage: 'Nafn á stofnun er skilyrt',
},
SingleProviderInstitutionNationalIdLabel: {
id:
'sp.document-provider:document-providers-single-institution-nationalid-label',
defaultMessage: 'Kennitala',
},
SingleProviderInstitutionNationalIdPlaceholder: {
id:
'sp.document-provider:document-providers-single-institution-nationalid-placeholder',
defaultMessage: 'Kennitala',
},
SingleProviderInstitutionNationalIdError: {
id:
'sp.document-provider:document-providers-single-institution-nationalid-error',
defaultMessage: 'Kennitala er skilyrt',
},
SingleProviderInstitutionNationalIdFormatError: {
id:
'sp.document-provider:document-providers-single-institution-nationalid-format-error',
defaultMessage: 'Kennitala verður að vera á réttu sniði',
},
SingleProviderInstitutionEmailLabel: {
id:
'sp.document-provider:document-providers-single-institution-email-label',
defaultMessage: 'Netfang',
},
SingleProviderInstitutionEmailPlaceholder: {
id:
'sp.document-provider:document-providers-single-institution-email-placeholder',
defaultMessage: 'Netfang',
},
SingleProviderInstitutionEmailError: {
id:
'sp.document-provider:document-providers-single-institution-email-error',
defaultMessage: 'Netfang er skilyrt',
},
SingleProviderInstitutionEmailFormatError: {
id:
'sp.document-provider:document-providers-single-institution-email-format-error',
defaultMessage: 'Netfang verður að vera á réttu sniði',
},
SingleProviderInstitutionPhonenumberLabel: {
id:
'sp.document-provider:document-providers-single-institution-phonenumber-label',
defaultMessage: 'Símanúmer',
},
SingleProviderInstitutionPhonenumberPlaceholder: {
id:
'sp.document-provider:document-providers-single-institution-phonenumber-placeholder',
defaultMessage: 'Símanúmer',
},
SingleProviderInstitutionPhonenumberError: {
id:
'sp.document-provider:document-providers-single-institution-phonenumber-error',
defaultMessage: 'Símanúmer er skilyrt',
},
SingleProviderInstitutionPhonenumberErrorOnlyNumbers: {
id:
'sp.document-provider:document-providers-single-institution-phonenumber-error-only-numbers',
defaultMessage: 'Eingöngu tölustafir eru leyfðir',
},
SingleProviderInstitutionPhonenumberErrorLength: {
id:
'sp.document-provider:document-providers-single-institution-phonenumber-error-length',
defaultMessage: 'Símanúmer þarf að vera 7 tölustafir á lengd',
},
SingleProviderInstitutionAddressLabel: {
id:
'sp.document-provider:document-providers-single-institution-address-label',
defaultMessage: 'Heimilisfang',
},
SingleProviderInstitutionAddressPlaceholder: {
id:
'sp.document-provider:document-providers-single-institution-address-placeholder',
defaultMessage: 'Heimilisfang',
},
SingleProviderInstitutionAddressError: {
id:
'sp.document-provider:document-providers-single-institution-address-error',
defaultMessage: 'Heimilisfang er skilyrt',
},
SingleProviderUpdateInformationError: {
id:
'sp.document-provider:document-providers-single-update-information-error',
defaultMessage: 'Ekki tókst að uppfæra upplýsingar',
},
SingleProviderUpdateInformationSuccess: {
id:
'sp.document-provider:document-providers-single-update-information-success',
defaultMessage: 'Upplýsingar uppfærðar!',
},
//DocumentProvidersSingleResponsibleContact
SingleProviderResponsibleContactHeading: {
id:
'sp.document-provider:document-providers-single-responsible-contact-heading',
defaultMessage: 'Ábyrgðarmaður',
},
SingleProviderResponsibleContactNameLabel: {
id:
'sp.document-provider:document-providers-single-responsible-contact-name-label',
defaultMessage: 'Nafn',
},
SingleProviderResponsibleContactNamePlaceholder: {
id:
'sp.document-provider:document-providers-single-responsible-contact-name-placeholder',
defaultMessage: 'Nafn',
},
SingleProviderResponsibleContactNameError: {
id:
'sp.document-provider:document-providers-single-responsible-contact-name-error',
defaultMessage: 'Nafn er skilyrt',
},
SingleProviderResponsibleContactEmailLabel: {
id:
'sp.document-provider:document-providers-single-responsible-contact-email-label',
defaultMessage: 'Netfang',
},
SingleProviderResponsibleContactEmailPlaceholder: {
id:
'sp.document-provider:document-providers-single-responsible-contact-email-placeholder',
defaultMessage: 'Netfang',
},
SingleProviderResponsibleContactEmailError: {
id:
'sp.document-provider:document-providers-single-responsible-contact-email-error',
defaultMessage: 'Netfang er skilyrt',
},
SingleProviderResponsibleContactEmailFormatError: {
id:
'sp.document-provider:document-providers-single-responsible-contact-email-format-error',
defaultMessage: 'Netfang verður að vera á réttu sniði',
},
SingleProviderResponsibleContactPhoneNumberLabel: {
id:
'sp.document-provider:document-providers-single-responsible-contact-phoneNumber-label',
defaultMessage: 'Símanúmer',
},
SingleProviderResponsibleContactPhoneNumberPlaceholder: {
id:
'sp.document-provider:document-providers-single-responsible-contact-phoneNumber-placeholder',
defaultMessage: 'Símanúmer',
},
SingleProviderResponsibleContactPhonenumberError: {
id:
'sp.document-provider:document-providers-single-responsible-contact-phonenumber-error',
defaultMessage: 'Símanúmer er skilyrt',
},
SingleProviderResponsibleContactPhonenumberErrorOnlyNumbers: {
id:
'sp.document-provider:document-providers-single-responsible-contact-phonenumber-error-only-numbers',
defaultMessage: 'Eingöngu tölustafir eru leyfðir',
},
SingleProviderResponsibleContactPhonenumberErrorLength: {
id:
'sp.document-provider:document-providers-single-responsible-contact-phonenumber-error-length',
defaultMessage: 'Símanúmer þarf að vera 7 tölustafir á lengd',
},
SingleProviderGetOrganisationError: {
id: 'sp.document-provider:document-providers-single-get-organisation-error',
defaultMessage: 'Ekki tókst að sækja upplýsingar um stofnun með kt.',
},
//DocumentProvidersSingleTechnicalContact
SingleProviderTechnicalContactHeading: {
id:
'sp.document-provider:document-providers-single-technical-contact-heading',
defaultMessage: 'Tæknilegur tengiliður',
},
SingleProviderTechnicalContactNameLabel: {
id:
'sp.document-provider:document-providers-single-technical-contact-name-label',
defaultMessage: 'Nafn',
},
SingleProviderTechnicalContactNamePlaceholder: {
id:
'sp.document-provider:document-providers-single-technical-contact-name-placeholder',
defaultMessage: 'Nafn',
},
SingleProviderTechnicalContactNameError: {
id:
'sp.document-provider:document-providers-single-technical-contact-name-error',
defaultMessage: 'Nafn er skilyrt',
},
SingleProviderTechnicalContactEmailLabel: {
id:
'sp.document-provider:document-providers-single-technical-contact-email-label',
defaultMessage: 'Netfang',
},
SingleProviderTechnicalContactEmailPlaceholder: {
id:
'sp.document-provider:document-providers-single-technical-contact-email-placeholder',
defaultMessage: 'Netfang',
},
SingleProviderTechnicalContactEmailError: {
id:
'sp.document-provider:document-providers-single-technical-contact-email-error',
defaultMessage: 'Netfang er skilyrt',
},
SingleProviderTechnicalContactEmailErrorFormat: {
id:
'sp.document-provider:document-providers-single-technical-contact-email-error-format',
defaultMessage: 'Netfang verður að vera á réttu sniði',
},
SingleProviderTechnicalContactPhoneNumberLabel: {
id:
'sp.document-provider:document-providers-single-technical-contact-phoneNumber-label',
defaultMessage: 'Símanúmer',
},
SingleProviderTechnicalContactPhoneNumberPlaceholder: {
id:
'sp.document-provider:document-providers-single-technical-contact-phoneNumber-placeholder',
defaultMessage: 'Símanúmer',
},
SingleProviderTechnicalContactPhonenumberError: {
id:
'sp.document-provider:document-providers-single-technical-contact-phonenumber-error',
defaultMessage: 'Símanúmer er skilyrt',
},
SingleProviderTechnicalContactPhonenumberErrorOnlyNumbers: {
id:
'sp.document-provider:document-providers-single-technical-contact-phonenumber-error-only-numbers',
defaultMessage: 'Eingöngu tölustafir eru leyfðir',
},
SingleProviderTechnicalContactPhonenumberErrorLength: {
id:
'sp.document-provider:document-providers-single-technical-contact-phonenumber-error-length',
defaultMessage: 'Símanúmer þarf að vera 7 tölustafir á lengd',
},
//DocumentProvidersSingleUserHelpContact
SingleProviderUserHelpContactHeading: {
id:
'sp.document-provider:document-providers-single-user-help-contact-heading',
defaultMessage: 'Notendaaðstoð',
},
SingleProviderUserHelpContactEmailLabel: {
id:
'sp.document-provider:document-providers-single-user-help-contact-email-label',
defaultMessage: 'Netfang',
},
SingleProviderUserHelpEmailError: {
id:
'sp.document-provider:document-providers-single-user-help-contact-email-error',
defaultMessage: 'Netfang er skilyrt',
},
SingleProviderUserHelpEmailErrorFormat: {
id:
'sp.document-provider:document-providers-single-user-help-contact-email-error-format',
defaultMessage: 'Netfang verður að vera á réttu sniði',
},
SingleProviderUserHelpContactEmailPlaceholder: {
id:
'sp.document-provider:document-providers-single-user-help-contact-email-placeholder',
defaultMessage: 'Netfang',
},
SingleProviderUserHelpContactPhoneNumberLabel: {
id:
'sp.document-provider:document-providers-single-user-help-contact-phoneNumber-label',
defaultMessage: 'Símanúmer',
},
SingleProviderUserHelpContactPhoneNumberPlaceholder: {
id:
'sp.document-provider:document-providers-single-user-help-contact-phoneNumber-placeholder',
defaultMessage: 'Símanúmer',
},
SingleProviderUserHelpPhonenumberError: {
id:
'sp.document-provider:document-providers-single-user-help-contact-phonenumber-error',
defaultMessage: 'Símanúmer er skilyrt',
},
SingleProviderUserHelpPhonenumberErrorOnlyNumbers: {
id:
'sp.document-provider:document-providers-single-user-help-contact-phonenumber-error-only-numbers',
defaultMessage: 'Eingöngu tölustafir eru leyfðir',
},
SingleProviderUserHelpPhonenumberErrorLength: {
id:
'sp.document-provider:document-providers-single-user-help-contact-phonenumber-error-length',
defaultMessage: 'Símanúmer þarf að vera 7 tölustafir á lengd',
},
//DocumentProvidersSingleButtons
SingleProviderBackButton: {
id: 'sp.document-provider:document-providers-single-back-button',
defaultMessage: 'Til baka',
},
SingleProviderSaveButton: {
id: 'sp.document-provider:document-providers-single-save-button',
defaultMessage: 'Vista breytingar',
},
//MyCategories
myCategoriesTitle: {
id: 'sp.document-provider:my-categories-title',
defaultMessage: 'Mínir flokkar',
},
myCategoriesDescription: {
id: 'sp.document-provider:my-categories-description',
defaultMessage:
'Einungis fyrir skjalaveitendur. Á þessari síðu getur þú bætt/breytt/eytt flokkum... TODO LAST',
},
//Settings
SettingsTitle: {
id: 'sp.document-provider:document-provider-settings-title',
defaultMessage: 'Stillingar',
},
//Stofnun
EditInstitution: {
id: 'sp.document-provider:edit-institution',
defaultMessage: 'Breyta stofnun',
},
EditInstitutionDescription: {
id: 'sp.document-provider:edit-institution-description',
defaultMessage: 'Hér getur þú breytt grunnupplýsingum fyrir stofnun',
},
//Ábyrgðarmaður
EditResponsibleContact: {
id: 'sp.document-provider:edit-responsible-contact',
defaultMessage: 'Breyta ábyrgðarmanni',
},
EditResponsibleContactDescription: {
id: 'sp.document-provider:edit-responsible-contact-description',
defaultMessage: 'Hér getur þú breytt upplýsingum um ábyrgðarmann',
},
//Tæknilegur tengiliður
EditTechnicalContact: {
id: 'sp.document-provider:edit-technical-contact',
defaultMessage: 'Breyta tæknilegum tengilið',
},
EditTechnicalContactDescription: {
id: 'sp.document-provider:edit-technical-contact-description',
defaultMessage: 'Hér getur þú breytt upplýsingum um tæknilegan tengilið',
},
//Notendaaðstoð
EditUserHelpContact: {
id: 'sp.document-provider:edit-user-help-contact',
defaultMessage: 'Breyta notendaaðstoð',
},
EditUserHelpContactDescription: {
id: 'sp.document-provider:edit-user-help-contact',
defaultMessage: 'Hér getur þú breytt upplýsingum um notendaaðstoð',
},
//Endapunktur
EditEndPoints: {
id: 'sp.document-provider:edit-endpoints',
defaultMessage: 'Breyta endapunkt',
},
EditEndPointsDescription: {
id: 'sp.document-provider:edit-endpoints',
defaultMessage: 'Hér getur þú breytt endpunkt',
},
//EditInstitution
SettingsEditInstitutionTitle: {
id: 'sp.document-provider:settings-edit-institution-title',
defaultMessage: 'Breyta stofnun',
},
SettingsEditInstitutionDescription: {
id: 'sp.document-provider:settings-edit-institution-description',
defaultMessage: 'Hér kemur form fyrir stofnun TODO',
},
SettingsEditInstitutionName: {
id: 'sp.document-provider:settings-edit-institution-name',
defaultMessage: 'Nafn á stofnun',
},
SettingsEditInstitutionNameRequiredMessage: {
id: 'sp.document-provider:settings-edit-institution-name-required-message',
defaultMessage: 'Skylda er að fylla út nafn stofnunar',
},
SettingsEditInstitutionNationalId: {
id: 'sp.document-provider:settings-edit-institution-nationalId',
defaultMessage: 'Kennitala',
},
SettingsEditInstitutionNationalIdRequiredMessage: {
id:
'sp.document-provider:settings-edit-institution-nationalId-required-message',
defaultMessage: 'Skylda er að fylla út kennitölu',
},
SettingsEditInstitutionNationalIdWrongFormatMessage: {
id:
'sp.document-provider:settings-edit-institution-nationalId-wrong-format-message',
defaultMessage: 'Kennitalan er ekki á réttu formi',
},
SettingsEditInstitutionAddress: {
id: 'sp.document-provider:settings-edit-institution-address',
defaultMessage: 'Heimilisfang',
},
SettingsEditInstitutionAddressRequiredMessage: {
id:
'sp.document-provider:settings-edit-institution-address-required-message',
defaultMessage: 'Skylda er að fylla út heimilisfang',
},
SettingsEditInstitutionEmail: {
id: 'sp.document-provider:settings-edit-institution-email',
defaultMessage: 'Netfang',
},
SettingsEditInstitutionEmailRequiredMessage: {
id: 'sp.document-provider:settings-edit-institution-email-required-message',
defaultMessage: 'Skylda er að fylla út netfang',
},
SettingsEditInstitutionEmailWrongFormatMessage: {
id:
'sp.document-provider:settings-edit-institution-email-wrong-format-message',
defaultMessage: 'Netfangið er ekki á réttu formi',
},
SettingsEditInstitutionTel: {
id: 'sp.document-provider:settings-edit-institution-tel',
defaultMessage: 'Símanúmer',
},
SettingsEditInstitutionTelRequiredMessage: {
id: 'sp.document-provider:settings-edit-institution-tel-required-message',
defaultMessage: 'Skylda er að fylla út símanúmer',
},
SettingsEditInstitutionTelWrongFormatMessage: {
id:
'sp.document-provider:settings-edit-institution-tel-wrong-format-message',
defaultMessage: 'Símanúmerið er ekki á réttu formi',
},
SettingsEditInstitutionSaveButton: {
id: 'sp.document-provider:settings-edit-institution-save-button',
defaultMessage: 'Vista breytingar',
},
SettingsEditInstitutionBackButton: {
id: 'sp.document-provider:settings-edit-institution-back-button',
defaultMessage: 'Til baka',
},
//EditResponsibleContact
SettingsEditResponsibleContactTitle: {
id: 'sp.document-provider:settings-edit-responsible-contact-title',
defaultMessage: 'Breyta ábyrgðarmanni',
},
SettingsEditResponsibleContactDescription: {
id: 'sp.document-provider:settings-edit-responsible-contact-description',
defaultMessage: 'Hér kemur form fyrir ábyrgðarmann TODO',
},
SettingsEditResponsibleContactName: {
id: 'sp.document-provider:settings-edit-responsible-contact-name',
defaultMessage: 'Nafn',
},
SettingsEditResponsibleContactNameRequiredMessage: {
id:
'sp.document-provider:settings-edit-responsible-contact-name-required-message',
defaultMessage: 'Skylda er að fylla út nafn',
},
SettingsEditResponsibleContactEmail: {
id: 'sp.document-provider:settings-edit-responsible-contact-email',
defaultMessage: 'Netfang',
},
SettingsEditResponsibleContactEmailRequiredMessage: {
id:
'sp.document-provider:settings-edit-responsible-contact-email-required-message',
defaultMessage: 'Skylda er að fylla út netfang',
},
SettingsEditResponsibleContactEmailWrongFormatMessage: {
id:
'sp.document-provider:settings-edit-responsible-contact-email-wrong-format-message',
defaultMessage: 'Netfangið er á vitlausu formi',
},
SettingsEditResponsibleContactTel: {
id: 'sp.document-provider:settings-edit-responsible-contact-tel',
defaultMessage: 'Símanúmer',
},
SettingsEditResponsibleContactTelRequiredMessage: {
id:
'sp.document-provider:settings-edit-responsible-contact-tel-required-message',
defaultMessage: 'Skylda er að fylla út símanúmer',
},
SettingsEditResponsibleContactTelWrongFormatMessage: {
id:
'sp.document-provider:settings-edit-responsible-contact-tel-wrong-format-message',
defaultMessage: 'Símanúmerið er á vitlausu formi',
},
SettingsEditResponsibleContactSaveButton: {
id: 'sp.document-provider:settings-edit-responsible-contact-save-button',
defaultMessage: 'Vista breytingar',
},
SettingsEditResponsibleContactBackButton: {
id: 'sp.document-provider:settings-edit-responsible-contact-back-button',
defaultMessage: 'Til baka',
},
//EditTechnicalContact
SettingsEditTechnicalContactTitle: {
id: 'sp.document-provider:settings-edit-technical-contact-title',
defaultMessage: 'Breyta tæknilegum tengilið',
},
SettingsEditTechnicalContactDescription: {
id: 'sp.document-provider:settings-edit-technical-contact-description',
defaultMessage: 'Hér kemur form fyrir tæknilegan tengilið TODO',
},
SettingsEditTechnicalContactName: {
id: 'sp.document-provider:settings-edit-technical-contact-name',
defaultMessage: 'Nafn',
},
SettingsEditTechnicalContactNameRequiredMessage: {
id:
'sp.document-provider:settings-edit-technical-contact-name-required-message',
defaultMessage: 'Skylda er að fylla út nafn',
},
SettingsEditTechnicalContactEmail: {
id: 'sp.document-provider:settings-edit-technical-contact-email',
defaultMessage: 'Netfang',
},
SettingsEditTechnicalContactEmailRequiredMessage: {
id:
'sp.document-provider:settings-edit-technical-contact-email-required-message',
defaultMessage: 'Skylda er að fylla út netfang',
},
SettingsEditTechnicalContactEmailWrongFormatMessage: {
id:
'sp.document-provider:settings-edit-technical-contact-email-wrong-format-message',
defaultMessage: 'Netfangið er ekki á réttu formi',
},
SettingsEditTechnicalContactTel: {
id: 'sp.document-provider:settings-edit-technical-contact-tel',
defaultMessage: 'Símanúmer',
},
SettingsEditTechnicalContactTelRequiredMessage: {
id:
'sp.document-provider:settings-edit-technical-contact-tel-required-message',
defaultMessage: 'Skylda er að fylla út símanúmer',
},
SettingsEditTechnicalContactTelWrongFormatMessage: {
id:
'sp.document-provider:settings-edit-technical-contact-tel-wrong-format-message',
defaultMessage: 'Símanúmerið er ekki á réttu formi',
},
SettingsEditTechnicalContactSaveButton: {
id: 'sp.document-provider:settings-edit-technical-contact-save-button',
defaultMessage: 'Vista breytingar',
},
SettingsEditTechnicalContactBackButton: {
id: 'sp.document-provider:settings-edit-technical-contact-back-button',
defaultMessage: 'Til baka',
},
//EditUserHelpContact
SettingsEditUserHelpContactTitle: {
id: 'sp.document-provider:settings-edit-user-help-contact-title',
defaultMessage: 'Breyta notendaaðstoð',
},
SettingsEditUserHelpContactDescription: {
id: 'sp.document-provider:settings-edit-user-help-contact-description',
defaultMessage: 'Hér kemur form fyrir notendaaðstoð TODO',
},
SettingsEditUserHelpContactEmail: {
id: 'sp.document-provider:settings-edit-user-help-contact-email',
defaultMessage: 'Netfang',
},
SettingsEditUserHelpContactEmailRequiredMessage: {
id:
'sp.document-provider:settings-edit-user-help-contact-email-required-message',
defaultMessage: 'Skylda er að fylla út netfang',
},
SettingsEditUserHelpContactEmailWrongFormatMessage: {
id: 'sp.document-provider:settings-edit-user-help-contact-email',
defaultMessage: 'Netfangið er ekki á réttu formi',
},
SettingsEditUserHelpContactTel: {
id: 'sp.document-provider:settings-edit-user-help-contact-tel',
defaultMessage: 'Símanúmer',
},
SettingsEditUserHelpContactTelRequiredMessage: {
id:
'sp.document-provider:settings-edit-user-help-contact-tel-required-message',
defaultMessage: 'Skylda er að fylla út símanúmer',
},
SettingsEditUserHelpContactTelWrongFormatMessage: {
id:
'sp.document-provider:settings-edit-user-help-contact-tel-wrong-format-message',
defaultMessage: 'Símanúmerið er ekki á réttu formi',
},
SettingsEditHelpContactSaveButton: {
id: 'sp.document-provider:settings-edit-help-contact-save-button',
defaultMessage: 'Vista breytingar',
},
SettingsEditHelpContactBackButton: {
id: 'sp.document-provider:settings-edit-help-contact-back-button',
defaultMessage: 'Til baka',
},
//EditEndPoints
SettingsEditEndPointsTitle: {
id: 'sp.document-provider:settings-edit-endpoints-title',
defaultMessage: 'Breyta endapunkt',
},
SettingsEditEndPointsDescription: {
id: 'sp.document-provider:settings-edit-endpoints-description',
defaultMessage: 'Hér kemur form fyrir endapunkta TODO',
},
SettingsEditEndPointsUrl: {
id: 'sp.document-provider:settings-edit-endpoints-url',
defaultMessage: 'Endapunktur',
},
SettingsEditEndPointsUrlRequiredMessage: {
id: 'sp.document-provider:settings-edit-endpoints-url-required-message',
defaultMessage: 'Skylda er að fylla út endapunkt',
},
SettingsEditEndPointsUrlWrongFormatMessage: {
id: 'sp.document-provider:settings-edit-endpoints-url-wrong-format-message',
defaultMessage: 'Endapunkturinn er ekki á réttu formi',
},
SettingsEditEndPointsSaveButton: {
id: 'sp.document-provider:settings-edit-endpoints-save-button',
defaultMessage: 'Vista breytingar',
},
SettingsEditEndPointsBackButton: {
id: 'sp.document-provider:settings-edit-endpoints-back-button',
defaultMessage: 'Til baka',
},
//TechnicalInformation
TechnicalInformationTitle: {
id: 'sp.document-provider:technical-information-title',
defaultMessage: 'Tæknilegar upplýsingar',
},
TechnicalInformationDescription: {
id: 'sp.document-provider:technical-information-description',
defaultMessage: 'Á þessari síðu sérð þú upplýsingar um tæknileg atriði',
},
//Statistics
StatisticsTitle: {
id: 'sp.document-provider:statistics-information-title',
defaultMessage: 'Tölfræði',
},
StatisticsDescription: {
id: 'sp.document-provider:statistics-information-description',
defaultMessage: 'Hér er tölfræði yfir rafrænar skjalasendingar ',
},
StatisticsSearchPlaceholder: {
id: 'sp.document-provider:statistics-search-placeholder',
defaultMessage: 'Leitaðu eftir skjalaveitanda',
},
//Statistics boxes
statisticsBoxOrganisationsCount: {
id: 'sp.document-provider:statistics-box-organisations-count',
defaultMessage: 'Fjöldi skjalaveitna',
},
statisticsBoxPublishedDocuments: {
id: 'sp.document-provider:statistics-box-published-documents',
defaultMessage: 'Send skjöl',
},
statisticsBoxOpenedDocuments: {
id: 'sp.document-provider:statistics-box-opened-documents',
defaultMessage: 'Opnuð skjöl',
},
statisticsBoxNotifications: {
id: 'sp.document-provider:statistics-box-notifications',
defaultMessage: 'Hnipp',
},
statisticsBoxMillions: {
id: 'sp.document-provider:statistics-box-millions',
defaultMessage: 'milljón',
},
statisticsBoxThousands: {
id: 'sp.document-provider:statistics-box-thousands',
defaultMessage: 'þúsund',
},
statisticsBoxNetworkError: {
id: 'sp.document-provider:statistics-box-network-error',
defaultMessage: 'Ekki tókst að sækja tölfræði',
},
}) | the_stack |
describe('infra node detail', () => {
let adminIdToken = '';
let nodeName = '';
let runlist = '';
const environment = '';
const serverID = 'chef-manage';
const serverName = 'chef manage';
const orgID = 'viveksingh_msys';
const orgName = 'viveksingh_msys';
const serverFQDN = 'api.chef.io';
const serverIP = '50.21.221.24';
const adminUser = 'viveksingh_msys';
const adminKey = Cypress.env('AUTOMATE_INFRA_ADMIN_KEY').replace(/\\n/g, '\n');
const nullJson = '{}';
const validJson = '{"test":"test"}';
const invalidJson = '{"invalid "test"';
before(() => {
cy.adminLogin('/').then(() => {
const admin = JSON.parse(<string>localStorage.getItem('chef-automate-user'));
adminIdToken = admin.id_token;
cy.request({
auth: { bearer: adminIdToken },
failOnStatusCode: false,
method: 'POST',
url: '/api/v0/infra/servers',
body: {
id: serverID,
name: serverName,
fqdn: serverFQDN,
ip_address: serverIP
}
}).then((response) => {
if (response.status === 200 && response.body.ok === true) {
return;
} else {
cy.request({
auth: { bearer: adminIdToken },
method: 'GET',
url: `/api/v0/infra/servers/${serverID}`,
body: {
id: serverID
}
});
}
});
cy.request({
auth: { bearer: adminIdToken },
failOnStatusCode: false,
method: 'POST',
url: `/api/v0/infra/servers/${serverID}/orgs`,
body: {
id: orgID,
server_id: serverID,
name: orgName,
admin_user: adminUser,
admin_key: adminKey
}
}).then((response) => {
if (response.status === 200 && response.body.ok === true) {
return;
} else {
cy.request({
auth: { bearer: adminIdToken },
method: 'GET',
url: `/api/v0/infra/servers/${serverID}/orgs/${orgID}`,
body: {
id: orgID,
server_id: serverID
}
});
}
});
cy.visit(`/infrastructure/chef-servers/${serverID}/organizations/${orgID}`);
cy.get('app-welcome-modal').invoke('hide');
});
cy.restoreStorage();
});
beforeEach(() => {
cy.restoreStorage();
});
afterEach(() => {
cy.saveStorage();
});
function getNodes(node: string, page: number, per_page = 9) {
const wildCardSearch = '*';
const target = nodeName !== '' ?
'name:' + wildCardSearch + node : wildCardSearch + ':';
const nameTarget = target + wildCardSearch;
const currentPage = page - 1;
// Add asterisk to do wildcard search
const params =
`search_query.q=${nameTarget}&search_query.page=${currentPage}&search_query.per_page=${per_page}`;
return cy.request({
auth: { bearer: adminIdToken },
failOnStatusCode: false,
method: 'GET',
url: `/api/v0/infra/servers/${serverID}/orgs/${orgID}/nodes?${params}`
});
}
function checkNodesResponse(response: any) {
if (response.body.nodes.length === 0) {
cy.get('[data-cy=empty-list]').should('be.visible');
} else {
cy.get('[data-cy=nodes-table-container] chef-th').contains('Node');
cy.get('[data-cy=nodes-table-container] chef-th').contains('Platform');
cy.get('[data-cy=nodes-table-container] chef-th').contains('FQDN');
cy.get('[data-cy=nodes-table-container] chef-th').contains('IP Address');
cy.get('[data-cy=nodes-table-container] chef-th').contains('Uptime');
cy.get('[data-cy=nodes-table-container] chef-th').contains('Last Check-In');
cy.get('[data-cy=nodes-table-container] chef-th').contains('Environment');
nodeName = response.body.nodes[0].name;
return true;
}
}
function getRunlist(name: string) {
return cy.request({
auth: { bearer: adminIdToken },
failOnStatusCode: false,
method: 'GET',
url: `/api/v0/infra/servers/${serverID}/orgs/${orgID}/node/${nodeName}/runlist/${name}`
});
}
function checkResponse(response: any) {
if (response.status === 200) {
if (response.body.run_list.length === 0) {
cy.get('[data-cy=empty-runlist]').scrollIntoView().should('be.visible');
} else {
cy.get('.details-tab').scrollIntoView();
cy.get('[data-cy=node-expand-runlist]').contains('Expand All');
cy.get('[data-cy=node-collapse-runlist]').contains('Collapse All');
cy.get('[data-cy=node-edit-runlist]').contains('Edit');
cy.get('[data-cy=runlist-table-container] th').contains('Version');
cy.get('[data-cy=runlist-table-container] th').contains('Position');
runlist = response.body.run_list[0].name;
return true;
}
} else {
cy.get('[data-cy=error-runlist]').scrollIntoView().should('be.visible');
}
}
describe('infra node list page', () => {
it('displays org details', () => {
cy.get('.page-title').contains(orgName);
});
// node tabs specs
it('can switch to node tab', () => {
cy.get('.nav-tab').contains('Nodes').click();
});
it('can check if node has list or not', () => {
getNodes('', 1).then((response) => {
checkNodesResponse(response);
});
});
it('can go to details page', () => {
if (nodeName !== '') {
cy.get('[data-cy=nodes-table-container] chef-td').contains(nodeName).click();
}
});
// details tab specs
it('displays infra node details', () => {
if (nodeName !== '') {
cy.get('.page-title').contains(nodeName);
cy.get('[data-cy=infra-node-head]').contains(nodeName);
cy.get('[data-cy=node-server]').contains(serverID);
cy.get('[data-cy=node-org]').contains(orgID);
}
});
it('can add the node tags', () => {
if (nodeName !== '') {
cy.get('[data-cy=add-tag]').clear().type('tag1');
cy.get('[data-cy=add-tag-button]').click();
cy.get('app-notification.info').contains('Successfully updated node tags.');
cy.get('app-notification.info chef-icon').click();
cy.get('[data-cy=tag-box]').scrollIntoView();
cy.get('[data-cy=tag-box]').should(('be.visible'));
}
});
it('can show the node tags box', () => {
if (nodeName !== '') {
cy.get('[data-cy=tag-box]').scrollIntoView();
cy.get('[data-cy=tag-box]').should(('be.visible'));
}
});
it('can add the multiple node tags', () => {
if (nodeName !== '') {
cy.get('[data-cy=add-tag]').clear().type('tag2, tag3, tag4, tag5');
cy.get('[data-cy=add-tag-button]').click();
cy.get('app-notification.info').contains('Successfully updated node tags.');
cy.get('app-notification.info chef-icon').click();
cy.get('[data-cy=tag-box]').scrollIntoView();
cy.get('[data-cy=tag-box]').should(('be.visible'));
cy.get('.display-node-tags').find('span').should('have.length', 5);
}
});
it('can remove the node tags', () => {
if (nodeName !== '') {
cy.get('[data-cy=remove-tag]').eq(0).click();
cy.get('app-notification.info').contains('Successfully updated node tags.');
cy.get('[data-cy=tag-box]').scrollIntoView();
cy.get('[data-cy=tag-box]').should(('be.visible'));
cy.get('.display-node-tags').find('span').should('have.length', 4);
}
});
it('can check environments list available or not in dropdown', () => {
if (nodeName !== '') {
cy.request({
auth: { bearer: adminIdToken },
method: 'GET',
url: `/api/v0/infra/servers/${serverID}/orgs/${orgID}/environments`
}).then((environmentResponse) => {
if (environmentResponse.status === 200 && environmentResponse.body.ok === true) {
expect(environmentResponse.status).to.equal(200);
}
if (environmentResponse.body.environments.length === 0) {
cy.get('.ng-dropdown-panel-items').should('not.be.visible');
} else {
cy.get('.ng-arrow-wrapper').click();
cy.get('.ng-dropdown-panel-items').should(('be.visible'));
cy.get('.ng-arrow-wrapper').click();
}
});
}
});
it('can select environment and display the confirmation box', () => {
if (nodeName !== '') {
cy.get('.ng-arrow-wrapper').click();
cy.get('.ng-dropdown-panel-items').should(('be.visible'));
cy.get('.ng-option').contains('google').then(option => {
option[0].click(); // this is jquery click() not cypress click()
});
cy.get('[data-cy=change-confirm]').should(('be.visible'));
}
});
it('can cancel the environemnt update', () => {
if (nodeName !== '') {
cy.get('.ng-arrow-wrapper').click();
cy.get('.ng-dropdown-panel-items').should(('be.visible'));
cy.get('.ng-option').contains('_default').then(option => {
option[0].click(); // this is jquery click() not cypress click()
});
cy.get('[data-cy=change-confirm]').should(('be.visible'));
cy.get('#button-env [data-cy=cancel-button]').click();
cy.get('[data-cy=change-confirm]').should(('not.be.visible'));
}
});
it('can update the environemnt', () => {
if (nodeName !== '') {
cy.get('.ng-arrow-wrapper').click();
cy.get('.ng-dropdown-panel-items').should(('be.visible'));
cy.get('.ng-option').contains('chef-environment-609823800').then(option => {
option[0].click(); // this is jquery click() not cypress click()
});
cy.get('.ng-arrow-wrapper').click();
cy.get('.ng-dropdown-panel-items').should(('be.visible'));
cy.get('.ng-option').contains('_default').then(option => {
option[0].click(); // this is jquery click() not cypress click()
});
cy.get('[data-cy=change-confirm]').should(('be.visible'));
cy.get('[data-cy=save-button]').click();
}
});
});
describe('inside run list tab ', () => {
// switch to Run list tab specs
it('can switch to run list tab', () => {
if (nodeName !== '') {
cy.get('[data-cy=run-list-tab]').contains('Run list').click();
cy.get('.default').contains('Run List');
}
});
it('can check if node has run list or not', () => {
if (nodeName !== '' && environment !== '' && environment === '_default') {
getRunlist(environment).then((response) => {
checkResponse(response);
});
}
});
it('can select multiple item from list, move to right then update the run list', () => {
if (nodeName !== '' && runlist !== '') {
cy.get('[data-cy=node-edit-runlist]').contains('Edit').click();
cy.get('app-infra-node-details chef-modal').should('exist');
cy.get('.cdk-virtual-scroll-content-wrapper [data-cy=select-run-list]')
.contains('test').click();
cy.get('.cdk-virtual-scroll-content-wrapper [data-cy=select-run-list]').contains('chef')
.click();
cy.get('[data-cy=drag-right]').click();
cy.get('[data-cy=update-run-list]').click();
cy.get('app-infra-node-details chef-modal').should('not.be.visible');
// verify success notification and then dismiss it
// so it doesn't get in the way of subsequent interactions
cy.get('app-notification.info').should('be.visible');
cy.get('app-notification.info chef-icon').click();
getRunlist(environment).then((runlistResponse) => {
checkResponse(runlistResponse);
});
}
});
it('can select a item from selected run list, move to left then update the run list', () => {
if (nodeName !== '' && runlist !== '') {
cy.get('[data-cy=node-edit-runlist]').contains('Edit').click();
cy.get('app-infra-node-details chef-modal').should('exist');
cy.get('.vertical [data-cy=updated-run-list]').contains('test').click();
cy.get('.vertical [data-cy=updated-run-list]').contains('chef').click();
cy.get('[data-cy=drag-left]').click();
cy.get('[data-cy=update-run-list]').click();
cy.get('app-infra-node-details chef-modal').should('not.be.visible');
// verify success notification and then dismiss it
// so it doesn't get in the way of subsequent interactions
cy.get('app-notification.info').should('be.visible');
cy.get('app-notification.info chef-icon').click();
getRunlist(environment).then((runlistResponse) => {
checkResponse(runlistResponse);
});
}
});
it('can check save button is disabled until run list value is not changed', () => {
if (nodeName !== '' && runlist !== '') {
cy.get('[data-cy=node-edit-runlist]').contains('Edit').click();
cy.get('app-infra-node-details chef-modal').should('exist');
cy.get('[data-cy=drag-right]').should('be.disabled');
cy.get('[data-cy=drag-left]').should('be.disabled');
cy.get('[data-cy=drag-up]').should('be.disabled');
cy.get('[data-cy=drag-down]').should('be.disabled');
// check for disabled save button
cy.get('[data-cy=update-run-list]')
.invoke('attr', 'disabled')
.then(disabled => {
disabled ? cy.log('buttonIsDiabled') : cy.get('[data-cy=update-run-list]').click();
});
cy.get('app-infra-node-details chef-modal').should('exist');
// here we exit with the Cancel button
cy.get('[data-cy=cancel-button]').contains('Cancel').should('be.visible').click();
cy.get('app-infra-node-details chef-modal').should('not.be.visible');
}
});
it('can cancel edit run list', () => {
if (nodeName !== '' && runlist !== '') {
cy.get('[data-cy=node-edit-runlist]').contains('Edit').click();
cy.get('app-infra-node-details chef-modal').should('exist');
cy.get('[data-cy=drag-right]').should('be.disabled');
cy.get('[data-cy=drag-left]').should('be.disabled');
cy.get('[data-cy=drag-up]').should('be.disabled');
cy.get('[data-cy=drag-down]').should('be.disabled');
// here we exit with the Cancel button
cy.get('[data-cy=cancel-button]').contains('Cancel').should('be.visible').click();
cy.get('app-infra-node-details chef-modal').should('not.be.visible');
}
});
// switch to Run list tab specs
it('can switch to details tab', () => {
if (nodeName !== '' && runlist !== '') {
cy.get('[data-cy=details-tab]').contains('Details').click();
}
});
it('can update the environemnt and check run list updated or not', () => {
if (nodeName !== '' && runlist !== '') {
// can change the environment
cy.get('.ng-arrow-wrapper').click();
cy.get('.ng-dropdown-panel-items').should(('be.visible'));
cy.get('.scrollable-content .ng-option').contains('chef-environment-5').click();
cy.get('[data-cy=change-confirm]').should(('be.visible'));
cy.get('[data-cy=save-button]').click();
cy.get('.ng-value').contains('chef-environment-5');
cy.get('app-notification.info').contains('Successfully updated node environment.');
cy.get('app-notification.info chef-icon').click();
// can switch to Run list tab specs and check run list
cy.get('[data-cy=run-list-tab]').contains('Run list').click();
cy.get('.default').contains('Run List');
getRunlist(environment).then((response) => {
checkResponse(response);
});
}
});
});
describe('inside attributes tab ', () => {
function updateAttributes(attribute: string) {
const nodeAttribute = {
org_id: orgID,
server_id: serverID,
name: nodeName,
attributes: JSON.parse(attribute.replace(/\r?\n|\r/g, ''))
};
return cy.request({
auth: { bearer: adminIdToken },
method: 'PUT',
url: `/api/v0/infra/servers/${serverID}/orgs/${orgID}/nodes/${nodeName}/attributes`,
body: nodeAttribute
});
}
// switch to attributes tab specs
it('can switch to attributes tab', () => {
cy.get('[data-cy=attributes-tab]').contains('Attributes').click();
cy.get('.default').contains('Attributes');
});
it('attribute tab contains buttons', () => {
cy.get('.default').contains('Attributes');
cy.get('[data-cy=expand-attributes]').contains('Expand All');
cy.get('[data-cy=collapse-attributes]').contains('Collapse All');
cy.get('[data-cy=node-edit-attributes]').contains('Edit');
});
it('can check save button is disabled until attributes value is not changed', () => {
cy.get('[data-cy=node-edit-attributes]').contains('Edit').click();
cy.get('app-infra-node-details chef-modal').should('exist');
// check for disabled save button
cy.get('[data-cy=save-attribute]')
.invoke('attr', 'disabled')
.then(disabled => {
disabled ? cy.log('buttonIsDiabled') : cy.get('[data-cy=save-attribute]').click();
});
cy.get('app-infra-node-details chef-modal').should('exist');
// here we exit with the Cancel button
cy.get('[data-cy=cancel-attribute-button]').contains('Cancel').should('be.visible').click();
cy.get('app-infra-node-details chef-modal').should('not.be.visible');
});
xit('edit attribute and show empty data', () => {
cy.get('[data-cy=node-edit-attributes]').contains('Edit').click({force: true});
cy.get('app-infra-node-details chef-modal').should('exist');
cy.get('[data-cy=attributes]').clear().invoke('val', nullJson)
.trigger('change').type(' ');
cy.get('[data-cy=save-attribute]').click();
cy.get('app-infra-node-details chef-modal').should('not.be.visible');
// verify success notification and then dismiss it
// so it doesn't get in the way of subsequent interactions
cy.get('app-notification.info').should('be.visible');
cy.get('app-notification.info chef-icon').click();
updateAttributes(nullJson).then((response) => {
if (Object.keys(response.body.attributes).length > 0) {
cy.get('[data-cy=expand-attributes]').should('not.be.disabled');
cy.get('[data-cy=collapse-attributes]').should('not.be.disabled');
} else {
cy.get('[data-cy=expand-attributes]').should('be.disabled');
cy.get('[data-cy=collapse-attributes]').should('be.visible');
}
});
});
xit('edit attribute and show updated data', () => {
cy.get('[data-cy=node-edit-attributes]').contains('Edit').click({force: true});
cy.get('app-infra-node-details chef-modal').should('exist');
cy.get('[data-cy=attributes]').clear().invoke('val', validJson)
.trigger('change').type(' ');
cy.get('[data-cy=save-attribute]').click();
cy.get('app-infra-node-details chef-modal').should('not.be.visible');
// verify success notification and then dismiss it
// so it doesn't get in the way of subsequent interactions
cy.get('app-notification.info').should('be.visible');
cy.get('app-notification.info chef-icon').click();
updateAttributes(validJson).then((response) => {
if (Object.keys(response.body.attributes).length > 0) {
cy.get('[data-cy=expand-attributes]').should('not.be.disabled');
cy.get('[data-cy=collapse-attributes]').should('not.be.disabled');
} else {
cy.get('[data-cy=expand-attributes]').should('be.disabled');
cy.get('[data-cy=collapse-attributes]').should('be.visible');
}
});
});
xit('fails to edit attribute with a invalid json', () => {
cy.get('[data-cy=node-edit-attributes').contains('Edit').click();
cy.get('app-infra-node-details chef-modal').should('exist');
cy.get('[data-cy=attributes]').clear().invoke('val', invalidJson).trigger('change');
cy.get('app-infra-node-details chef-modal chef-error')
.contains('Must be a valid JSON object').should('be.visible');
cy.get('[data-cy=cancel-attribute-button]').click();
cy.get('app-infra-node-details chef-modal').should('not.be.visible');
});
xit('can cancel edit attributes', () => {
cy.get('[data-cy=node-edit-attributes]').contains('Edit').click();
cy.get('app-infra-node-details chef-modal').should('exist');
cy.get('[data-cy=cancel-attribute-button]').contains('Cancel').should('be.visible').click();
cy.get('app-infra-node-details chef-modal').should('not.be.visible');
});
// switch to Run details tab
it('can switch to details tab', () => {
cy.get('[data-cy=details-tab]').contains('Details').click();
});
});
}); | the_stack |
import { Structure, ColumnMetadata, ResultsParams, GraphResponse, ResultsResponse, TruncationType } from '../definitions.d'
import SQL from '../adapter/sql'
import moment from 'moment'
export default class Results {
params: Partial<ResultsParams>
structure: Structure
adapter: SQL
response: ResultsResponse | null = null
baseModelName: string | null = null
columnMetadata: ColumnMetadata[] = []
resultsTableColumnMetadata: ColumnMetadata[] = []
commonSqlConditions: {
having: string[]
where: string[]
} = {
having: [],
where: []
}
commonSqlParts: {
fromAndJoins: string
where: string
having: string
} = {
fromAndJoins: '',
where: '',
having: ''
}
resultsTableCount: number = 1
resultsTableSqlParts: {
select: string
group: string
sort: string
limit: number
offset: number
} = {
select: '',
group: '',
sort: '',
limit: 25,
offset: 0
}
finalResults: any[] = []
graphResponse: GraphResponse | null = null
constructor ({ params, adapter, structure } : {
params: Partial<ResultsParams>,
adapter: SQL
structure: Structure
}) {
this.params = params
this.adapter = adapter
this.structure = structure
}
async getResponse () : Promise<ResultsResponse> {
this.resetCache()
// common
this.setJoinsAndColumnMetadata()
this.setFilter()
// table
this.setGroup()
this.setSort()
this.setLimit()
if (!this.params.graphOnly) {
await this.getCount()
await this.getResults()
}
// graph
if (!this.params.tableOnly) {
await this.getGraph()
}
this.setResponse()
return this.response
}
resetCache () {
this.baseModelName = null
this.columnMetadata = []
this.resultsTableColumnMetadata = []
this.commonSqlConditions = {
having: [],
where: []
}
this.commonSqlParts = {
fromAndJoins: '',
where: '',
having: ''
}
this.resultsTableCount = 1
this.resultsTableSqlParts = {
select: '',
group: '',
sort: '',
limit: 25,
offset: 0
}
this.finalResults = []
this.graphResponse = null
this.response = null
}
setJoinsAndColumnMetadata () {
// input params
const { columns, filter } = this.params
// are we requesting any data?
if (!columns) {
throw new Error('No columns selected')
}
// the model we're requesting must exist
this.baseModelName = columns[0].split('.')[0]
if (!this.structure[this.baseModelName]) {
throw new Error(`Base model "${this.baseModelName}" not found`)
}
// get all the columns we must be able to access (results table + filter)
const filterColumns = uniq(filter.map(v => v.key))
const columnsToJoin = uniq(columns.concat(filterColumns))
// each requested column must be for this model
if (columnsToJoin.filter(s => s.split('.')[0] !== this.baseModelName).count > 0) {
throw new Error('Each column must be from the same base model!')
}
// counters for value and table aliases
let tableCounter = 0
let valueCounter = 0
// add the base model's path to the "join list"
const baseTableName = this.structure[this.baseModelName]['table_name']
const baseTableAlias = `$T${tableCounter}` // "$T0"
let joins = {
[this.baseModelName]: {
alias: baseTableAlias,
sql: this.adapter.fromTableAs(baseTableName, baseTableAlias) // "FROM baseTableName AS baseTableAlias"
}
}
// make sure we have access to each of the columns we need
columnsToJoin.forEach(column => {
// each incoming column is in the format "path!transform!aggregate"
// e.g. "Order.order_lines.created_at!month!max"
const [ path, transform, aggregate ] = column.replace('$', '!').split('!', 3)
// we will split the path by "." and follow the links going forward, adding joins when needed
// always starting the traverse from the base model
let node = this.structure[this.baseModelName]
let tableAlias = baseTableAlias
// log of how far we have gotten. empty at first
let traversedPath = [this.baseModelName]
// remove the modal from the path, so "Order.order_lines.created_at" -> "order_lines.created_at"
let localPath = path.split('.')
localPath.shift()
localPath.forEach(key => {
// if the next part of the key is a column, deal with it
// (alternatively, if it's a link to a model, and we'll deal with it below in the "else")
if (node.columns[key] || node.custom[key]) {
let meta = null // from insights.yml
let sql = null // how to access this field
let sqlBeforeTransform = null
// get meta and sql
if (node.columns[key]) {
meta = node.columns[key]
sql = this.adapter.tableAliasWithColumn(tableAlias, key)
} else if (node.custom[key]) {
meta = node.custom[key]
sql = meta.sql
let limit = 0
// replace keys like "${other_column}"
while (true) {
limit += 1
if (limit > 100) {
throw new Error(`Recursive loop when evalutating custom key ${traversedPath.join('.')}.${key}`)
}
const match = sql.match(/\${([^}]+)}/)
if (!match) {
break
}
const toReplace = match[0]
const keyword = match[1]
if (node.columns[keyword]) {
sql = sql.split(toReplace).join(this.adapter.tableAliasWithColumn(tableAlias, keyword))
}
if (node.custom[keyword]) {
sql = sql.split(toReplace).join(`(${node.custom[keyword].sql})`)
}
}
// replace "$$." with the table name
sql = this.adapter.customSqlInTableReplace(sql, tableAlias)
}
// perform date conversion if needed
if (meta.type === 'time') {
sql = this.adapter.convertSqlTimezone(sql)
}
if (transform && (meta.type === 'time' || meta.type === 'date')) {
sqlBeforeTransform = sql
sql = this.adapter.truncateDate(sql, transform)
}
// add aggregation functions (count(...), etc)
if (aggregate) {
sql = this.adapter.addAggregation(sql, aggregate)
}
const metadatumObject = {
column: column,
path: path,
table: tableAlias,
key: key,
sql: sql,
sqlBeforeTransform: sqlBeforeTransform,
alias: `$V${valueCounter}`,
type: meta.type.replace(/^:/, ''),
url: meta.url,
model: node.model,
transform: transform,
aggregate: aggregate || null,
index: meta.index
}
this.columnMetadata.push(metadatumObject)
// is this a column that is present in the results table?
if (columns.includes(column)) {
this.resultsTableColumnMetadata.push(metadatumObject)
}
valueCounter += 1
// the current traversed node is a link to a new model (foreign key)
} else if (node.links[key]) {
// details of the link
const linkMeta = node.links[key]
// remember the node's table's alias for the join
let lastTableAlias = tableAlias
// take the next node
node = this.structure[linkMeta['model']]
// add this to the traversed path
traversedPath.push(key)
// if we already joined this table, reuse the old name
if (joins[traversedPath.join('.')]) {
tableAlias = joins[traversedPath.join('.')].alias
// otherwise add it to the joins list
} else {
tableCounter += 1
tableAlias = `$T${tableCounter}`
joins[traversedPath.join('.')] = {
alias: tableAlias,
sql: this.adapter.leftJoin(node['table_name'], tableAlias, linkMeta['model_key'], lastTableAlias, linkMeta['my_key'])
}
}
}
})
})
// save the table "from ... join ... join ..." sql
this.commonSqlParts.fromAndJoins = this.adapter.connectFromAndJoinsArray(Object.values(joins).map(v => v.sql))
}
setFilter () {
const { filter } = this.params
if (!filter) {
return
}
let whereConditions = []
let havingConditions = []
filter.forEach(filterObject => {
const column = filterObject.key
const condition = filterObject.value
const meta = this.columnMetadata.filter(v => v.column === column)[0]
if (!meta) {
return
}
let conditions = []
if (condition === 'null') {
conditions.push(this.adapter.filterEmpty(meta.sql, meta.type))
} else if (condition === 'not null') {
conditions.push(this.adapter.filterPresent(meta.sql, meta.type))
} else if (condition.indexOf('in:') === 0) {
conditions.push(this.adapter.filterIn(meta.sql, condition.substring(3)))
} else if (condition.indexOf('not_in:') === 0) {
conditions.push(this.adapter.filterNotIn(meta.sql, condition.substring(7)))
} else if (meta.type === 'boolean' && condition === 'true') {
conditions.push(this.adapter.filterEquals(meta.sql, meta.type, 'true'))
} else if (meta.type === 'boolean' && condition === 'false') {
conditions.push(this.adapter.filterEquals(meta.sql, meta.type, 'false'))
} else if (condition === 'equals') {
conditions.push(this.adapter.filterEquals(meta.sql, meta.type, ''))
} else if (condition.indexOf('equals:') === 0) {
conditions.push(this.adapter.filterEquals(meta.sql, meta.type, condition.substring(7)))
} else if (condition.indexOf('contains:') === 0) {
conditions.push(this.adapter.filterContains(meta.sql, condition.substring(9)))
} else if (condition.indexOf('between:') === 0) {
conditions = conditions.concat(this.adapter.filterBetween(meta.sql, condition.substring(8)))
} else if (condition.indexOf('date_range:') === 0) {
conditions = conditions.concat(this.adapter.filterDateRange(meta.sql, condition.substring(11)))
}
if (meta.aggregate) {
havingConditions = havingConditions.concat(conditions)
} else {
whereConditions = whereConditions.concat(conditions)
}
})
this.commonSqlConditions.where = whereConditions
this.commonSqlConditions.having = havingConditions
if (whereConditions.length > 0) {
this.commonSqlParts.where = this.adapter.where(whereConditions)
}
if (havingConditions.length > 0) {
this.commonSqlParts.having = this.adapter.having(havingConditions)
}
}
setGroup () {
const aggregateColumns = this.resultsTableColumnMetadata.filter(v => v.aggregate)
if (aggregateColumns.length === 0) {
return
}
const groupParts = this.resultsTableColumnMetadata.filter(v => !v.aggregate).map(v => v.sql)
if (groupParts.length === 0) {
return
}
this.resultsTableSqlParts.group = this.adapter.groupBy(groupParts)
}
setSort () {
let sortColumn = this.params.sort
let sortDescending = false
if (sortColumn && sortColumn.indexOf('-') === 0) {
sortColumn = sortColumn.substring(1)
sortDescending = true
}
let sortParts = []
// add the requested sort column into sortParts, if it's something we have access to
if (sortColumn) {
const sortValue = this.columnMetadata.filter(v => v.column === sortColumn)[0]
if (sortValue && sortValue.sql) {
sortParts.push(this.adapter.orderPart(sortValue.sql, sortDescending))
}
}
// also add the primary key of the base model to the list, to keep the results table stable
// otherwise when scrolling things can shift around annoyingly
const baseTableAlias = '$T0' // hardcoded for now
const firstPrimary = (Object.entries(this.structure[this.baseModelName]['columns']).filter(([k, v]) => v['index'] === 'primary_key')[0] || [])[0]
const noAggregate = this.columnMetadata.filter(v => v.aggregate).length === 0
if (firstPrimary && noAggregate) {
const columnSql = this.adapter.tableAliasWithColumn(baseTableAlias, firstPrimary)
sortParts.push(this.adapter.orderPart(columnSql, false))
}
if (sortParts.length === 0) {
return
}
this.resultsTableSqlParts.sort = this.adapter.orderBy(sortParts)
}
setLimit () {
this.resultsTableSqlParts.offset = this.params.offset || 0
this.resultsTableSqlParts.limit = this.params.limit || 25
if (this.params.export === 'xlsx') {
this.resultsTableSqlParts.offset = 0
this.resultsTableSqlParts.limit = 65535
}
}
async getCount () {
const nonAggregateColumns = this.columnMetadata.filter(v => !v.aggregate)
if (nonAggregateColumns.length === 0) {
return
}
this.resultsTableCount = await this.adapter.getCount({
fromAndJoins: this.commonSqlParts.fromAndJoins,
where: this.commonSqlParts.where,
having: this.commonSqlParts.having,
group: this.resultsTableSqlParts.group
})
}
async getResults () {
// set what to select
this.resultsTableSqlParts.select = this.adapter.valueListToSelect(this.resultsTableColumnMetadata)
// get the results from the database
const results = await this.adapter.getResults(Object.assign({}, this.commonSqlParts, this.resultsTableSqlParts))
// get the keys used in the results
const columnAliases = this.resultsTableColumnMetadata.map(v => v.alias)
// convert to an array
this.finalResults = results.map(row => columnAliases.map(a => row[a]))
}
async getGraph () {
const graphTimeFilter = this.params.graphTimeFilter || 'last-60'
const { cumulative, prediction } = this.params.graphControls
const facetsCount = this.params.facetsCount || 6
const facetsColumnKey = this.params.facetsColumn
// see what we have to work with
let timeColumns = this.resultsTableColumnMetadata.filter(v => (v.type === 'time' || v.type === 'date') && !v.aggregate)
const aggregateColumns = this.resultsTableColumnMetadata.filter(v => v.aggregate)
// must have at least 1 aggregate and exactly 1 time column
if (aggregateColumns.length < 1 || timeColumns.length !== 1) {
return
}
// day? week? month?
const timeGroup: TruncationType = timeColumns[0].transform || 'day'
const compareWith = this.params.graphControls.compareWith || 0
// start and end of the graph timeline (or nil)
let [firstDate, lastDate] = getTimesFromString(graphTimeFilter, 0, timeGroup)
let compareWithFirstDate
let compareWithLastDate
if (compareWith && firstDate && lastDate) {
compareWithFirstDate = moment(firstDate).subtract(compareWith, timeGroup).startOf(timeGroup).format('YYYY-MM-DD')
compareWithLastDate = moment(lastDate).subtract(compareWith, timeGroup).endOf(timeGroup).format('YYYY-MM-DD')
}
let predictionFirstDate
let predictionLastDate
const rightNow = new Date()
// prediction enabled and we are showing the last month of the time period
if (compareWith && prediction && moment(lastDate).startOf(timeGroup).isBefore(rightNow) && moment(lastDate).endOf(timeGroup).isAfter(rightNow)) {
const startOf = moment(rightNow).startOf(timeGroup).valueOf()
const endOf = moment(rightNow).endOf(timeGroup).valueOf()
const current = moment(rightNow).valueOf()
const percentage = (current - startOf) / (endOf - startOf)
const predictionStart = moment(compareWithLastDate).startOf(timeGroup).valueOf()
const predictionEnd = moment(compareWithLastDate).endOf(timeGroup).valueOf()
const predictionCurrent = moment(percentage * (predictionEnd - predictionStart) + predictionStart)
predictionFirstDate = moment(predictionStart).format('YYYY-MM-DD')
predictionLastDate = moment(predictionCurrent).format('YYYY-MM-DD')
}
// add the date truncation transform to the columns if none present
timeColumns = timeColumns.map(v => (
Object.assign({}, v, { transform: timeGroup, sql: this.adapter.truncateDate(v.sqlBeforeTransform || v.sql, timeGroup) })
))
const timeColumn = timeColumns[0]
// sort by time
const graphSortParts = [this.adapter.orderPart(timeColumn.sql, false)]
const graphSortSql = this.adapter.orderBy(graphSortParts)
// limit the results to what's visible on the graph
let graphWhereConditions = this.commonSqlConditions.where.slice(0)
if (firstDate && lastDate) {
graphWhereConditions = graphWhereConditions.concat(this.adapter.filterDateRange(timeColumn.sql, `${firstDate}:${lastDate}`))
}
const graphWhereSql = this.adapter.where(graphWhereConditions)
let compareWithWhereSql
if (compareWith) {
let compareWithWhereConditions = this.commonSqlConditions.where.slice(0)
if (compareWithFirstDate && compareWithLastDate) {
compareWithWhereConditions = compareWithWhereConditions.concat(this.adapter.filterDateRange(timeColumn.sql, `${compareWithFirstDate}:${compareWithLastDate}`))
}
compareWithWhereSql = this.adapter.where(compareWithWhereConditions)
}
let predictionWhereSql
if (predictionFirstDate && predictionLastDate) {
let predictionWhereConditions = this.commonSqlConditions.where.slice(0)
if (predictionFirstDate && predictionLastDate) {
predictionWhereConditions = predictionWhereConditions.concat(this.adapter.filterDateRange(timeColumn.sql, `${predictionFirstDate}:${predictionLastDate}`))
}
predictionWhereSql = this.adapter.where(predictionWhereConditions)
}
// facets column
let facetsColumn = null
let facetsColumns = []
if (facetsColumnKey) {
facetsColumns = this.resultsTableColumnMetadata
.filter(v => ['string', 'boolean'].includes(v.type) && !v.aggregate && v.column === facetsColumnKey)
.slice(0, 1)
facetsColumn = facetsColumns[0]
}
let facetValues = []
// grouping
let graphGroupParts = timeColumns.concat(aggregateColumns).concat(facetsColumns).filter(v => !v.aggregate).map(v => v.sql)
let graphGroupSql = this.adapter.groupBy(graphGroupParts)
// if we're faceting, see if we need to limit the facets
if (facetsColumn) {
const { values: facetValuesInner, hasOther } = await this.adapter.getFacetValuesAndHasOther({
column: facetsColumn.sql,
fromAndJoins: this.commonSqlParts.fromAndJoins,
where: graphWhereSql,
group: graphGroupSql,
having: this.commonSqlParts.having,
limit: facetsCount
})
facetValues = facetValuesInner
// there are no values in the column, remove the facets
if (!facetValues || facetValues.length === 0) {
facetsColumn = null
facetsColumns = []
// there are values. do we have all of them, or must we add an "other"?
} else if (facetsColumn.type === 'string' && hasOther) {
const facetOther = facetValues.includes('Other') ? '__OTHER__' : 'Other'
facetsColumn = Object.assign({}, facetsColumn, {
sql: this.adapter.facetedValuesOrOther(facetsColumn.sql, facetValues, facetOther)
})
facetsColumns = [facetsColumn]
facetValues.push(facetOther)
}
}
// regroup in case something changed
graphGroupParts = timeColumns.concat(aggregateColumns).concat(facetsColumns).filter(v => !v.aggregate).map(v => v.sql)
graphGroupSql = this.adapter.groupBy(graphGroupParts)
// graph results
const graphSelectValues = timeColumns.concat(aggregateColumns).concat(facetsColumns)
const graphSelectSql = this.adapter.valueListToSelect(graphSelectValues)
// raw results from sql
const graphResults = await this.adapter.getResults({
select: graphSelectSql,
fromAndJoins: this.commonSqlParts.fromAndJoins,
where: graphWhereSql,
group: graphGroupSql,
having: this.commonSqlParts.having,
sort: graphSortSql,
limit: 10000,
offset: 0
})
let compareWithHash = {}
if (compareWith) {
const compareWithResults = await this.adapter.getResults({
select: graphSelectSql,
fromAndJoins: this.commonSqlParts.fromAndJoins,
where: compareWithWhereSql,
group: graphGroupSql,
having: this.commonSqlParts.having,
sort: graphSortSql,
limit: 10000,
offset: 0
})
compareWithResults.forEach(result => {
// TODO: should we do someting special with columns that have no date?
if (!result[timeColumn.alias]) {
return
}
let date = moment(result[timeColumn.alias]).format('YYYY-MM-DD')
if (!compareWithHash[date]) {
compareWithHash[date] = {}
}
aggregateColumns.forEach(aggregateColumn => {
let key = `compareWith::${aggregateColumn.column}`
facetsColumns.forEach(column => {
key += `$$${result[column.alias]}`
})
compareWithHash[date][key] = result[aggregateColumn.alias]
})
})
if (predictionWhereSql) {
const predictionResults = await this.adapter.getResults({
select: graphSelectSql,
fromAndJoins: this.commonSqlParts.fromAndJoins,
where: predictionWhereSql,
group: graphGroupSql,
having: this.commonSqlParts.having,
sort: graphSortSql,
limit: 10000,
offset: 0
})
predictionResults.forEach(result => {
if (!result[timeColumn.alias]) {
return
}
let date = moment(result[timeColumn.alias]).format('YYYY-MM-DD')
if (!compareWithHash[date]) {
compareWithHash[date] = {}
}
aggregateColumns.forEach(aggregateColumn => {
compareWithHash[date]['__hasCompareWithPartial'] = true
let key = `compareWithPartial::${aggregateColumn.column}`
facetsColumns.forEach(column => {
key += `$$${result[column.alias]}`
})
compareWithHash[date][key] = result[aggregateColumn.alias]
})
})
}
}
// save the results in a hash with dates as keys... and all aggregate columns with facets as values
let resultHash = {}
graphResults.forEach(result => {
// TODO: should we do someting special with columns that have no date?
if (!result[timeColumn.alias]) {
return
}
let date = moment(result[timeColumn.alias]).format('YYYY-MM-DD')
if (!resultHash[date]) {
resultHash[date] = { time: date }
}
aggregateColumns.forEach(aggregateColumn => {
let key = aggregateColumn.column
facetsColumns.forEach(column => {
key += `$$${result[column.alias]}`
})
resultHash[date][key] = result[aggregateColumn.alias]
})
})
// each hash in the resultHash should have allKeys set
let allKeys = []
aggregateColumns.forEach(aggregateColumn => {
const { column } = aggregateColumn
if (facetValues.length > 0) {
facetValues.forEach(v => {
allKeys.push(`${column}$$${v}`)
})
} else {
allKeys.push(column)
}
})
// get the first and last dates if not already set
if (!firstDate || !lastDate) {
const allDateKeys = Object.keys(resultHash).sort()
if (!firstDate) {
firstDate = allDateKeys[0]
}
if (!lastDate) {
lastDate = allDateKeys[allDateKeys.length - 1]
}
}
// calculate all the dates that should be in the results
let allDates = []
if (firstDate && lastDate) {
let lastTime = moment(lastDate)
for (let date = moment(firstDate); date <= lastTime; date = date.add(1, 'day')) {
// could be optimised... but whatever, it's not going to be a huge loop
if (timeGroup === 'year' && (date.date() !== 1 || date.month() !== 0)) {
continue
}
if (timeGroup === 'quarter' && !(date.date() === 1 && [0, 3, 6, 9].includes(date.month()))) {
continue
}
if (timeGroup === 'month' && date.date() !== 1) {
continue
}
if (timeGroup === 'week' && date.weekday() !== 1) {
continue
}
allDates.push(date.format('YYYY-MM-DD'))
}
}
// make sure all the dates have all the values present (as 0 if nil)
if (allDates.length > 0) {
let emptyHash = {}
allKeys.forEach(key => {
emptyHash[key] = 0
})
allDates.forEach(date => {
resultHash[date] = Object.assign({ time: date }, emptyHash, resultHash[date] || {})
})
}
if (compareWith) {
Object.keys(resultHash).forEach(date => {
const compareWithDate = moment(date).subtract(compareWith, timeGroup).format('YYYY-MM-DD')
const compareWithResult = compareWithHash[compareWithDate]
if (compareWithResult) {
resultHash[date] = Object.assign({}, resultHash[date], compareWithResult)
}
})
}
// if we're asking for a cumulative response, sum all the values
if (cumulative) {
let countHash = {}
allKeys.forEach(key => {
countHash[key] = 0
if (compareWith) {
const compareWithKey = `compareWith::${key}`
countHash[compareWithKey] = 0
}
})
allDates.forEach(date => {
allKeys.forEach(key => {
countHash[key] += parseFloat(resultHash[date][key]) || 0
resultHash[date][key] = countHash[key]
if (compareWith) {
const compareWithKey = `compareWith::${key}`
countHash[compareWithKey] += parseFloat(resultHash[date][compareWithKey]) || 0
resultHash[date][compareWithKey] = countHash[compareWithKey]
}
})
})
}
this.graphResponse = {
meta: graphSelectValues.map(values => {
const { column, path, type, url, key, model, aggregate, transform, index } = values
return { column, path, type, url, key, model, aggregate, transform, index }
}),
keys: allKeys,
facets: facetValues,
results: Object.keys(resultHash).sort().map(key => resultHash[key]),
timeGroup: timeGroup
}
}
setResponse () {
let columnsMeta = {}
this.columnMetadata.forEach(values => {
const { column, path, type, url, key, model, aggregate, transform, index } = values
columnsMeta[column] = { column, path, type, url, key, model, aggregate, transform, index }
})
this.response = {
success: true,
columns: this.resultsTableColumnMetadata.map(v => v.column),
columnsMeta: columnsMeta,
results: this.finalResults,
count: this.resultsTableCount,
offset: this.resultsTableSqlParts.offset,
limit: this.resultsTableSqlParts.limit,
sort: this.params.sort,
filter: this.params.filter,
graph: this.graphResponse,
facetsColumn: this.params.facetsColumn || null,
facetsCount: this.params.facetsCount,
graphTimeFilter: this.params.graphTimeFilter || 'last-60',
graphControls: this.params.graphControls
}
}
}
// convert 'last-365', etc to start and end dates
function getTimesFromString (timeFilter, smooth = 0, timeGroup = 'day') {
let firstDate
let lastDate
if (timeFilter.match(/^20[0-9][0-9]$/)) {
const year = parseInt(timeFilter)
firstDate = moment(`${year}-01-01`).add(-smooth, 'days')
lastDate = moment(`${year + 1}-01-01`).add(-1, 'day')
} else if (timeFilter === 'this-month-so-far') {
firstDate = moment().startOf('month')
lastDate = moment()
} else if (timeFilter === 'today') {
firstDate = moment()
lastDate = moment()
} else if (timeFilter === 'yesterday') {
firstDate = moment().add(-1, 'day')
lastDate = moment().add(-1, 'day')
} else if (timeFilter === 'this-month') {
firstDate = moment().startOf('month')
lastDate = moment().endOf('month')
} else if (timeFilter === 'last-month') {
firstDate = moment().startOf('month').add(-1, 'month')
lastDate = moment(firstDate).endOf('month')
} else if (timeFilter.match(/^last-([0-9]+)$/)) {
let dayCount = parseInt(timeFilter.split('last-')[1]) + smooth
firstDate = moment().add(-dayCount, 'days')
if (timeGroup === 'month') {
firstDate = moment(firstDate).startOf('month')
} else if (timeGroup === 'week') {
const wday = firstDate.day()
firstDate = moment(firstDate).add(-(wday === 0 ? 6 : wday - 1), 'days')
}
lastDate = moment()
} else if (timeFilter.match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}-to-[0-9]{4}-[0-9]{2}-[0-9]{2}$/)) {
const parts = timeFilter.split('-to-').map(t => moment(t))
firstDate = parts[0]
lastDate = parts[1]
}
if (!firstDate || !lastDate) {
return []
}
return [firstDate.format('YYYY-MM-DD'), lastDate.format('YYYY-MM-DD')]
}
function uniq (array) {
let tracker = {}
return array.filter(a => {
const notFound = !tracker[a]
tracker[a] = true
return notFound
})
} | the_stack |
import * as R from "ramda";
import { exit } from "../../lib/process";
import { Argv } from "yargs";
import { BaseArgs } from "../../types";
import {
authz,
graphTypes,
getEnvironmentsByEnvParentId,
getEnvironmentName,
getSubEnvironmentsByParentEnvironmentId,
} from "@core/lib/graph";
import { initCore, dispatch, getState } from "../../lib/core";
import {
parseKeyValuePairs,
getShowEnvs,
fetchEnvsIfNeeded,
findEnvironment,
} from "../../lib/envs";
import { confirmPendingConflicts } from "../../lib/conflicts";
import { parseMultiFormat } from "@core/lib/parse";
import { Model, Client } from "@core/types";
import { hasPendingConflicts } from "@core/lib/client";
import { getPending } from "../../lib/envs";
import chalk from "chalk";
import { spinnerWithText, stopSpinner } from "../../lib/spinner";
import {
findCliUser,
findUser,
getEnvironmentChoices,
logAndExitIfActionFailed,
} from "../../lib/args";
import { autoModeOut, getPrompt, isAutoMode } from "../../lib/console_io";
import {
argIsEnvironment,
tryApplyDetectedAppOverride,
} from "../../app_detection";
export const command = "set [app-or-block] [environment] [kv-pairs...]";
export const desc = "Add, edit, or delete environment variables.";
export const builder = (yargs: Argv<BaseArgs>) =>
yargs
.positional("app-or-block", { type: "string" })
.positional("environment", { type: "string" })
.positional("kv-pairs", {
type: "string",
describe: 'Accepts KEY=val or json (\'{"KEY": "val"}\')',
})
.array("kv-pairs")
.option("empty", {
type: "string",
describe: "Set a variable to empty",
})
.option("remove", {
type: "string",
describe: "Delete a variable from the environment",
})
.option("branch", {
type: "string",
alias: "b",
coerce: R.toLower,
})
.option("local-override", {
type: "boolean",
alias: ["l", "local-overrides"],
describe: "Set this key as a local override for the current user",
})
.option("override-user", {
type: "string",
alias: ["u", "override-for-user", "overrides-for-user"],
describe:
"Set this key as a local override for another user by email or id",
conflicts: ["local-override"],
coerce: (value) => {
if (!value) {
throw new Error("Missing user override");
}
return value;
},
})
.option("commit", {
type: "boolean",
alias: "c",
describe: "Commit this change immediately",
})
.option("message", {
type: "string",
alias: "m",
implies: "commit",
describe: "Add a commit message",
});
export const handler = async (
argv: BaseArgs & {
"app-or-block"?: string;
environment?: string;
branch?: string;
"kv-pairs"?: string[];
empty?: string;
remove?: string;
"local-override"?: boolean;
"override-user"?: string;
commit?: boolean;
message?: string;
}
): Promise<void> => {
const prompt = getPrompt();
let { state, auth } = await initCore(argv, true);
let envParent: Model.EnvParent | undefined,
environment: Model.Environment | undefined,
environmentChoiceIds: string[] | undefined,
envIdOrUserOverride: string,
arg1Type: "envParent" | "environment" | undefined,
arg2Type: "environment" | undefined,
localOverrideForUserId: string | undefined;
const { apps, blocks } = graphTypes(state.graph),
envParents = [...apps, ...blocks],
envParentsByName = R.indexBy(R.pipe(R.prop("name"), R.toLower), envParents),
envParentsById = R.indexBy(R.pipe(R.prop("id"), R.toLower), envParents);
if (!envParents.length) {
return exit(
1,
chalk.red.bold("Create an app before setting config values.")
);
}
if (argv["app-or-block"]) {
envParent =
envParentsByName[argv["app-or-block"].toLowerCase()] ??
envParentsById[argv["app-or-block"].toLowerCase()];
if (envParent) {
arg1Type = "envParent";
}
}
if (!envParent) {
if (tryApplyDetectedAppOverride(auth.userId, argv)) {
return handler(argv);
}
const appId = argv["detectedApp"]?.appId?.toLowerCase();
if (appId) {
const otherArgsValid =
!argv["app-or-block"] ||
argv["app-or-block"].includes("=") ||
argIsEnvironment(state.graph, appId, argv["app-or-block"]);
if (otherArgsValid) {
envParent = envParentsByName[appId] ?? envParentsById[appId];
if (envParent) {
console.log("Detected app", chalk.bold(envParent.name), "\n");
}
}
}
}
if (!envParent) {
// determine if there's a default app
// if app not found via arg or default, prompt for it
const { name } = await prompt<{ name: string }>({
type: "autocomplete",
name: "name",
message:
"Choose an " +
chalk.bold("app") +
" or " +
chalk.bold("block") +
" (type to search):",
initial: 0,
choices: envParents.map((envParent) => ({
name: envParent.name,
message: chalk.bold(envParent.name),
})),
});
envParent = envParentsByName[name.toLowerCase()];
}
const environmentsByName = R.groupBy(
(e) => getEnvironmentName(state.graph, e.id).toLowerCase(),
getEnvironmentsByEnvParentId(state.graph)[envParent.id] ?? []
);
if (argv["environment"]) {
const name = argv["environment"];
const environments = environmentsByName[name.toLowerCase()] ?? [];
if (environments.length == 1) {
environment = environments[0];
} else if (environments.length > 1) {
environmentChoiceIds = environments.map(R.prop("id"));
}
if (environment) {
arg2Type = "environment";
}
}
if (!environment && argv["app-or-block"] && !arg1Type) {
const name = argv["app-or-block"];
const environments = environmentsByName[name.toLowerCase()] ?? [];
if (environments.length == 1) {
environment = environments[0];
} else if (environments.length > 1) {
environmentChoiceIds = environments.map(R.prop("id"));
}
if (environment) {
arg1Type = "environment";
}
}
if (argv["branch"]) {
const name = argv["branch"];
if (environment) {
const subEnvironmentsByName = R.indexBy(
(sub) => (sub.isSub ? sub.subName.toLowerCase() : ""),
getSubEnvironmentsByParentEnvironmentId(state.graph)[environment.id] ??
[]
);
environment = subEnvironmentsByName[name.toLowerCase()];
} else {
const environments = environmentsByName[name.toLowerCase()] ?? [];
if (environments.length == 1) {
environment = environments[0];
} else if (environments.length > 1) {
environmentChoiceIds = environments.map(R.prop("id"));
}
}
}
if (argv["local-override"]) {
localOverrideForUserId = auth.userId;
} else if (argv["override-user"]) {
const otherUser =
findUser(state.graph, argv["override-user"]) ||
findCliUser(state.graph, argv["override-user"]);
if (!otherUser) {
return exit(1, chalk.red.bold("User not found for override."));
}
localOverrideForUserId = otherUser.id;
if (
!authz.canUpdateLocals(
state.graph,
auth.userId,
envParent.id,
localOverrideForUserId!
)
) {
return exit(
1,
chalk.red.bold(
"You don't have permission to change the environment for that user."
)
);
}
} else {
// traditional environment
if (!environment) {
if (argv["detectedApp"]) {
environment = findEnvironment(
state.graph,
envParent.id,
argv["detectedApp"].environmentId ?? "development"
);
}
}
if (!environment) {
const { name } = await prompt<{ name: string }>({
type: "autocomplete",
name: "name",
message:
"Choose an " + chalk.bold("environment") + " (type to search):",
initial: 0,
choices: getEnvironmentChoices(
state.graph,
auth.userId,
envParent.id,
undefined,
environmentChoiceIds
),
});
environment = findEnvironment(state.graph, envParent.id, name);
}
if (!environment) {
return exit(
1,
chalk.red("Environment is not found, or you don't have access.")
);
}
}
let kvArgs: string[] = [];
if (argv["kv-pairs"]) {
kvArgs = kvArgs.concat(argv["kv-pairs"]);
}
if (argv["app-or-block"] && !arg1Type) {
kvArgs.push(argv["app-or-block"]);
}
if (argv["environment"] && !arg2Type) {
kvArgs.push(argv["environment"]);
}
if (kvArgs.length == 0 && !(argv["empty"] || argv["remove"])) {
const { kvString } = await prompt<{ kvString: string }>({
type: "input",
name: "kvString",
message: "Set variables in " + chalk.bold("KEY=val") + " format",
validate: (s: string) =>
s && s.trim() && parseMultiFormat(s, ["env"]) ? true : "Invalid input",
});
kvArgs.push(kvString);
}
const kv = parseKeyValuePairs(kvArgs);
if (argv["empty"]) {
kv[argv["empty"]] = "";
}
if (argv["remove"]) {
// Special case of setting key to undefined - better than modifying the type of RawEnv and losing safety elsewhere
// @ts-ignore
kv[argv["remove"]] = undefined;
}
state = await fetchEnvsIfNeeded(state, [envParent.id]);
envIdOrUserOverride = localOverrideForUserId
? [envParent.id, localOverrideForUserId].join("|")
: environment!.id; // wont be undefined when localOverrideForUserId is set
if (
!authz.canUpdateLocals(
state.graph,
auth.userId,
envParent.id,
envIdOrUserOverride
)
) {
return exit(
1,
chalk.red.bold(
`You don't have permission to modify the environment ${chalk.bold(
envIdOrUserOverride
)}.`
)
);
}
for (let k of Object.keys(kv)) {
let val: string | undefined = kv[k];
let inheritsEnvironmentId: string | undefined;
if (val?.toLowerCase().startsWith("inherits:")) {
const inheritsName = val?.split("inherits:")[1];
if (inheritsName in environmentsByName) {
const [inheritsEnvironment] =
environmentsByName[inheritsName.toLowerCase()];
if (inheritsEnvironment && !inheritsEnvironment.isSub) {
inheritsEnvironmentId = inheritsEnvironment.id;
val = undefined;
}
}
}
await dispatch({
type: Client.ActionType.UPDATE_ENTRY_VAL,
payload: {
envParentId: envParent.id,
environmentId: envIdOrUserOverride,
entryKey: k,
update: {
val,
inheritsEnvironmentId,
isEmpty: val === "" ? true : undefined,
isUndefined:
typeof val === "undefined" && !inheritsEnvironmentId
? true
: undefined,
} as any,
},
});
}
if (environment?.id) {
console.log(
"Environment:",
getEnvironmentName(state.graph, environment.id)
);
}
state = getState();
if (argv.commit) {
const [summary, pending] = getPending(state);
if (pending) {
console.log(summary);
console.log("");
console.log(pending);
console.log("");
if (!isAutoMode()) {
if (hasPendingConflicts(state, [envParent.id], [envIdOrUserOverride])) {
await confirmPendingConflicts(
state,
[envParent.id],
[envIdOrUserOverride]
);
} else {
const { confirm } = await prompt<{ confirm: boolean }>({
type: "confirm",
name: "confirm",
message: chalk.bold(`Commit all changes?`),
});
if (!confirm) {
return exit();
}
}
}
}
spinnerWithText("Encrypting and syncing...");
const res = await dispatch({
type: Client.ActionType.COMMIT_ENVS,
payload: { message: argv.message },
});
stopSpinner();
await logAndExitIfActionFailed(res, "Your changes failed to commit.");
state = res.state;
console.log(chalk.green("The changes have been committed."));
const [output] = getShowEnvs(
state,
envParent.id,
[envIdOrUserOverride],
new Set(Object.keys(kv))
);
console.log(output, "\n");
} else {
const [filteredSummary, filteredPending] = getPending(state, {
envParentIds: new Set([envParent.id]),
environmentIds: new Set([envIdOrUserOverride]),
entryKeys: new Set(Object.keys(kv)),
}),
[allSummary, allPending] = getPending(state);
if (filteredPending) {
console.log(
chalk.green.bold("Your changes are pending:"),
"\n" + filteredSummary,
"\n" + filteredPending
);
} else {
console.log(chalk.bold("No values were updated."), "\n" + allSummary);
}
if (filteredPending != allPending) {
console.log(
chalk.bold.cyan("\nAdditional changes are pending."),
"Use",
chalk.bold("envkey pending"),
"to see them all, and",
chalk.bold("envkey commit"),
"or",
chalk.bold("envkey reset"),
"to selectively commit or cancel.\n"
);
} else {
console.log(
"\nUse",
chalk.bold("envkey commit"),
"or",
chalk.bold("envkey reset"),
"to selectively commit or cancel.\n"
);
}
}
const [, , diffsByEnvironmentId] = getPending(state);
autoModeOut({
envParentId: envParent.id,
pendingEnvs: Object.keys(diffsByEnvironmentId).length
? diffsByEnvironmentId
: null,
});
// need to manually exit process since yargs doesn't properly wait for async handlers
return exit();
}; | the_stack |
'use strict';
import * as vscode from 'vscode';
import { LanguageClient, NotificationType, Range } from 'vscode-languageclient';
import { Location, WorkspaceEdit } from './commonTypes';
import { makeVscodeRange, makeVscodeLocation, makeVscodeTextEdits, rangeEquals } from './utils';
import {LocalizeStringParams, getLocalizedString } from './localization';
import { CppSourceStr } from './extension';
import { CppSettings } from './settings';
import * as nls from 'vscode-nls';
nls.config({ messageFormat: nls.MessageFormat.bundle, bundleFormat: nls.BundleFormat.standalone })();
const localize: nls.LocalizeFunc = nls.loadMessageBundle();
let diagnosticsCollectionCodeAnalysis: vscode.DiagnosticCollection;
export function RegisterCodeAnalysisNotifications(languageClient: LanguageClient): void {
languageClient.onNotification(PublishCodeAnalysisDiagnosticsNotification, publishCodeAnalysisDiagnostics);
languageClient.onNotification(PublishRemoveCodeAnalysisCodeActionFixesNotification, publishRemoveCodeAnalysisCodeActionFixes);
}
export interface CodeActionDiagnosticInfo {
version: number; // Needed due to https://github.com/microsoft/vscode/issues/148723 .
// Used to work around https://github.com/microsoft/vscode/issues/126393.
// If that bug were fixed, then we could use the vscode.CodeAction.diagnostic directly.
range: vscode.Range;
code: string;
fixCodeAction?: vscode.CodeAction;
// suppressCodeAction?: vscode.CodeAction; // TODO?
removeCodeAction?: vscode.CodeAction;
}
// Used to handle fix invalidation after an edit,
// i.e. it's set to undefined if it becomes invalid.
interface CodeActionWorkspaceEdit {
workspaceEdit?: vscode.WorkspaceEdit;
}
interface CodeActionPerUriInfo {
// These two arrays have the same length, i.e. index i of identifiers
// is used to index into workspaceEdits to get the corresponding edit.
identifiers: CodeAnalysisDiagnosticIdentifier[];
workspaceEdits?: CodeActionWorkspaceEdit[];
// Used to quickly determine how many non-undefined entries are in "workspaceEdits"
// (so the array doesn't have to be iterated through).
numValidWorkspaceEdits: number;
}
// Tracks the "type" code actions (i.e. "code" is a synonym for "type" in this context).
export interface CodeActionCodeInfo {
version: number; // Needed due to https://github.com/microsoft/vscode/issues/148723 .
// Needed to quickly update the "type" action for a file.
uriToInfo: Map<string, CodeActionPerUriInfo>;
fixAllTypeCodeAction?: vscode.CodeAction;
disableAllTypeCodeAction?: vscode.CodeAction;
removeAllTypeCodeAction?: vscode.CodeAction;
docCodeAction?: vscode.CodeAction;
}
interface CodeActionAllInfo {
version: number; // Needed due to https://github.com/microsoft/vscode/issues/148723 .
fixAllCodeAction: vscode.CodeAction;
removeAllCodeAction: vscode.CodeAction;
}
interface CodeAnalysisDiagnosticRelatedInformation {
location: Location;
message: string;
workspaceEdit?: WorkspaceEdit;
}
interface CodeAnalysisDiagnostic {
range: Range;
code: string;
severity: vscode.DiagnosticSeverity;
localizeStringParams: LocalizeStringParams;
relatedInformation?: CodeAnalysisDiagnosticRelatedInformation[];
workspaceEdit?: WorkspaceEdit;
}
interface CodeAnalysisDiagnosticIdentifier {
range: Range;
code: string;
}
export interface CodeAnalysisDiagnosticIdentifiersAndUri {
uri: string;
identifiers: CodeAnalysisDiagnosticIdentifier[];
}
export interface RemoveCodeAnalysisProblemsParams {
identifiersAndUris: CodeAnalysisDiagnosticIdentifiersAndUri[];
refreshSquigglesOnSave: boolean;
};
interface RemoveCodeAnalysisCodeActionFixesParams {
identifiersAndUris: CodeAnalysisDiagnosticIdentifiersAndUri[];
};
interface PublishCodeAnalysisDiagnosticsParams {
uri: string;
diagnostics: CodeAnalysisDiagnostic[];
}
const PublishCodeAnalysisDiagnosticsNotification: NotificationType<PublishCodeAnalysisDiagnosticsParams, void> = new NotificationType<PublishCodeAnalysisDiagnosticsParams, void>('cpptools/publishCodeAnalysisDiagnostics');
const PublishRemoveCodeAnalysisCodeActionFixesNotification: NotificationType<RemoveCodeAnalysisCodeActionFixesParams, void> = new NotificationType<RemoveCodeAnalysisCodeActionFixesParams, void>('cpptools/publishRemoveCodeAnalysisCodeActionFixes');
export const codeAnalysisFileToCodeActions: Map<string, CodeActionDiagnosticInfo[]> = new Map<string, CodeActionDiagnosticInfo[]>();
export const codeAnalysisCodeToFixes: Map<string, CodeActionCodeInfo> = new Map<string, CodeActionCodeInfo>();
export const codeAnalysisAllFixes: CodeActionAllInfo = {
version: 0,
fixAllCodeAction: {
title: localize("fix_all_code_analysis_problems", "Fix all code analysis problems"),
command: { title: 'FixAllCodeAnalysisProblems', command: 'C_Cpp.FixAllCodeAnalysisProblems',
arguments: [ 0, undefined, true, [] ] },
kind: vscode.CodeActionKind.QuickFix
},
removeAllCodeAction: {
title: localize("clear_all_code_analysis_problems", "Clear all code analysis problems"),
command: { title: "RemoveAllCodeAnalysisProblems", command: "C_Cpp.RemoveAllCodeAnalysisProblems" },
kind: vscode.CodeActionKind.QuickFix
}
};
// Rebuild codeAnalysisCodeToFixes and codeAnalysisAllFixes.fixAllCodeActions.
function rebuildCodeAnalysisCodeAndAllFixes(): void {
if (codeAnalysisAllFixes.fixAllCodeAction.command?.arguments !== undefined) {
codeAnalysisAllFixes.fixAllCodeAction.command.arguments[0] = ++codeAnalysisAllFixes.version;
codeAnalysisAllFixes.fixAllCodeAction.command.arguments[1] = undefined;
codeAnalysisAllFixes.fixAllCodeAction.command.arguments[3] = [];
}
const identifiersAndUrisForAllFixes: CodeAnalysisDiagnosticIdentifiersAndUri[] = [];
const uriToEditsForAll: Map<vscode.Uri, vscode.TextEdit[]> = new Map<vscode.Uri, vscode.TextEdit[]>();
let numFixTypes: number = 0;
for (const codeToFixes of codeAnalysisCodeToFixes) {
const identifiersAndUris: CodeAnalysisDiagnosticIdentifiersAndUri[] = [];
const uriToEdits: Map<vscode.Uri, vscode.TextEdit[]> = new Map<vscode.Uri, vscode.TextEdit[]>();
codeToFixes[1].uriToInfo.forEach((perUriInfo: CodeActionPerUriInfo, uri: string) => {
const newIdentifiersAndUri: CodeAnalysisDiagnosticIdentifiersAndUri = { uri: uri, identifiers: perUriInfo.identifiers };
identifiersAndUris.push(newIdentifiersAndUri);
if (perUriInfo.workspaceEdits === undefined || perUriInfo.numValidWorkspaceEdits === 0) {
return;
}
identifiersAndUrisForAllFixes.push(newIdentifiersAndUri);
for (const edit of perUriInfo.workspaceEdits) {
if (edit.workspaceEdit === undefined) {
continue;
}
for (const [uri, edits] of edit.workspaceEdit.entries()) {
const textEdits: vscode.TextEdit[] = uriToEdits.get(uri) ?? [];
textEdits.push(...edits);
uriToEdits.set(uri, textEdits);
const textEditsForAll: vscode.TextEdit[] = uriToEditsForAll.get(uri) ?? [];
textEditsForAll.push(...edits);
uriToEditsForAll.set(uri, textEdits);
}
}
});
if (uriToEdits.size > 0) {
const allTypeWorkspaceEdit: vscode.WorkspaceEdit = new vscode.WorkspaceEdit();
for (const [uri, edits] of uriToEdits.entries()) {
allTypeWorkspaceEdit.set(uri, edits);
}
++numFixTypes;
codeToFixes[1].fixAllTypeCodeAction = {
title: localize("fix_all_type_problems", "Fix all {0} problems", codeToFixes[0]),
command: { title: 'FixAllTypeCodeAnalysisProblems', command: 'C_Cpp.FixAllTypeCodeAnalysisProblems',
arguments: [ codeToFixes[0], ++codeToFixes[1].version, allTypeWorkspaceEdit, true, identifiersAndUris ] },
kind: vscode.CodeActionKind.QuickFix
};
}
if (new CppSettings().clangTidyCodeActionShowDisable) {
codeToFixes[1].disableAllTypeCodeAction = {
title: localize("disable_all_type_problems", "Disable all {0} problems", codeToFixes[0]),
command: { title: 'DisableAllTypeCodeAnalysisProblems', command: 'C_Cpp.DisableAllTypeCodeAnalysisProblems',
arguments: [ codeToFixes[0], identifiersAndUris ] },
kind: vscode.CodeActionKind.QuickFix
};
} else {
codeToFixes[1].disableAllTypeCodeAction = undefined;
}
if (new CppSettings().clangTidyCodeActionShowClear !== "None") {
codeToFixes[1].removeAllTypeCodeAction = {
title: localize("clear_all_type_problems", "Clear all {0} problems", codeToFixes[0]),
command: { title: 'RemoveAllTypeCodeAnalysisProblems', command: 'C_Cpp.RemoveCodeAnalysisProblems',
arguments: [ false, identifiersAndUris ] },
kind: vscode.CodeActionKind.QuickFix
};
}
}
if (numFixTypes > 1) {
const allWorkspaceEdit: vscode.WorkspaceEdit = new vscode.WorkspaceEdit();
for (const [uri, edits] of uriToEditsForAll.entries()) {
allWorkspaceEdit.set(uri, edits);
}
if (codeAnalysisAllFixes.fixAllCodeAction.command?.arguments !== undefined) {
codeAnalysisAllFixes.fixAllCodeAction.command.arguments[1] = allWorkspaceEdit;
codeAnalysisAllFixes.fixAllCodeAction.command.arguments[3] = identifiersAndUrisForAllFixes;
}
} else {
if (codeAnalysisAllFixes.fixAllCodeAction.command?.arguments !== undefined) {
codeAnalysisAllFixes.fixAllCodeAction.command.arguments[1] = undefined;
}
}
}
export function publishCodeAnalysisDiagnostics(params: PublishCodeAnalysisDiagnosticsParams): void {
if (!diagnosticsCollectionCodeAnalysis) {
diagnosticsCollectionCodeAnalysis = vscode.languages.createDiagnosticCollection("clang-tidy");
}
// Convert from our Diagnostic objects to vscode Diagnostic objects
const diagnosticsCodeAnalysis: vscode.Diagnostic[] = [];
const realUri: vscode.Uri = vscode.Uri.parse(params.uri);
// Reset codeAnalysisCodeToFixes for the file.
for (const codeToFixes of codeAnalysisCodeToFixes) {
++codeToFixes[1].version;
if (codeToFixes[1].uriToInfo.has(params.uri)) {
codeToFixes[1].uriToInfo.delete(params.uri);
}
}
const previousDiagnostics: CodeActionDiagnosticInfo[] | undefined = codeAnalysisFileToCodeActions.get(params.uri);
let nextVersion: number = 0;
if (previousDiagnostics !== undefined) {
for (const diagnostic of previousDiagnostics) {
if (diagnostic.version > nextVersion) {
nextVersion = diagnostic.version;
}
}
}
++nextVersion;
const codeActionDiagnosticInfo: CodeActionDiagnosticInfo[] = [];
for (const d of params.diagnostics) {
const diagnostic: vscode.Diagnostic = new vscode.Diagnostic(makeVscodeRange(d.range),
getLocalizedString(d.localizeStringParams), d.severity);
const identifier: CodeAnalysisDiagnosticIdentifier = { range: d.range, code: d.code };
const identifiersAndUri: CodeAnalysisDiagnosticIdentifiersAndUri = { uri: params.uri, identifiers: [ identifier ] };
const codeAction: CodeActionDiagnosticInfo = {
version: nextVersion,
range: makeVscodeRange(identifier.range),
code: identifier.code,
removeCodeAction: {
title: localize("clear_this_problem", "Clear this {0} problem", d.code),
command: { title: 'RemoveCodeAnalysisProblems', command: 'C_Cpp.RemoveCodeAnalysisProblems',
arguments: [ false, [ identifiersAndUri ] ] },
kind: vscode.CodeActionKind.QuickFix
}
};
const workspaceEdit: CodeActionWorkspaceEdit = {};
if (d.workspaceEdit) {
workspaceEdit.workspaceEdit = new vscode.WorkspaceEdit();
for (const [uriStr, edits] of Object.entries(d.workspaceEdit.changes)) {
workspaceEdit.workspaceEdit.set(vscode.Uri.parse(uriStr, true), makeVscodeTextEdits(edits));
}
const fixThisCodeAction: vscode.CodeAction = {
title: localize("fix_this_problem", "Fix this {0} problem", d.code),
command: { title: 'FixThisCodeAnalysisProblem', command: 'C_Cpp.FixThisCodeAnalysisProblem',
arguments: [ nextVersion, workspaceEdit.workspaceEdit, true, [ identifiersAndUri ] ] },
kind: vscode.CodeActionKind.QuickFix
};
codeAction.fixCodeAction = fixThisCodeAction;
}
// Edits from clang-tidy can be associated with the related information instead of the root diagnostic.
const relatedCodeActions: CodeActionDiagnosticInfo[] = [];
const rootAndRelatedWorkspaceEdits: CodeActionWorkspaceEdit[] = [];
const rootAndRelatedIdentifiersAndUris: CodeAnalysisDiagnosticIdentifiersAndUri[] = [];
if (workspaceEdit.workspaceEdit !== undefined) {
rootAndRelatedWorkspaceEdits.push(workspaceEdit);
rootAndRelatedIdentifiersAndUris.push(identifiersAndUri);
}
if (d.relatedInformation) {
diagnostic.relatedInformation = [];
for (const info of d.relatedInformation) {
diagnostic.relatedInformation.push(new vscode.DiagnosticRelatedInformation(makeVscodeLocation(info.location), info.message));
if (info.workspaceEdit === undefined) {
continue;
}
const relatedWorkspaceEdit: vscode.WorkspaceEdit = new vscode.WorkspaceEdit();
for (const [uriStr, edits] of Object.entries(info.workspaceEdit.changes)) {
relatedWorkspaceEdit.set(vscode.Uri.parse(uriStr, true), makeVscodeTextEdits(edits));
}
const relatedIdentifier: CodeAnalysisDiagnosticIdentifier = { range: info.location.range, code: d.code };
const relatedIdentifiersAndUri: CodeAnalysisDiagnosticIdentifiersAndUri = {
uri: info.location.uri, identifiers: [ relatedIdentifier ] };
const relatedCodeAction: vscode.CodeAction = {
title: localize("fix_this_problem", "Fix this {0} problem", d.code),
command: { title: 'FixThisCodeAnalysisProblem', command: 'C_Cpp.FixThisCodeAnalysisProblem',
arguments: [ nextVersion, relatedWorkspaceEdit, true, [ relatedIdentifiersAndUri ] ] },
kind: vscode.CodeActionKind.QuickFix
};
if (codeAction.fixCodeAction === undefined) {
codeAction.fixCodeAction = relatedCodeAction;
} else {
const relatedCodeActionInfo: CodeActionDiagnosticInfo = {
version: nextVersion,
range: makeVscodeRange(relatedIdentifier.range),
code: relatedIdentifier.code,
fixCodeAction: relatedCodeAction
};
relatedCodeActions.push(relatedCodeActionInfo);
}
rootAndRelatedWorkspaceEdits.push({ workspaceEdit: relatedWorkspaceEdit});
rootAndRelatedIdentifiersAndUris.push(relatedIdentifiersAndUri);
}
}
if (identifier.code.length !== 0) {
const codeActionCodeInfo: CodeActionCodeInfo = codeAnalysisCodeToFixes.get(identifier.code) ??
{ version: 0, uriToInfo: new Map<string, CodeActionPerUriInfo>() };
let rootAndRelatedWorkspaceEditsIndex: number = 0;
for (const rootAndRelatedIdentifiersAndUri of rootAndRelatedIdentifiersAndUris) {
const existingInfo: CodeActionPerUriInfo = codeActionCodeInfo.uriToInfo.get(rootAndRelatedIdentifiersAndUri.uri) ??
{ identifiers: [], numValidWorkspaceEdits: 0 };
existingInfo.identifiers.push(...rootAndRelatedIdentifiersAndUri.identifiers);
const rootAndRelatedWorkspaceEdit: CodeActionWorkspaceEdit = rootAndRelatedWorkspaceEdits[rootAndRelatedWorkspaceEditsIndex];
if (rootAndRelatedWorkspaceEdit !== undefined) {
if (existingInfo.workspaceEdits === undefined) {
existingInfo.workspaceEdits = [ rootAndRelatedWorkspaceEdit ];
} else {
existingInfo.workspaceEdits.push(rootAndRelatedWorkspaceEdit);
}
++existingInfo.numValidWorkspaceEdits;
}
codeActionCodeInfo.uriToInfo.set(rootAndRelatedIdentifiersAndUri.uri, existingInfo);
++rootAndRelatedWorkspaceEditsIndex;
}
if (!identifier.code.startsWith("clang-diagnostic-")) {
const codes: string[] = identifier.code.split(',');
let codeIndex: number = codes.length - 1;
if (codes[codeIndex] === "cert-dcl51-cpp") { // Handle aliasing
codeIndex = 0;
}
// TODO: Is the ideal code always selected as the primary one?
const primaryCode: string = codes[codeIndex];
const docPage: string = primaryCode === "clang-tidy-nolint" ? "#suppressing-undesired-diagnostics" :
`checks/${primaryCode}.html`;
const primaryDocUri: vscode.Uri = vscode.Uri.parse(`https://releases.llvm.org/14.0.0/tools/clang/tools/extra/docs/clang-tidy/${docPage}`);
diagnostic.code = { value: identifier.code, target: primaryDocUri };
if (new CppSettings().clangTidyCodeActionShowDocumentation) {
if (codeActionCodeInfo.docCodeAction === undefined) {
codeActionCodeInfo.docCodeAction = {
title: localize("show_documentation_for", "Show documentation for {0}", primaryCode),
command: { title: 'ShowDocumentation', command: 'C_Cpp.ShowCodeAnalysisDocumentation',
arguments: [ primaryDocUri ] },
kind: vscode.CodeActionKind.QuickFix
};
}
} else {
codeActionCodeInfo.docCodeAction = undefined;
}
} else {
diagnostic.code = d.code;
}
codeAnalysisCodeToFixes.set(identifier.code, codeActionCodeInfo);
} else {
diagnostic.code = d.code;
}
diagnostic.source = CppSourceStr;
codeActionDiagnosticInfo.push(codeAction);
if (relatedCodeActions.length > 0) {
codeActionDiagnosticInfo.push(...relatedCodeActions);
}
diagnosticsCodeAnalysis.push(diagnostic);
}
codeAnalysisFileToCodeActions.set(params.uri, codeActionDiagnosticInfo);
rebuildCodeAnalysisCodeAndAllFixes();
diagnosticsCollectionCodeAnalysis.set(realUri, diagnosticsCodeAnalysis);
}
function removeCodeAnalysisCodeActions(identifiersAndUris: CodeAnalysisDiagnosticIdentifiersAndUri[],
removeFixesOnly: boolean): void {
for (const identifiersAndUri of identifiersAndUris) {
const codeActionDiagnosticInfo: CodeActionDiagnosticInfo[] | undefined = codeAnalysisFileToCodeActions.get(identifiersAndUri.uri);
if (codeActionDiagnosticInfo === undefined) {
return;
}
for (const identifier of identifiersAndUri.identifiers) {
const updatedCodeActions: CodeActionDiagnosticInfo[] = [];
for (const codeAction of codeActionDiagnosticInfo) {
if (rangeEquals(codeAction.range, identifier.range) && codeAction.code === identifier.code) {
if (removeFixesOnly) {
++codeAction.version;
codeAction.fixCodeAction = undefined;
} else {
continue;
}
}
updatedCodeActions.push(codeAction);
}
codeAnalysisFileToCodeActions.set(identifiersAndUri.uri, updatedCodeActions);
let codeActionInfoChanged: boolean = false;
for (const codeFixes of codeAnalysisCodeToFixes) {
const codeActionInfo: CodeActionPerUriInfo | undefined = codeFixes[1].uriToInfo.get(identifiersAndUri.uri);
if (codeActionInfo === undefined) {
continue;
}
let removedCodeActionInfoIndex: number = -1;
for (let codeActionInfoIndex: number = 0; codeActionInfoIndex < codeActionInfo.identifiers.length; ++codeActionInfoIndex) {
if (identifier.code === codeActionInfo.identifiers[codeActionInfoIndex].code &&
rangeEquals(identifier.range, codeActionInfo.identifiers[codeActionInfoIndex].range)) {
removedCodeActionInfoIndex = codeActionInfoIndex;
codeActionInfoChanged = true;
break;
}
}
if (removedCodeActionInfoIndex !== -1) {
if (removeFixesOnly) {
if (codeActionInfo.workspaceEdits !== undefined) {
codeActionInfo.workspaceEdits[removedCodeActionInfoIndex].workspaceEdit = undefined;
--codeActionInfo.numValidWorkspaceEdits;
}
} else {
codeActionInfo.identifiers.splice(removedCodeActionInfoIndex, 1);
if (codeActionInfo.workspaceEdits !== undefined) {
codeActionInfo.workspaceEdits.splice(removedCodeActionInfoIndex, 1);
--codeActionInfo.numValidWorkspaceEdits;
}
}
if (codeActionInfo.identifiers.length === 0) {
codeFixes[1].uriToInfo.delete(identifiersAndUri.uri);
} else {
codeFixes[1].uriToInfo.set(identifiersAndUri.uri, codeActionInfo);
}
}
}
if (codeActionInfoChanged) {
rebuildCodeAnalysisCodeAndAllFixes();
}
}
}
}
export function publishRemoveCodeAnalysisCodeActionFixes(params: RemoveCodeAnalysisCodeActionFixesParams): void {
removeCodeAnalysisCodeActions(params.identifiersAndUris, true);
}
export function removeAllCodeAnalysisProblems(): boolean {
if (!diagnosticsCollectionCodeAnalysis) {
return false;
}
diagnosticsCollectionCodeAnalysis.clear();
codeAnalysisFileToCodeActions.clear();
codeAnalysisCodeToFixes.clear();
rebuildCodeAnalysisCodeAndAllFixes();
return true;
}
export function removeCodeAnalysisProblems(identifiersAndUris: CodeAnalysisDiagnosticIdentifiersAndUri[]): boolean {
if (!diagnosticsCollectionCodeAnalysis) {
return false;
}
// Remove the diagnostics.
for (const identifiersAndUri of identifiersAndUris) {
const uri: vscode.Uri = vscode.Uri.parse(identifiersAndUri.uri);
const diagnostics: readonly vscode.Diagnostic[] | undefined = diagnosticsCollectionCodeAnalysis.get(uri);
if (diagnostics === undefined) {
continue;
}
const newDiagnostics: vscode.Diagnostic[] = [];
for (const diagnostic of diagnostics) {
const code: string = typeof diagnostic.code === "string" ? diagnostic.code :
(typeof diagnostic.code === "object" && typeof diagnostic.code.value === "string" ?
diagnostic.code.value : "");
let removed: boolean = false;
for (const identifier of identifiersAndUri.identifiers) {
if (code !== identifier.code || !rangeEquals(diagnostic.range, identifier.range)) {
continue;
}
removed = true;
break;
}
if (!removed) {
newDiagnostics.push(diagnostic);
}
}
diagnosticsCollectionCodeAnalysis.set(uri, newDiagnostics);
}
removeCodeAnalysisCodeActions(identifiersAndUris, false);
return true;
} | the_stack |
import React, {useState, useEffect, useContext} from "react";
import {Row, Col, Card, Menu, Dropdown, Collapse, Icon, Switch} from "antd";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faPlusSquare} from "@fortawesome/free-solid-svg-icons";
import {faTrashAlt} from "@fortawesome/free-regular-svg-icons";
import {useHistory} from "react-router-dom";
import {MLButton, MLTable, MLInput, MLRadio, MLTooltip} from "@marklogic/design-system";
import styles from "./matching-step-detail.module.scss";
import "./matching-step-detail.scss";
import {MatchingStepTooltips} from "../../../../config/tooltips.config";
import CustomPageHeader from "../../page-header/page-header";
import RulesetSingleModal from "../ruleset-single-modal/ruleset-single-modal";
import RulesetMultipleModal from "../ruleset-multiple-modal/ruleset-multiple-modal";
import NumberIcon from "../../../number-icon/number-icon";
import ThresholdModal from "../threshold-modal/threshold-modal";
import {CurationContext} from "../../../../util/curation-context";
import {MatchingStep} from "../../../../types/curation-types";
import {MatchingStepDetailText} from "../../../../config/tooltips.config";
import {updateMatchingArtifact, calculateMatchingActivity, previewMatchingActivity, getDocFromURI} from "../../../../api/matching";
import {DownOutlined} from "@ant-design/icons";
import {getViewSettings, setViewSettings, clearSessionStorageOnRefresh} from "../../../../util/user-context";
import ExpandCollapse from "../../../expand-collapse/expand-collapse";
import ExpandableTableView from "../expandable-table-view/expandable-table-view";
import CompareValuesModal from "../compare-values-modal/compare-values-modal";
import moment from "moment";
import TimelineVis from "./timeline-vis/timeline-vis";
import TimelineVisDefault from "./timeline-vis-default/timeline-vis-default";
const DEFAULT_MATCHING_STEP: MatchingStep = {
name: "",
description: "",
additionalCollections: [],
collections: [],
lastUpdated: "",
permissions: "",
provenanceGranularityLevel: "",
selectedSource: "",
sourceDatabase: "",
sourceQuery: "",
stepDefinitionName: "",
stepDefinitionType: "",
stepId: "",
targetDatabase: "",
targetEntityType: "",
targetFormat: "",
matchRulesets: [],
thresholds: [],
interceptors: {},
customHook: {}
};
const MatchingStepDetail: React.FC = () => {
const storage = getViewSettings();
// Prevents an infinite loop issue with sessionStorage due to user refreshing in step detail page.
clearSessionStorageOnRefresh();
const history = useHistory<any>();
const {curationOptions, updateActiveStepArtifact} = useContext(CurationContext);
const [matchingStep, setMatchingStep] = useState<MatchingStep>(DEFAULT_MATCHING_STEP);
const [editThreshold, setEditThreshold] = useState({});
const [editRuleset, setEditRuleset] = useState({});
const [showThresholdModal, toggleShowThresholdModal] = useState(false);
const [showRulesetSingleModal, toggleShowRulesetSingleModal] = useState(false);
const [moreThresholdText, toggleMoreThresholdText] = useState(true);
const [moreRulesetText, toggleMoreRulesetText] = useState(true);
const [matchingActivity, setMatchingActivity] = useState<any>({scale: {}, thresholdActions: []});
const [value, setValue] = React.useState(1);
const [UriTableData, setUriTableData] = useState<any[]>([]);
const [UriTableData2, setUriTableData2] = useState<any[]>([]);
const [uriContent, setUriContent] = useState("");
const [uriContent2, setUriContent2] = useState("");
const [inputUriDisabled, setInputUriDisabled] = useState(false);
const [inputUriDisabled2, setInputUriDisabled2] = useState(true);
const [testMatchTab] = useState("matched");
const [duplicateUriWarning, setDuplicateUriWarning] = useState(false);
const [duplicateUriWarning2, setDuplicateUriWarning2] = useState(false);
const [singleUriWarning, setSingleUriWarning] = useState(false);
const [singleUriWarning2, setSingleUriWarning2] = useState(false);
const [uriTestMatchClicked, setUriTestMatchClicked] = useState(false);
const [allDataSelected, setAllDataSelected] = useState(false);
const [testUrisOnlySelected, setTestUrisOnlySelected] = useState(true);
const [testUrisAllDataSelected, setTestUrisAllDataSelected] = useState(false);
const [testMatchedData, setTestMatchedData] = useState<any>({stepName: "", sampleSize: 100, uris: []});
const [previewMatchedActivity, setPreviewMatchedActivity] = useState<any>({sampleSize: 100, uris: [], actionPreview: []});
const [showRulesetMultipleModal, toggleShowRulesetMultipleModal] = useState(false);
const [rulesetDataList, setRulesetDataList] = useState<any>([{rulesetName: "", actionPreviewData: [{name: "", action: "", uris: ["", ""]}], score: 0}]);
const {Panel} = Collapse;
const [activeMatchedRuleset, setActiveMatchedRuleset] = useState<string[]>([]);
const [activeMatchedUri, setActiveMatchedUri] = useState<string[]>([]);
const [allRulesetNames] = useState<string[]>([]);
const [compareModalVisible, setCompareModalVisible] = useState(false);
const [uriInfo, setUriInfo] = useState<any>();
const [entityProperties, setEntityProperties] = useState<any>();
const [urisCompared, setUrisCompared] = useState<string[]>([]);
const [uris, setUris] = useState<string[]>([]);
const [previewMatchedData, setPreviewMatchedData] = useState(-1);
const [expandRuleset, setExpandRuleset] = useState(false);
//To handle timeline display
const [rulesetItems, setRulesetItems] = useState<any []>([]);
const [thresholdItems, setThresholdItems] = useState<any []>([]);
const [displayRulesetTimeline, toggleDisplayRulesetTimeline] = useState(false);
const [displayThresholdTimeline, toggleDisplayThresholdTimeline] = useState(false);
const menu = (
<Menu>
<Menu.Item key="singlePropertyRuleset">
<span onClick={() => addNewSingleRuleset()} aria-label={"singlePropertyRulesetOption"}>Add ruleset for a single property</span>
</Menu.Item>
<Menu.Item key="multiPropertyRuleset">
<span onClick={() => addNewMultipleRuleset()} aria-label={"multiPropertyRulesetOption"}>Add ruleset for multiple properties</span>
</Menu.Item>
</Menu>
);
useEffect(() => {
if (Object.keys(curationOptions.activeStep.stepArtifact).length !== 0) {
const matchingStepArtifact: MatchingStep = curationOptions.activeStep.stepArtifact;
if (matchingStepArtifact.matchRulesets) {
if (matchingStepArtifact.matchRulesets.length > 0) {
let rulesetItems = matchingStepArtifact.matchRulesets.map((item, id) => ({
id: id,
start: item.weight,
reduce: item.reduce ? item.reduce : false,
value: item.name+ ":" + item.weight.toString()
}));
setRulesetItems(rulesetItems);
toggleMoreRulesetText(false);
} else {
toggleMoreRulesetText(true);
}
}
if (matchingStepArtifact.thresholds) {
if (matchingStepArtifact.thresholds.length > 0) {
let thresholdItems = matchingStepArtifact.thresholds.map((item, id) => ({
id: id,
start: item.score,
value: item.thresholdName+ " - " + item.action +":"+ item.score.toString(),
}));
setThresholdItems(thresholdItems);
toggleMoreThresholdText(false);
} else {
toggleMoreThresholdText(true);
}
}
setMatchingStep(matchingStepArtifact);
handleMatchingActivity(matchingStepArtifact.name);
} else {
history.push("/tiles/curate");
}
/*return () => {
toggleDisplayRulesetTimeline(false);
}*/
}, [JSON.stringify(curationOptions.activeStep.stepArtifact)]);
const handleMatchingActivity = async (matchStepName) => {
let matchActivity = await calculateMatchingActivity(matchStepName);
setMatchingActivity(matchActivity);
};
const handlePreviewMatchingActivity = async (testMatchData) => {
const test = () => {
for (let i = 0; i < curationOptions.activeStep.stepArtifact.thresholds.length; i++) {
let ruleset = curationOptions.activeStep.stepArtifact.thresholds[i].thresholdName.concat(" - ") + curationOptions.activeStep.stepArtifact.thresholds[i].action;
let score = curationOptions.activeStep.stepArtifact.thresholds[i].score;
let actionPreviewList = [{}];
if (previewMatchActivity === undefined) previewMatchActivity={actionPreview: []};
for (let j = 0; j < previewMatchActivity.actionPreview.length; j++) {
if (curationOptions.activeStep.stepArtifact.thresholds[i].thresholdName === previewMatchActivity.actionPreview[j].name && curationOptions.activeStep.stepArtifact.thresholds[i].action === previewMatchActivity.actionPreview[j].action) {
actionPreviewList.push(previewMatchActivity.actionPreview[j]);
}
}
actionPreviewList.shift();
let localData = {rulesetName: "", actionPreviewData: [{}], score: 0};
localData.rulesetName = ruleset;
localData.score = score;
localData.actionPreviewData = actionPreviewList;
allRulesetNames.push(ruleset);
if (localData.actionPreviewData.length > 0) {
rulesetDataList.push(localData);
}
}
rulesetDataList.shift();
};
let previewMatchActivity = await previewMatchingActivity(testMatchData);
setPreviewMatchedData(previewMatchActivity.actionPreview.length);
if (previewMatchActivity) {
await test();
setPreviewMatchedActivity(previewMatchActivity);
setRulesetDataList(rulesetDataList);
}
};
const getKeysToExpandFromTable = async () => {
let allKeys=[""];
rulesetDataList.forEach((ruleset) => {
for (let i in ruleset.actionPreviewData) {
let key=ruleset.rulesetName.concat("/")+i;
allKeys.push(key);
}
});
return allKeys;
};
const addNewSingleRuleset = () => {
setEditRuleset({});
toggleShowRulesetSingleModal(true);
};
const addNewMultipleRuleset = () => {
setEditRuleset({});
toggleShowRulesetMultipleModal(true);
};
const getRulesetName = (rulesetComb) => {
let matchRules = rulesetComb.matchRules;
let rulesetName = rulesetComb.rulesetName.split(".").join(" > ");
if (!rulesetComb.rulesetName && Array.isArray(matchRules) && matchRules.length) {
rulesetName = matchRules[0].entityPropertyPath.split(".").join(" > ") + " - " + matchRules[0].matchAlgorithm;
}
return rulesetName;
};
const onTestMatchRadioChange = event => {
setValue(event.target.value);
setPreviewMatchedData(-1);
};
const handleUriInputChange = (event) => {
setUriContent(event.target.value);
};
const handleUriInputChange2 = (event) => {
setUriContent2(event.target.value);
};
const handleClickAddUri = (event) => {
let flag=false;
let setDuplicateWarning = () => { setDuplicateUriWarning(true); setSingleUriWarning(false); };
if (UriTableData.length > 0) {
for (let i=0; i<UriTableData.length;i++) {
if (UriTableData[i].uriContent === uriContent) {
flag=true;
setDuplicateWarning();
break;
}
}
}
if (uriContent.length > 0 && !flag) {
let data = [...UriTableData];
data.push({uriContent});
setUriTableData(data);
setUriContent("");
setDuplicateUriWarning(false);
setSingleUriWarning(false);
}
};
const handleClickAddUri2 = (event) => {
let flag=false;
let setDuplicateWarning = () => { setDuplicateUriWarning2(true); setSingleUriWarning2(false); };
if (UriTableData2.length > 0) {
for (let i=0; i<UriTableData2.length;i++) {
if (UriTableData2[i].uriContent2 === uriContent2) {
flag=true;
setDuplicateWarning();
break;
}
}
}
if (uriContent2.length > 0 && !flag) {
let data = [...UriTableData2];
data.push({uriContent2});
setUriTableData2(data);
setUriContent2("");
setDuplicateUriWarning2(false);
setSingleUriWarning2(false);
}
};
const renderUriTableData = UriTableData.map((uriData) => {
return {
key: uriData.uriContent,
uriValue: uriData.uriContent,
};
});
const renderUriTableData2 = UriTableData2.map((uriData) => {
return {
key: uriData.uriContent2,
uriValue: uriData.uriContent2,
};
});
const UriColumns = [{
key: "uriValue",
title: "uriValues",
dataIndex: "uriValue",
render: (text, key) => (
<span className={styles.tableRow}>{text}<i className={styles.positionDeleteIcon} aria-label="deleteIcon">
<FontAwesomeIcon icon={faTrashAlt} className={styles.deleteIcon} onClick={() => handleDeleteUri(key)} size="lg"/></i>
</span>
),
}];
const UriColumns2 = [{
key: "uriValue",
title: "uriValues",
dataIndex: "uriValue",
render: (text, key) => (
<span className={styles.tableRow}>{text}<i className={styles.positionDeleteIcon} aria-label="deleteIcon">
<FontAwesomeIcon icon={faTrashAlt} className={styles.deleteIcon} onClick={() => handleDeleteUri2(key)} size="lg"/></i>
</span>
),
}];
const handleDeleteUri = (event) => {
let uriValue = event.uriValue;
let data = [...UriTableData];
for (let i =0; i < data.length; i++) {
if (data[i].uriContent === uriValue) {
data.splice(i, 1);
break;
}
}
setUriTableData(data);
setDuplicateUriWarning(false);
setSingleUriWarning(false);
setUriTestMatchClicked(false);
};
const handleDeleteUri2 = (event) => {
let uriValue = event.uriValue;
let data = [...UriTableData2];
for (let i =0; i < data.length; i++) {
if (data[i].uriContent2 === uriValue) {
data.splice(i, 1);
break;
}
}
setUriTableData2(data);
setDuplicateUriWarning2(false);
setSingleUriWarning2(false);
setUriTestMatchClicked(false);
};
const handleAllDataRadioClick = (event) => {
testMatchedData.uris=[];
setAllDataSelected(true);
setUriTableData([]);
setUriTableData2([]);
setUriContent("");
setUriContent2("");
setInputUriDisabled(true);
setInputUriDisabled2(true);
setDuplicateUriWarning(false);
setDuplicateUriWarning2(false);
setSingleUriWarning(false);
setSingleUriWarning2(false);
setUriTestMatchClicked(false);
setRulesetDataList([{rulesetName: "", actionPreviewData: [{name: "", action: "", uris: ["", ""]}], score: 0}]);
};
const handleTestButtonClick = async () => {
testMatchedData.uris=[];
setRulesetDataList([{rulesetName: "", actionPreviewData: [{name: "", action: "", uris: ["", ""]}], score: 0}]);
setActiveMatchedUri([]);
setActiveMatchedRuleset([]);
if (UriTableData.length < 2 && !allDataSelected && !testUrisAllDataSelected) {
setDuplicateUriWarning(false);
setSingleUriWarning(true);
}
if (UriTableData2.length === 0 && !allDataSelected && !testUrisOnlySelected) {
setDuplicateUriWarning2(false);
setSingleUriWarning2(true);
}
if (UriTableData.length >= 2 || allDataSelected) {
if (!duplicateUriWarning && !singleUriWarning) {
setUriTestMatchClicked(true);
for (let i=0;i<UriTableData.length;i++) {
testMatchedData.uris.push(UriTableData[i].uriContent);
}
testMatchedData.stepName=matchingStep.name;
if (!allDataSelected) testMatchedData.restrictToUris=true;
else testMatchedData.restrictToUris=false;
setTestMatchedData(testMatchedData);
await handlePreviewMatchingActivity(testMatchedData);
}
}
if (UriTableData2.length >= 1) {
if (!duplicateUriWarning2 && !singleUriWarning2) {
setUriTestMatchClicked(true);
for (let i=0;i<UriTableData2.length;i++) {
testMatchedData.uris.push(UriTableData2[i].uriContent2);
}
testMatchedData.stepName=matchingStep.name;
testMatchedData.restrictToUris=false;
setTestMatchedData(testMatchedData);
await handlePreviewMatchingActivity(testMatchedData);
}
}
};
// const handleTestMatchTab = (event) => {
// setTestMatchTab(event.key);
// };
const handleUriInputSelected = (event) => {
setInputUriDisabled(false);
setTestUrisOnlySelected(true);
setTestUrisAllDataSelected(false);
setInputUriDisabled2(true);
setAllDataSelected(false);
setUriTableData2([]);
setUriContent2("");
setUriTestMatchClicked(false);
setSingleUriWarning2(false);
setDuplicateUriWarning2(false);
setRulesetDataList([{rulesetName: "", actionPreviewData: [{name: "", action: "", uris: ["", ""]}], score: 0}]);
};
const handleUriInputSelected2 = (event) => {
setInputUriDisabled2(false);
setInputUriDisabled(true);
setTestUrisOnlySelected(false);
setTestUrisAllDataSelected(true);
setDuplicateUriWarning(false);
setSingleUriWarning(false);
setUriTableData([]);
setUriContent("");
setAllDataSelected(false);
setUriTestMatchClicked(false);
setRulesetDataList([{rulesetName: "", actionPreviewData: [{name: "", action: "", uris: ["", ""]}], score: 0}]);
};
const handleExpandCollapse = async (option) => {
if (option === "collapse") {
setActiveMatchedRuleset([]);
setActiveMatchedUri([]);
} else {
setActiveMatchedRuleset(allRulesetNames);
let allKey =await getKeysToExpandFromTable();
setActiveMatchedUri(allKey);
}
};
const handleExpandCollapseRulesIcon = async (option) => {
if (option === "collapse") {
setExpandRuleset(false);
} else {
setExpandRuleset(true);
}
};
const handleRulesetCollapseChange = async (keys) => {
Array.isArray(keys) ? setActiveMatchedRuleset(keys):setActiveMatchedRuleset([keys]);
let arr=activeMatchedUri;
for (let i=0;i<activeMatchedUri.length;i++) {
let rulesetName = activeMatchedUri[i].split("/")[0];
if (!activeMatchedRuleset.includes(rulesetName)) {
arr = arr.filter(e => e !== activeMatchedUri[i]);
}
}
handleUrisCollapseChange(arr);
};
const handleUrisCollapseChange = (keys) => {
Array.isArray(keys) ? setActiveMatchedUri(keys):setActiveMatchedUri([keys]);
};
const handleCompareButton = async (arr) => {
setEntityProperties(curationOptions.entityDefinitionsArray[0].properties);
const result1 = await getDocFromURI(arr[0]);
const result2 = await getDocFromURI(arr[1]);
const uris=[arr[0], arr[1]];
setUris(uris);
if (result1.status === 200 && result2.status === 200) {
let result1Instance = result1.data.data.envelope.instance;
let result2Instance = result2.data.data.envelope.instance;
await setUriInfo([{result1Instance}, {result2Instance}]);
}
setCompareModalVisible(true);
setUrisCompared(uris);
};
const updateRulesetItems = async (id, newvalue) => {
let stepArtifact = curationOptions.activeStep.stepArtifact;
let stepArtifactRulesets = curationOptions.activeStep.stepArtifact.matchRulesets;
let updateRuleset = stepArtifactRulesets[id];
updateRuleset["weight"] = parseInt(newvalue);
stepArtifactRulesets[id] = updateRuleset;
stepArtifact["matchRulesets"] = stepArtifactRulesets;
updateActiveStepArtifact(stepArtifact);
await updateMatchingArtifact(stepArtifact);
};
const timelineOrder = (a, b) => {
let aParts = a.value.split(":");
let bParts = b.value.split(":");
// If weights not equal
if (bParts[bParts.length-1] !== aParts[aParts.length-1]) {
// By weight
return parseInt(bParts[bParts.length-1]) - parseInt(aParts[aParts.length-1]);
} else {
// Else alphabetically
let aUpper = a.value.toUpperCase();
let bUpper = b.value.toUpperCase();
return (aUpper < bUpper) ? 1 : (aUpper > bUpper) ? -1 : 0;
}
};
const rulesetOptions:any = {
max: 120,
min: -20,
start: -20,
end: 120,
width: "100%",
itemsAlwaysDraggable: {
item: displayRulesetTimeline,
range: displayRulesetTimeline
},
selectable: false,
editable: {
remove: true,
updateTime: true
},
moveable: false,
timeAxis: {
scale: "millisecond",
step: 5
},
onMove: function(item, callback) {
if (item.start >= 0 && item.start <= 100) {
item.value = item.start.getMilliseconds().toString();
callback(item);
updateRulesetItems(item.id, item.start.getMilliseconds().toString());
} else {
if (item.start < 1) {
item.start = 1;
item.value = "1";
} else {
item.start = 100;
item.value = "100";
}
callback(item);
updateRulesetItems(item.id, item.value);
}
},
format: {
minorLabels: function (date, scale, step) {
let time;
if (date >= 0 && date <= 100) {
time = date.format("SSS");
return moment.duration(time).asMilliseconds();
} else {
return "";
}
},
},
template: function(item) {
if (item && item.hasOwnProperty("value")) {
if (item.reduce === false) {
return "<div data-testid=\"ruleset"+" "+item.value.split(":")[0]+"\">" + item.value.split(":")[0] + "<div class=\"itemValue\">" + item.value.split(":")[1] + "</div></div>";
} else {
return "<div data-testid=\"ruleset-reduce"+" "+item.value.split(":")[0]+"\">" + item.value.split(":")[0] + "<div class=\"itemReduceValue\">" + - item.value.split(":")[1] + "</div></div>";
}
}
},
maxMinorChars: 4,
order: timelineOrder
};
const thresholdOptions:any = {
max: 120,
min: -20,
start: -20,
end: 120,
width: "100%",
itemsAlwaysDraggable: {
item: displayThresholdTimeline,
range: displayThresholdTimeline
},
selectable: false,
editable: {
remove: true,
updateTime: true
},
moveable: false,
timeAxis: {
scale: "millisecond",
step: 5
},
onMove: function(item, callback) {
if (item.start >= 0 && item.start <= 100) {
item.value = item.start.getMilliseconds().toString();
callback(item);
updateThresholdItems(item.id, item.start.getMilliseconds().toString());
} else {
if (item.start < 1) {
item.start = 1;
item.value = "1";
} else {
item.start = 100;
item.value = "100";
}
callback(item);
updateThresholdItems(item.id, item.value);
}
},
format: {
minorLabels: function (date, scale, step) {
let time;
if (date >= 0 && date <= 100) {
time = date.format("SSS");
return moment.duration(time).asMilliseconds();
} else {
return "";
}
},
},
template: function(item) {
if (item && item.hasOwnProperty("value")) {
return "<div data-testid=\"threshold"+" "+item.value.split(":")[0]+"\">" + item.value.split(":")[0] + "<div class=\"itemValue\">" + item.value.split(":")[1] + "</div></div>";
}
},
maxMinorChars: 4,
order: timelineOrder
};
const renderRulesetTimeline = () => {
return <div data-testid={"active-ruleset-timeline"}><TimelineVis items={rulesetItems} options={rulesetOptions} clickHandler={onRuleSetTimelineItemClicked} /></div>;
};
const renderDefaultRulesetTimeline = () => {
return <div data-testid={"default-ruleset-timeline"}><TimelineVisDefault items={rulesetItems} options={rulesetOptions} /></div>;
};
const renderDefaultThresholdTimeline = () => {
return <div data-testid={"default-threshold-timeline"}><TimelineVisDefault items={thresholdItems} options={thresholdOptions} /></div>;
};
const renderThresholdTimeline = () => {
return <div data-testid={"active-threshold-timeline"}><TimelineVis items={thresholdItems} options={thresholdOptions} clickHandler={onThresholdTimelineItemClicked} /></div>;
};
const updateThresholdItems = async (id, newvalue) => {
let stepArtifact = curationOptions.activeStep.stepArtifact;
let stepArtifactThresholds = curationOptions.activeStep.stepArtifact.thresholds;
let updateThreshold = stepArtifactThresholds[id];
updateThreshold["score"] = parseInt(newvalue);
stepArtifactThresholds[id] = updateThreshold;
stepArtifact["thresholds"] = stepArtifactThresholds;
updateActiveStepArtifact(stepArtifact);
await updateMatchingArtifact(stepArtifact);
};
const onRuleSetTimelineItemClicked = (event) => {
let updateStepArtifactRulesets = curationOptions.activeStep.stepArtifact.matchRulesets;
let index = event.item;
let editMatchRuleset = updateStepArtifactRulesets[index];
setEditRuleset({...editMatchRuleset, index});
if (editMatchRuleset) {
if (editMatchRuleset.hasOwnProperty("rulesetType") && editMatchRuleset["rulesetType"] === "multiple") {
toggleShowRulesetMultipleModal(true);
} else {
toggleShowRulesetSingleModal(true);
}
}
};
const onThresholdTimelineItemClicked = (event) => {
let updateStepArtifactThresholds = curationOptions.activeStep.stepArtifact.thresholds;
let index = event.item;
let editThreshold = updateStepArtifactThresholds[index];
setEditThreshold({...editThreshold, index});
if (editThreshold) {
toggleShowThresholdModal(true);
}
};
return (
<>
<CustomPageHeader
title={matchingStep.name}
handleOnBack={() => {
history.push("/tiles/curate");
setViewSettings({...storage, curate: {}});
}}
/>
<p className={styles.headerDescription}>{MatchingStepDetailText.description}</p>
<div className={styles.matchingDetailContainer}>
<div className={expandRuleset ? styles.matchCombinationsExpandedContainer : styles.matchCombinationsCollapsedContainer}>
<div aria-label="matchCombinationsHeading" className={styles.matchCombinationsHeading}>Possible Combinations of Matched Rulesets</div>
<span className={styles.expandCollapseRulesIcon}><ExpandCollapse handleSelection={(id) => handleExpandCollapseRulesIcon(id)} currentSelection={"collapse"} aria-label="expandCollapseRulesetIcon"/></span>
{matchingActivity?.thresholdActions && matchingActivity?.thresholdActions.length ?
<Row gutter={[24, 24]} type="flex">
{matchingActivity?.thresholdActions?.map((combinationsObject, i, combArr) => {
return <Col span={8} key={`${combinationsObject["name"]}-${i}`}>
<div className={styles.matchCombinationsColsContainer}>
<Card bordered={false} className={styles.matchCombinationsCardStyle}>
<div className={combArr.length > 1 ? styles.colsWithoutDivider : styles.colsWithSingleMatch}>
<div className={styles.combinationlabel} aria-label={`combinationLabel-${combinationsObject.name}`}>Minimum combinations for <strong>{combinationsObject.name}</strong> threshold:</div>
{combinationsObject.minimumMatchContributions?.map((minMatchArray, index) => {
return <div key={`${minMatchArray[0]["rulsetName"]}-${index}`}>{minMatchArray.map((obj, index, arr) => {
if (arr.length - 1 === index) {
return <span key={`${combinationsObject.name}-${index}`} aria-label={`rulesetName-${combinationsObject.name}-${obj.rulesetName}`}>{getRulesetName(obj)}</span>;
} else {
return <span key={`${combinationsObject.name}-${index}`} aria-label={`rulesetName-${combinationsObject.name}-${obj.rulesetName}`}>{getRulesetName(obj)} <span className={styles.period}></span> </span>;
}
})}</div>;
})}
</div>
</Card>
</div>
</Col>;
})
}
</Row> : <p aria-label="noMatchedCombinations">Add thresholds and rulesets to the following sliders to determine which combinations of qualifying rulesets would meet each threshold.</p>
}
</div>
<div className={styles.stepNumberContainer}>
<NumberIcon value={1} />
<div className={styles.stepText}>Configure your thresholds</div>
</div>
<div className={styles.greyContainer}>
<div className={styles.topHeader}>
<div className={styles.textContainer}>
<p aria-label="threshold-text" className={`${moreThresholdText ? styles.showText : styles.hideText}`}>A <span className={styles.italic}>threshold</span> specifies how closely entities have to match before a certain action is triggered.
The action could be the merging of those entities, the creation of a match notification, or a custom action that is defined programmatically.
Click the <span className={styles.bold}>Add</span> button to create a threshold. If most of the values in the entities should match to trigger the action associated with your threshold,
then move the threshold higher on the scale. If only some of the values in the entities must match, then move the threshold lower.
<span aria-label="threshold-less" className={styles.link} onClick={() => toggleMoreThresholdText(!moreThresholdText)}>less</span>
</p>
{!moreThresholdText && <span aria-label="threshold-more" className={styles.link} onClick={() => toggleMoreThresholdText(!moreThresholdText)}>more</span> }
</div>
<div className={styles.addButtonContainer}>
<MLButton
aria-label="add-threshold"
type="primary"
size="default"
className={styles.addThresholdButton}
onClick={() => {
setEditThreshold({});
toggleShowThresholdModal(true);
}}
>Add</MLButton>
</div>
</div>
<div><span className={styles.editingLabel}><b>Edit Thresholds</b></span><Switch aria-label="threshold-scale-switch" onChange={(e) => toggleDisplayThresholdTimeline(e)} defaultChecked={false} ></Switch>
<span>
<MLTooltip title={MatchingStepTooltips.thresholdScale} placement={"right"}>
<Icon type="question-circle" className={styles.scaleTooltip} theme="filled" data-testid={"info-tooltip-threshold"}/>
</MLTooltip><br />
</span></div>
{displayThresholdTimeline ? renderThresholdTimeline() : renderDefaultThresholdTimeline()}
</div>
<div className={styles.stepNumberContainer}>
<NumberIcon value={2} />
<div className={styles.stepText}>Place rulesets on a match scale</div>
</div>
<div className={styles.greyContainer}>
<div className={styles.topHeader}>
<div className={styles.textContainer}>
<p aria-label="ruleset-text" className={`${moreRulesetText ? styles.showText : styles.hideText}`}>A <span className={styles.italic}>ruleset</span> specifies the criteria for determining whether the values of your entities match.
The way you define your rulesets, and where you place them on the scale, influences whether the entities are considered a match.
Click the <span className={styles.bold}>Add</span> button to create a ruleset. If you want the ruleset to have a major influence over whether entities are qualified as a "match",
move it higher on the scale. If you want it to have only some influence, then move the ruleset lower.
<span aria-label="ruleset-less" className={styles.link} onClick={() => toggleMoreRulesetText(!moreRulesetText)}>less</span>
</p>
{!moreRulesetText && <span aria-label="ruleset-more" className={styles.link} onClick={() => toggleMoreRulesetText(!moreRulesetText)}>more</span> }
</div>
<div
id="panelActionsMatch"
onClick={event => {
event.stopPropagation(); // Do not trigger collapse
event.preventDefault();
}}
>
<Dropdown
overlay={menu}
trigger={["click"]}
overlayClassName="stepMenu"
>
<div className={styles.addButtonContainer}>
<MLButton aria-label="add-ruleset" size="default" type="primary">
Add{" "}
<DownOutlined /></MLButton>
</div></Dropdown></div>
</div>
<div><span className={styles.editingLabel}><b>Edit Rulesets</b></span><Switch aria-label="ruleset-scale-switch" onChange={(e) => toggleDisplayRulesetTimeline(e)} defaultChecked={false} ></Switch>
<span>
<MLTooltip title={MatchingStepTooltips.rulesetScale} placement={"right"}>
<Icon type="question-circle" className={styles.scaleTooltip} theme="filled" data-testid={`info-tooltip-ruleset`}/>
</MLTooltip><br />
</span></div>
{displayRulesetTimeline ? renderRulesetTimeline() : renderDefaultRulesetTimeline()}
</div>
<div className={styles.stepNumberContainer}>
<NumberIcon value={3} />
<div className={styles.stepText}>Test and review matched entities</div>
</div>
<div className={styles.testMatch} aria-label="testMatch">
<MLRadio.MLGroup onChange={onTestMatchRadioChange} value={value} id="addDataRadio" className={styles.testMatchedRadioGroup}>
<span className={styles.borders}>
<MLRadio className={styles.urisData} value={1} aria-label="inputUriOnlyRadio" onClick={handleUriInputSelected} validateStatus={duplicateUriWarning || singleUriWarning ? "error" : ""}>
<span className={styles.radioTitle}>Test URIs</span>
<span className={styles.selectTooltip} aria-label="testUriOnlyTooltip">
<MLTooltip title={MatchingStepTooltips.testUris} placement={"right"}>
<Icon type="question-circle" className={styles.questionCircle} theme="filled"/>
</MLTooltip><br />
</span>
<MLInput
placeholder="Enter URI or Paste URIs"
className={styles.uriInput}
value={uriContent}
onChange={handleUriInputChange}
aria-label="UriOnlyInput"
disabled={inputUriDisabled}
/>
<FontAwesomeIcon icon={faPlusSquare} className={inputUriDisabled ? styles.disabledAddIcon : styles.addIcon} onClick={handleClickAddUri} aria-label="addUriOnlyIcon"/>
{duplicateUriWarning ? <div className={styles.duplicateUriWarning}>This URI has already been added.</div> : ""}
{singleUriWarning ? <div className={styles.duplicateUriWarning}>At least Two URIs are required.</div> : ""}
<div className={styles.UriTable}>
{UriTableData.length > 0 ? <MLTable
columns={UriColumns}
className={styles.tableContent}
dataSource={renderUriTableData}
rowKey="key"
id="uriData"
pagination={false}
/>:""}
</div>
</MLRadio></span>
<MLRadio value={2} className={styles.allDataUris} aria-label="inputUriRadio" onClick={handleUriInputSelected2} validateStatus={duplicateUriWarning || singleUriWarning ? "error" : ""}>
<span className={styles.radioTitle}>Test URIs with All Data</span>
<span aria-label="testUriTooltip"><MLTooltip title={MatchingStepTooltips.testUrisAllData} placement={"right"}>
<Icon type="question-circle" className={styles.questionCircle} theme="filled"/>
</MLTooltip></span><br />
<MLInput
placeholder="Enter URI or Paste URIs"
className={styles.uriInput}
value={uriContent2}
onChange={handleUriInputChange2}
aria-label="UriInput"
disabled={inputUriDisabled2}
/>
<FontAwesomeIcon icon={faPlusSquare} className={inputUriDisabled2 ? styles.disabledAddIcon : styles.addIcon} onClick={handleClickAddUri2} aria-label="addUriIcon"/>
{duplicateUriWarning2 ? <div className={styles.duplicateUriWarning}>This URI has already been added.</div> : ""}
{singleUriWarning2 ? <div className={styles.duplicateUriWarning}>At least one URI is required.</div> : ""}
<div className={styles.UriTable}>
{UriTableData2.length > 0 ? <MLTable
columns={UriColumns2}
className={styles.tableContent}
dataSource={renderUriTableData2}
rowKey="key"
id="uriData"
pagination={false}
/>:""}
</div>
</MLRadio>
<MLRadio value={3} className={styles.allDataRadio} onClick={handleAllDataRadioClick} aria-label="allDataRadio">
<span>Test All Data</span>
<span aria-label={"allDataTooltip"}><MLTooltip title={MatchingStepTooltips.testAllData} placement={"right"}>
<Icon type="question-circle" className={styles.questionCircle} theme="filled"/>
</MLTooltip></span>
<div aria-label="allDataContent"><br />
Select All Data in your source query in order to preview matching activity against all URIs up to 100 displayed pair matches. It is best practice to test with a smaller-sized source query.
</div>
</MLRadio>
</MLRadio.MLGroup>
<div className={styles.testButton}>
<MLButton type="primary" htmlType="submit" size="default" onClick={handleTestButtonClick} aria-label="testMatchUriButton">Test</MLButton>
</div>
</div>
{/*<div className={styles.matchedTab}>*/}
{/* <Menu onClick={handleTestMatchTab} selectedKeys={[testMatchTab]} mode="horizontal" aria-label="testMatchTab">*/}
{/* <Menu.Item key="matched">Matched Entities</Menu.Item>*/}
{/* <Menu.Item key="notMatched">Not Matched</Menu.Item>*/}
{/* </Menu>*/}
{/*</div>*/}
{previewMatchedData === 0 && <div className={styles.noMatchedDataView} aria-label="noMatchedDataView"><span>No matches found. You can try: </span><br/>
<div className={styles.noMatchedDataContent}>
<span> Selecting a different test case</span><br/>
<span> Changing or adding more URIs</span><br/>
<span> Changing your match configuration. Preview matches in the Possible Combinations box</span>
</div>
</div>}
{previewMatchedActivity.actionPreview.length > 0 && testMatchTab === "matched" && uriTestMatchClicked ?
<div className={styles.UriMatchedDataTable}>
<div className={styles.modalTitleLegend} aria-label="modalTitleLegend">
<div className={styles.expandCollapseIcon}><ExpandCollapse handleSelection={(id) => handleExpandCollapse(id)} currentSelection={"collapse"} aria-label="expandCollapseIcon"/></div>
</div>
<Collapse activeKey={activeMatchedRuleset} onChange={handleRulesetCollapseChange}>
{rulesetDataList.map((rulesetDataList) => (
<Panel id="testMatchedPanel" key={rulesetDataList.rulesetName} header={
<div><span className={styles.matchRulesetStyle}>{rulesetDataList.rulesetName}</span>
<span className={styles.thresholdDisplay}> (Threshold: {rulesetDataList.score})</span>
<div className={styles.scoreDisplay}>{rulesetDataList.actionPreviewData.length} pair matches</div>
</div>
}>
<div className={styles.actionPreviewRows}>
<Collapse activeKey={activeMatchedUri} onChange={handleUrisCollapseChange} bordered={false}>
{rulesetDataList.actionPreviewData.map((actionPreviewData, index) => (
<Panel id="testMatchedUriDataPanel" key={actionPreviewData.name.concat(" - ") + actionPreviewData.action.concat("/") + index} header={
<span onClick={e => e.stopPropagation()}><div className={styles.uri1Position}>{actionPreviewData.uris[0]}<span className={styles.scoreDisplay}> (Score: {actionPreviewData.score})</span>
<span className={styles.compareButton}><MLButton type={"primary"} onClick={() => { handleCompareButton([actionPreviewData.uris[0], actionPreviewData.uris[1]]); }} aria-label={actionPreviewData.uris[0].substr(0, 41) + " compareButton"}>Compare</MLButton></span>
</div>
<div className={styles.uri2Position}>{actionPreviewData.uris[1]}</div></span>
}>
<span aria-label="expandedTableView"><ExpandableTableView rowData={actionPreviewData} allRuleset={curationOptions.activeStep.stepArtifact.matchRulesets} entityData={curationOptions.activeStep}/></span>
</Panel>))}
</Collapse>
</div>
</Panel>
))}
</Collapse>
</div> : ""}
</div>
<RulesetSingleModal
isVisible={showRulesetSingleModal}
editRuleset={editRuleset}
toggleModal={toggleShowRulesetSingleModal}
/>
<RulesetMultipleModal
isVisible={showRulesetMultipleModal}
editRuleset={editRuleset}
toggleModal={toggleShowRulesetMultipleModal}
/>
<CompareValuesModal
isVisible={compareModalVisible}
toggleModal={setCompareModalVisible}
uriInfo = {uriInfo}
activeStepDetails={curationOptions.activeStep}
entityProperties={entityProperties}
uriCompared={urisCompared}
previewMatchActivity={previewMatchedActivity}
entityDefinitionsArray={curationOptions.entityDefinitionsArray}
uris={uris}
/>
<ThresholdModal
isVisible={showThresholdModal}
editThreshold={editThreshold}
toggleModal={toggleShowThresholdModal}
/>
</>
);
};
export default MatchingStepDetail; | the_stack |
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes';
import { DisposableStore } from 'vs/base/common/lifecycle';
import { ICodeEditor } from 'vs/editor/browser/editorBrowser';
import { EditorCommand, registerEditorCommand, registerEditorContribution } from 'vs/editor/browser/editorExtensions';
import { Position } from 'vs/editor/common/core/position';
import { Range } from 'vs/editor/common/core/range';
import { IEditorContribution } from 'vs/editor/common/editorCommon';
import { EditorContextKeys } from 'vs/editor/common/editorContextKeys';
import { CompletionItem, CompletionItemKind, CompletionItemProvider, SnippetTextEdit } from 'vs/editor/common/languages';
import { ILanguageConfigurationService } from 'vs/editor/common/languages/languageConfigurationRegistry';
import { ITextModel } from 'vs/editor/common/model';
import { ILanguageFeaturesService } from 'vs/editor/common/services/languageFeatures';
import { Choice } from 'vs/editor/contrib/snippet/browser/snippetParser';
import { showSimpleSuggestions } from 'vs/editor/contrib/suggest/browser/suggest';
import { OvertypingCapturer } from 'vs/editor/contrib/suggest/browser/suggestOvertypingCapturer';
import { localize } from 'vs/nls';
import { ContextKeyExpr, IContextKey, IContextKeyService, RawContextKey } from 'vs/platform/contextkey/common/contextkey';
import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry';
import { ILogService } from 'vs/platform/log/common/log';
import { SnippetSession } from './snippetSession';
export interface ISnippetInsertOptions {
overwriteBefore: number;
overwriteAfter: number;
adjustWhitespace: boolean;
undoStopBefore: boolean;
undoStopAfter: boolean;
clipboardText: string | undefined;
overtypingCapturer: OvertypingCapturer | undefined;
}
const _defaultOptions: ISnippetInsertOptions = {
overwriteBefore: 0,
overwriteAfter: 0,
undoStopBefore: true,
undoStopAfter: true,
adjustWhitespace: true,
clipboardText: undefined,
overtypingCapturer: undefined
};
export class SnippetController2 implements IEditorContribution {
public static readonly ID = 'snippetController2';
static get(editor: ICodeEditor): SnippetController2 | null {
return editor.getContribution<SnippetController2>(SnippetController2.ID);
}
static readonly InSnippetMode = new RawContextKey('inSnippetMode', false, localize('inSnippetMode', "Whether the editor in current in snippet mode"));
static readonly HasNextTabstop = new RawContextKey('hasNextTabstop', false, localize('hasNextTabstop', "Whether there is a next tab stop when in snippet mode"));
static readonly HasPrevTabstop = new RawContextKey('hasPrevTabstop', false, localize('hasPrevTabstop', "Whether there is a previous tab stop when in snippet mode"));
private readonly _inSnippet: IContextKey<boolean>;
private readonly _hasNextTabstop: IContextKey<boolean>;
private readonly _hasPrevTabstop: IContextKey<boolean>;
private _session?: SnippetSession;
private _snippetListener = new DisposableStore();
private _modelVersionId: number = -1;
private _currentChoice?: Choice;
private _choiceCompletionItemProvider?: CompletionItemProvider;
constructor(
private readonly _editor: ICodeEditor,
@ILogService private readonly _logService: ILogService,
@ILanguageFeaturesService private readonly _languageFeaturesService: ILanguageFeaturesService,
@IContextKeyService contextKeyService: IContextKeyService,
@ILanguageConfigurationService private readonly _languageConfigurationService: ILanguageConfigurationService,
) {
this._inSnippet = SnippetController2.InSnippetMode.bindTo(contextKeyService);
this._hasNextTabstop = SnippetController2.HasNextTabstop.bindTo(contextKeyService);
this._hasPrevTabstop = SnippetController2.HasPrevTabstop.bindTo(contextKeyService);
}
dispose(): void {
this._inSnippet.reset();
this._hasPrevTabstop.reset();
this._hasNextTabstop.reset();
this._session?.dispose();
this._snippetListener.dispose();
}
insert(
template: string,
opts?: Partial<ISnippetInsertOptions>
): void {
// this is here to find out more about the yet-not-understood
// error that sometimes happens when we fail to inserted a nested
// snippet
try {
this._doInsert(template, typeof opts === 'undefined' ? _defaultOptions : { ..._defaultOptions, ...opts });
} catch (e) {
this.cancel();
this._logService.error(e);
this._logService.error('snippet_error');
this._logService.error('insert_template=', template);
this._logService.error('existing_template=', this._session ? this._session._logInfo() : '<no_session>');
}
}
private _doInsert(
template: string,
opts: ISnippetInsertOptions
): void {
if (!this._editor.hasModel()) {
return;
}
// don't listen while inserting the snippet
// as that is the inflight state causing cancelation
this._snippetListener.clear();
if (opts.undoStopBefore) {
this._editor.getModel().pushStackElement();
}
if (!this._session) {
this._modelVersionId = this._editor.getModel().getAlternativeVersionId();
this._session = new SnippetSession(this._editor, template, opts, this._languageConfigurationService);
this._session.insert();
} else {
this._session.merge(template, opts);
}
if (opts.undoStopAfter) {
this._editor.getModel().pushStackElement();
}
// regster completion item provider when there is any choice element
if (this._session?.hasChoice) {
this._choiceCompletionItemProvider = {
provideCompletionItems: (model: ITextModel, position: Position) => {
if (!this._session || model !== this._editor.getModel() || !Position.equals(this._editor.getPosition(), position)) {
return undefined;
}
const { activeChoice } = this._session;
if (!activeChoice || activeChoice.options.length === 0) {
return undefined;
}
const info = model.getWordUntilPosition(position);
const isAnyOfOptions = Boolean(activeChoice.options.find(o => o.value === info.word));
const suggestions: CompletionItem[] = [];
for (let i = 0; i < activeChoice.options.length; i++) {
const option = activeChoice.options[i];
suggestions.push({
kind: CompletionItemKind.Value,
label: option.value,
insertText: option.value,
sortText: 'a'.repeat(i + 1),
range: new Range(position.lineNumber, info.startColumn, position.lineNumber, info.endColumn),
filterText: isAnyOfOptions ? `${info.word}_${option.value}` : undefined,
command: { id: 'jumpToNextSnippetPlaceholder', title: localize('next', 'Go to next placeholder...') }
});
}
return { suggestions };
}
};
const registration = this._languageFeaturesService.completionProvider.register({
language: this._editor.getModel().getLanguageId(),
pattern: this._editor.getModel().uri.path,
scheme: this._editor.getModel().uri.scheme
}, this._choiceCompletionItemProvider);
this._snippetListener.add(registration);
}
this._updateState();
this._snippetListener.add(this._editor.onDidChangeModelContent(e => e.isFlush && this.cancel()));
this._snippetListener.add(this._editor.onDidChangeModel(() => this.cancel()));
this._snippetListener.add(this._editor.onDidChangeCursorSelection(() => this._updateState()));
}
private _updateState(): void {
if (!this._session || !this._editor.hasModel()) {
// canceled in the meanwhile
return;
}
if (this._modelVersionId === this._editor.getModel().getAlternativeVersionId()) {
// undo until the 'before' state happened
// and makes use cancel snippet mode
return this.cancel();
}
if (!this._session.hasPlaceholder) {
// don't listen for selection changes and don't
// update context keys when the snippet is plain text
return this.cancel();
}
if (this._session.isAtLastPlaceholder || !this._session.isSelectionWithinPlaceholders()) {
this._editor.getModel().pushStackElement();
return this.cancel();
}
this._inSnippet.set(true);
this._hasPrevTabstop.set(!this._session.isAtFirstPlaceholder);
this._hasNextTabstop.set(!this._session.isAtLastPlaceholder);
this._handleChoice();
}
private _handleChoice(): void {
if (!this._session || !this._editor.hasModel()) {
this._currentChoice = undefined;
return;
}
const { activeChoice } = this._session;
if (!activeChoice || !this._choiceCompletionItemProvider) {
this._currentChoice = undefined;
return;
}
if (this._currentChoice !== activeChoice) {
this._currentChoice = activeChoice;
// trigger suggest with the special choice completion provider
queueMicrotask(() => {
showSimpleSuggestions(this._editor, this._choiceCompletionItemProvider!);
});
}
}
finish(): void {
while (this._inSnippet.get()) {
this.next();
}
}
cancel(resetSelection: boolean = false): void {
this._inSnippet.reset();
this._hasPrevTabstop.reset();
this._hasNextTabstop.reset();
this._snippetListener.clear();
this._currentChoice = undefined;
this._session?.dispose();
this._session = undefined;
this._modelVersionId = -1;
if (resetSelection) {
// reset selection to the primary cursor when being asked
// for. this happens when explicitly cancelling snippet mode,
// e.g. when pressing ESC
this._editor.setSelections([this._editor.getSelection()!]);
}
}
prev(): void {
if (this._session) {
this._session.prev();
}
this._updateState();
}
next(): void {
if (this._session) {
this._session.next();
}
this._updateState();
}
isInSnippet(): boolean {
return Boolean(this._inSnippet.get());
}
getSessionEnclosingRange(): Range | undefined {
if (this._session) {
return this._session.getEnclosingRange();
}
return undefined;
}
}
registerEditorContribution(SnippetController2.ID, SnippetController2);
const CommandCtor = EditorCommand.bindToContribution<SnippetController2>(SnippetController2.get);
registerEditorCommand(new CommandCtor({
id: 'jumpToNextSnippetPlaceholder',
precondition: ContextKeyExpr.and(SnippetController2.InSnippetMode, SnippetController2.HasNextTabstop),
handler: ctrl => ctrl.next(),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 30,
kbExpr: EditorContextKeys.editorTextFocus,
primary: KeyCode.Tab
}
}));
registerEditorCommand(new CommandCtor({
id: 'jumpToPrevSnippetPlaceholder',
precondition: ContextKeyExpr.and(SnippetController2.InSnippetMode, SnippetController2.HasPrevTabstop),
handler: ctrl => ctrl.prev(),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 30,
kbExpr: EditorContextKeys.editorTextFocus,
primary: KeyMod.Shift | KeyCode.Tab
}
}));
registerEditorCommand(new CommandCtor({
id: 'leaveSnippet',
precondition: SnippetController2.InSnippetMode,
handler: ctrl => ctrl.cancel(true),
kbOpts: {
weight: KeybindingWeight.EditorContrib + 30,
kbExpr: EditorContextKeys.editorTextFocus,
primary: KeyCode.Escape,
secondary: [KeyMod.Shift | KeyCode.Escape]
}
}));
registerEditorCommand(new CommandCtor({
id: 'acceptSnippet',
precondition: SnippetController2.InSnippetMode,
handler: ctrl => ctrl.finish(),
// kbOpts: {
// weight: KeybindingWeight.EditorContrib + 30,
// kbExpr: EditorContextKeys.textFocus,
// primary: KeyCode.Enter,
// }
}));
// ---
export function performSnippetEdit(editor: ICodeEditor, edit: SnippetTextEdit) {
const controller = SnippetController2.get(editor);
if (!controller) {
return false;
}
editor.focus();
editor.setSelection(edit.range);
controller.insert(edit.snippet);
return controller.isInSnippet();
} | the_stack |
import { RuntimeError, normalizeAngle, prefix } from './util';
import { GroupAttributes, RenderContext, TextMeasure } from './rendercontext';
// eslint-disable-next-line
type Attributes = { [key: string]: any };
const attrNamesToIgnoreMap: { [nodeName: string]: Attributes } = {
path: {
x: true,
y: true,
width: true,
height: true,
'font-family': true,
'font-weight': true,
'font-style': true,
'font-size': true,
},
rect: {
'font-family': true,
'font-weight': true,
'font-style': true,
'font-size': true,
},
text: {
width: true,
height: true,
},
};
/** Create the SVG in the SVG namespace. */
const SVG_NS = 'http://www.w3.org/2000/svg';
const TWO_PI = 2 * Math.PI;
interface State {
state: Attributes;
attributes: Attributes;
shadow_attributes: Attributes;
lineWidth: number;
}
class MeasureTextCache {
protected txt?: SVGTextElement;
// The cache is keyed first by the text string, then by the font attributes
// joined together.
protected cache: Record<string, Record<string, TextMeasure>> = {};
lookup(text: string, svg: SVGSVGElement, attributes: Attributes): TextMeasure {
let entries = this.cache[text];
if (entries === undefined) {
entries = {};
this.cache[text] = entries;
}
const family = attributes['font-family'];
const size = attributes['font-size'];
const style = attributes['font-style'];
const weight = attributes['font-weight'];
const key = `${family}%${size}%${style}%${weight}`;
let entry = entries[key];
if (entry === undefined) {
entry = this.measureImpl(text, svg, attributes);
entries[key] = entry;
}
return entry;
}
measureImpl(text: string, svg: SVGSVGElement, attributes: Attributes): TextMeasure {
let txt = this.txt;
if (!txt) {
// Create the SVG text element that will be used to measure text in the event
// of a cache miss.
txt = document.createElementNS(SVG_NS, 'text');
this.txt = txt;
}
txt.textContent = text;
txt.setAttributeNS(null, 'font-family', attributes['font-family']);
txt.setAttributeNS(null, 'font-size', attributes['font-size']);
txt.setAttributeNS(null, 'font-style', attributes['font-style']);
txt.setAttributeNS(null, 'font-weight', attributes['font-weight']);
svg.appendChild(txt);
const bbox = txt.getBBox();
svg.removeChild(txt);
// Remove the trailing 'pt' from the font size and scale to convert from points
// to canvas units.
// CSS specifies dpi to be 96 and there are 72 points to an inch: 96/72 == 4/3.
const fontSize = attributes['font-size'];
const height = (fontSize.substring(0, fontSize.length - 2) * 4) / 3;
return {
width: bbox.width,
height: height,
};
}
}
/**
* SVG rendering context with an API similar to CanvasRenderingContext2D.
*/
export class SVGContext extends RenderContext {
protected static measureTextCache = new MeasureTextCache();
element: HTMLElement; // the parent DOM object
svg: SVGSVGElement;
width: number = 0;
height: number = 0;
path: string;
pen: { x: number; y: number };
lineWidth: number;
attributes: Attributes;
background_attributes: Attributes;
shadow_attributes: Attributes;
state: Attributes;
state_stack: State[];
parent: SVGGElement;
groups: SVGGElement[];
fontString: string = '';
constructor(element: HTMLElement) {
super();
this.element = element;
const svg = this.create('svg');
// Add it to the canvas:
this.element.appendChild(svg);
// Point to it:
this.svg = svg;
this.groups = [this.svg]; // Create the group stack
this.parent = this.svg;
this.path = '';
this.pen = { x: NaN, y: NaN };
this.lineWidth = 1.0;
this.state = {
scale: { x: 1, y: 1 },
'font-family': 'Arial',
'font-size': '8pt',
'font-weight': 'normal',
};
const defaultAttributes = {
'stroke-dasharray': 'none',
'font-family': 'Arial',
'font-size': '10pt',
'font-weight': 'normal',
'font-style': 'normal',
};
this.attributes = {
'stroke-width': 0.3,
fill: 'black',
stroke: 'black',
...defaultAttributes,
};
this.background_attributes = {
'stroke-width': 0,
fill: 'white',
stroke: 'white',
...defaultAttributes,
};
this.shadow_attributes = {
width: 0,
color: 'black',
};
this.state_stack = [];
}
/**
* Use one of the overload signatures to create an SVG element of a specific type.
* The last overload accepts an arbitrary string, and is identical to the
* implementation signature.
* Feel free to add new overloads for other SVG element types as required.
*/
create(svgElementType: 'g'): SVGGElement;
create(svgElementType: 'path'): SVGPathElement;
create(svgElementType: 'rect'): SVGRectElement;
create(svgElementType: 'svg'): SVGSVGElement;
create(svgElementType: 'text'): SVGTextElement;
create(svgElementType: string): SVGElement;
create(svgElementType: string): SVGElement {
return document.createElementNS(SVG_NS, svgElementType);
}
// Allow grouping elements in containers for interactivity.
openGroup(cls: string, id?: string, attrs?: GroupAttributes): SVGGElement {
const group = this.create('g');
this.groups.push(group);
this.parent.appendChild(group);
this.parent = group;
if (cls) group.setAttribute('class', prefix(cls));
if (id) group.setAttribute('id', prefix(id));
if (attrs && attrs.pointerBBox) {
group.setAttribute('pointer-events', 'bounding-box');
}
return group;
}
closeGroup(): void {
this.groups.pop();
this.parent = this.groups[this.groups.length - 1];
}
add(elem: SVGElement): void {
this.parent.appendChild(elem);
}
// ### Styling & State Methods:
setFont(family: string, size: number, weight?: string): this {
// In SVG italic is handled by font-style.
// We search the weight argument and apply bold and italic
// to font-weight and font-style respectively.
let foundBold = false;
let foundItalic = false;
// Weight might also be a number (200, 400, etc...) so we
// test its type to be sure we have access to String methods.
if (typeof weight === 'string') {
// look for "italic" in the weight:
if (weight.indexOf('italic') !== -1) {
weight = weight.replace(/italic/g, '');
foundItalic = true;
}
// look for "bold" in weight
if (weight.indexOf('bold') !== -1) {
weight = weight.replace(/bold/g, '');
foundBold = true;
}
// remove any remaining spaces
weight = weight.replace(/ /g, '');
}
const noWeightProvided = typeof weight === 'undefined' || weight === '';
if (noWeightProvided) {
weight = 'normal';
}
const fontAttributes = {
'font-family': family,
'font-size': size + 'pt',
'font-weight': foundBold ? 'bold' : weight,
'font-style': foundItalic ? 'italic' : 'normal',
};
// Currently this.fontString only supports size & family. See setRawFont().
this.fontString = `${size}pt ${family}`;
this.attributes = { ...this.attributes, ...fontAttributes };
this.state = { ...this.state, ...fontAttributes };
return this;
}
setRawFont(font: string): this {
this.fontString = font.trim();
// Assumes size first, splits on space -- which is presently
// how all existing modules are calling this.
const fontArray = this.fontString.split(' ');
const size = fontArray[0];
this.attributes['font-size'] = size;
this.state['font-size'] = size;
const family = fontArray[1];
this.attributes['font-family'] = family;
this.state['font-family'] = family;
return this;
}
setFillStyle(style: string): this {
this.attributes.fill = style;
return this;
}
setBackgroundFillStyle(style: string): this {
this.background_attributes.fill = style;
this.background_attributes.stroke = style;
return this;
}
setStrokeStyle(style: string): this {
this.attributes.stroke = style;
return this;
}
setShadowColor(color: string): this {
this.shadow_attributes.color = color;
return this;
}
/**
* @param blur A non-negative float specifying the level of shadow blur, where 0
* represents no blur and larger numbers represent increasingly more blur.
* @returns this
*/
setShadowBlur(blur: number): this {
this.shadow_attributes.width = blur;
return this;
}
/**
* @param width
* @returns this
*/
setLineWidth(width: number): this {
this.attributes['stroke-width'] = width;
this.lineWidth = width;
return this;
}
/**
* @param lineDash an array of integers in the form of [dash, space, dash, space, etc...]
* @returns this
*
* See: [SVG `stroke-dasharray` attribute](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray)
*/
setLineDash(lineDash: number[]): this {
if (Object.prototype.toString.call(lineDash) === '[object Array]') {
this.attributes['stroke-dasharray'] = lineDash.join(',');
return this;
} else {
throw new RuntimeError('ArgumentError', 'lineDash must be an array of integers.');
}
}
/**
* @param capType
* @returns this
*/
setLineCap(capType: CanvasLineCap): this {
this.attributes['stroke-linecap'] = capType;
return this;
}
// ### Sizing & Scaling Methods:
// TODO (GCR): See note at scale() -- separate our internal
// conception of pixel-based width/height from the style.width
// and style.height properties eventually to allow users to
// apply responsive sizing attributes to the SVG.
resize(width: number, height: number): this {
this.width = width;
this.height = height;
this.element.style.width = width.toString();
this.svg.style.width = width.toString();
this.svg.style.height = height.toString();
const attributes = {
width,
height,
};
this.applyAttributes(this.svg, attributes);
this.scale(this.state.scale.x, this.state.scale.y);
return this;
}
scale(x: number, y: number): this {
// uses viewBox to scale
// TODO (GCR): we may at some point want to distinguish the
// style.width / style.height properties that are applied to
// the SVG object from our internal conception of the SVG
// width/height. This would allow us to create automatically
// scaling SVG's that filled their containers, for instance.
//
// As this isn't implemented in Canvas contexts,
// I've left as is for now, but in using the viewBox to
// handle internal scaling, am trying to make it possible
// for us to eventually move in that direction.
this.state.scale = { x, y };
const visibleWidth = this.width / x;
const visibleHeight = this.height / y;
this.setViewBox(0, 0, visibleWidth, visibleHeight);
return this;
}
/**
* 1 arg: string in the "x y w h" format
* 4 args: x:number, y:number, w:number, h:number
*/
setViewBox(viewBox_or_minX: string | number, minY?: number, width?: number, height?: number): void {
if (typeof viewBox_or_minX === 'string') {
this.svg.setAttribute('viewBox', viewBox_or_minX);
} else {
const viewBoxString = viewBox_or_minX + ' ' + minY + ' ' + width + ' ' + height;
this.svg.setAttribute('viewBox', viewBoxString);
}
}
// ### Drawing helper methods:
applyAttributes(element: SVGElement, attributes: Attributes): SVGElement {
const attrNamesToIgnore = attrNamesToIgnoreMap[element.nodeName];
Object.keys(attributes).forEach((propertyName) => {
if (attrNamesToIgnore && attrNamesToIgnore[propertyName]) {
return;
}
element.setAttributeNS(null, propertyName, attributes[propertyName]);
});
return element;
}
// ### Shape & Path Methods:
clear(): void {
// Clear the SVG by removing all inner children.
// (This approach is usually slightly more efficient
// than removing the old SVG & adding a new one to
// the container element, since it does not cause the
// container to resize twice. Also, the resize
// triggered by removing the entire SVG can trigger
// a touchcancel event when the element resizes away
// from a touch point.)
while (this.svg.lastChild) {
this.svg.removeChild(this.svg.lastChild);
}
// Replace the viewbox attribute we just removed:
this.scale(this.state.scale.x, this.state.scale.y);
}
// ## Rectangles:
rect(x: number, y: number, width: number, height: number, attributes?: Attributes): this {
// Avoid invalid negative height attribs by
// flipping the rectangle on its head:
if (height < 0) {
y += height;
height *= -1;
}
// Create the rect & style it:
const rectangle = this.create('rect');
if (typeof attributes === 'undefined') {
attributes = {
fill: 'none',
'stroke-width': this.lineWidth,
stroke: 'black',
};
}
attributes = { ...attributes, x, y, width, height };
this.applyAttributes(rectangle, attributes);
this.add(rectangle);
return this;
}
fillRect(x: number, y: number, width: number, height: number): this {
const attributes = { fill: this.attributes.fill };
this.rect(x, y, width, height, attributes);
return this;
}
clearRect(x: number, y: number, width: number, height: number): this {
// TODO(GCR): Improve implementation of this...
// Currently it draws a box of the background color, rather
// than creating alpha through lower z-levels.
//
// See the implementation of this in SVGKit:
// http://sourceforge.net/projects/svgkit/
// as a starting point.
//
// Adding a large number of transform paths (as we would
// have to do) could be a real performance hit. Since
// tabNote seems to be the only module that makes use of this
// it may be worth creating a separate tabStave that would
// draw lines around locations of tablature fingering.
//
this.rect(x, y, width, height, this.background_attributes);
return this;
}
// ## Paths:
beginPath(): this {
this.path = '';
this.pen.x = NaN;
this.pen.y = NaN;
return this;
}
moveTo(x: number, y: number): this {
this.path += 'M' + x + ' ' + y;
this.pen.x = x;
this.pen.y = y;
return this;
}
lineTo(x: number, y: number): this {
this.path += 'L' + x + ' ' + y;
this.pen.x = x;
this.pen.y = y;
return this;
}
bezierCurveTo(x1: number, y1: number, x2: number, y2: number, x: number, y: number): this {
this.path += 'C' + x1 + ' ' + y1 + ',' + x2 + ' ' + y2 + ',' + x + ' ' + y;
this.pen.x = x;
this.pen.y = y;
return this;
}
quadraticCurveTo(x1: number, y1: number, x: number, y: number): this {
this.path += 'Q' + x1 + ' ' + y1 + ',' + x + ' ' + y;
this.pen.x = x;
this.pen.y = y;
return this;
}
arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, counterclockwise: boolean): this {
const x0 = x + radius * Math.cos(startAngle);
const y0 = y + radius * Math.sin(startAngle);
// Handle the edge case where arc length is greater than or equal to
// the circle's circumference:
// https://html.spec.whatwg.org/multipage/canvas.html#ellipse-method-steps
if (
(!counterclockwise && endAngle - startAngle >= TWO_PI) ||
(counterclockwise && startAngle - endAngle >= TWO_PI)
) {
const x1 = x + radius * Math.cos(startAngle + Math.PI);
const y1 = y + radius * Math.sin(startAngle + Math.PI);
// There's no way to specify a completely circular arc in SVG so we have to
// use two semi-circular arcs.
this.path += `M${x0} ${y0} A${radius} ${radius} 0 0 0 ${x1} ${y1} `;
this.path += `A${radius} ${radius} 0 0 0 ${x0} ${y0}`;
this.pen.x = x0;
this.pen.y = y0;
} else {
const x1 = x + radius * Math.cos(endAngle);
const y1 = y + radius * Math.sin(endAngle);
startAngle = normalizeAngle(startAngle);
endAngle = normalizeAngle(endAngle);
let large: boolean;
if (Math.abs(endAngle - startAngle) < Math.PI) {
large = counterclockwise;
} else {
large = !counterclockwise;
}
if (startAngle > endAngle) {
large = !large;
}
const sweep = !counterclockwise;
this.path += `M${x0} ${y0} A${radius} ${radius} 0 ${+large} ${+sweep} ${x1} ${y1}`;
this.pen.x = x1;
this.pen.y = y1;
}
return this;
}
closePath(): this {
this.path += 'Z';
return this;
}
private getShadowStyle(): string {
const sa = this.shadow_attributes;
// A CSS drop-shadow filter blur looks different than a canvas shadowBlur
// of the same radius, so we scale the drop-shadow radius here to make it
// look close to the canvas shadow.
return `filter: drop-shadow(0 0 ${sa.width / 1.5}px ${sa.color})`;
}
fill(attributes: Attributes): this {
const path = this.create('path');
if (typeof attributes === 'undefined') {
attributes = { ...this.attributes, stroke: 'none' };
}
attributes.d = this.path;
if (this.shadow_attributes.width > 0) {
attributes.style = this.getShadowStyle();
}
this.applyAttributes(path, attributes);
this.add(path);
return this;
}
stroke(): this {
const path = this.create('path');
const attributes: Attributes = {
...this.attributes,
fill: 'none',
'stroke-width': this.lineWidth,
d: this.path,
};
if (this.shadow_attributes.width > 0) {
attributes.style = this.getShadowStyle();
}
this.applyAttributes(path, attributes);
this.add(path);
return this;
}
// ## Text Methods:
measureText(text: string): TextMeasure {
return SVGContext.measureTextCache.lookup(text, this.svg, this.attributes);
}
fillText(text: string, x: number, y: number): this {
if (!text || text.length <= 0) {
return this;
}
const attributes: Attributes = {
...this.attributes,
stroke: 'none',
x,
y,
};
const txt = this.create('text');
txt.textContent = text;
this.applyAttributes(txt, attributes);
this.add(txt);
return this;
}
save(): this {
// TODO(mmuthanna): State needs to be deep-copied.
this.state_stack.push({
state: {
'font-family': this.state['font-family'],
'font-weight': this.state['font-weight'],
'font-style': this.state['font-style'],
'font-size': this.state['font-size'],
scale: this.state.scale,
},
attributes: {
'font-family': this.attributes['font-family'],
'font-weight': this.attributes['font-weight'],
'font-style': this.attributes['font-style'],
'font-size': this.attributes['font-size'],
fill: this.attributes.fill,
stroke: this.attributes.stroke,
'stroke-width': this.attributes['stroke-width'],
'stroke-dasharray': this.attributes['stroke-dasharray'],
},
shadow_attributes: {
width: this.shadow_attributes.width,
color: this.shadow_attributes.color,
},
lineWidth: this.lineWidth,
});
return this;
}
restore(): this {
// TODO(0xfe): State needs to be deep-restored.
const savedState = this.state_stack.pop();
if (savedState) {
const state = savedState;
this.state['font-family'] = state.state['font-family'];
this.state['font-weight'] = state.state['font-weight'];
this.state['font-style'] = state.state['font-style'];
this.state['font-size'] = state.state['font-size'];
this.state.scale = state.state.scale;
this.attributes['font-family'] = state.attributes['font-family'];
this.attributes['font-weight'] = state.attributes['font-weight'];
this.attributes['font-style'] = state.attributes['font-style'];
this.attributes['font-size'] = state.attributes['font-size'];
this.attributes.fill = state.attributes.fill;
this.attributes.stroke = state.attributes.stroke;
this.attributes['stroke-width'] = state.attributes['stroke-width'];
this.attributes['stroke-dasharray'] = state.attributes['stroke-dasharray'];
this.shadow_attributes.width = state.shadow_attributes.width;
this.shadow_attributes.color = state.shadow_attributes.color;
this.lineWidth = state.lineWidth;
}
return this;
}
set font(value: string) {
this.setRawFont(value);
}
get font(): string {
return this.fontString;
}
set fillStyle(style: string | CanvasGradient | CanvasPattern) {
this.setFillStyle(style as string);
}
get fillStyle(): string | CanvasGradient | CanvasPattern {
return this.attributes.fill;
}
set strokeStyle(style: string | CanvasGradient | CanvasPattern) {
this.setStrokeStyle(style as string);
}
get strokeStyle(): string | CanvasGradient | CanvasPattern {
return this.attributes.stroke;
}
} | the_stack |
/*
* ---------------------------------------------------------
* Copyright(C) Microsoft Corporation. All rights reserved.
* ---------------------------------------------------------
*
* ---------------------------------------------------------
* Generated file, DO NOT EDIT
* ---------------------------------------------------------
*/
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
import * as restm from 'typed-rest-client/RestClient';
import vsom = require('./VsoClient');
import basem = require('./ClientApiBases');
import VsoBaseInterfaces = require('./interfaces/common/VsoBaseInterfaces');
import Comments_Contracts = require("./interfaces/CommentsInterfaces");
import GitInterfaces = require("./interfaces/GitInterfaces");
import VSSInterfaces = require("./interfaces/common/VSSInterfaces");
import WikiInterfaces = require("./interfaces/WikiInterfaces");
export interface IWikiApi extends basem.ClientApiBase {
createCommentAttachment(customHeaders: any, contentStream: NodeJS.ReadableStream, project: string, wikiIdentifier: string, pageId: number): Promise<Comments_Contracts.CommentAttachment>;
getAttachmentContent(project: string, wikiIdentifier: string, pageId: number, attachmentId: string): Promise<NodeJS.ReadableStream>;
addCommentReaction(project: string, wikiIdentifier: string, pageId: number, commentId: number, type: Comments_Contracts.CommentReactionType): Promise<Comments_Contracts.CommentReaction>;
deleteCommentReaction(project: string, wikiIdentifier: string, pageId: number, commentId: number, type: Comments_Contracts.CommentReactionType): Promise<Comments_Contracts.CommentReaction>;
getEngagedUsers(project: string, wikiIdentifier: string, pageId: number, commentId: number, type: Comments_Contracts.CommentReactionType, top?: number, skip?: number): Promise<VSSInterfaces.IdentityRef[]>;
addComment(request: Comments_Contracts.CommentCreateParameters, project: string, wikiIdentifier: string, pageId: number): Promise<Comments_Contracts.Comment>;
deleteComment(project: string, wikiIdentifier: string, pageId: number, id: number): Promise<void>;
getComment(project: string, wikiIdentifier: string, pageId: number, id: number, excludeDeleted?: boolean, expand?: Comments_Contracts.CommentExpandOptions): Promise<Comments_Contracts.Comment>;
listComments(project: string, wikiIdentifier: string, pageId: number, top?: number, continuationToken?: string, excludeDeleted?: boolean, expand?: Comments_Contracts.CommentExpandOptions, order?: Comments_Contracts.CommentSortOrder, parentId?: number): Promise<Comments_Contracts.CommentList>;
updateComment(comment: Comments_Contracts.CommentUpdateParameters, project: string, wikiIdentifier: string, pageId: number, id: number): Promise<Comments_Contracts.Comment>;
getPageText(project: string, wikiIdentifier: string, path?: string, recursionLevel?: GitInterfaces.VersionControlRecursionType, versionDescriptor?: GitInterfaces.GitVersionDescriptor, includeContent?: boolean): Promise<NodeJS.ReadableStream>;
getPageZip(project: string, wikiIdentifier: string, path?: string, recursionLevel?: GitInterfaces.VersionControlRecursionType, versionDescriptor?: GitInterfaces.GitVersionDescriptor, includeContent?: boolean): Promise<NodeJS.ReadableStream>;
getPageByIdText(project: string, wikiIdentifier: string, id: number, recursionLevel?: GitInterfaces.VersionControlRecursionType, includeContent?: boolean): Promise<NodeJS.ReadableStream>;
getPageByIdZip(project: string, wikiIdentifier: string, id: number, recursionLevel?: GitInterfaces.VersionControlRecursionType, includeContent?: boolean): Promise<NodeJS.ReadableStream>;
getPagesBatch(pagesBatchRequest: WikiInterfaces.WikiPagesBatchRequest, project: string, wikiIdentifier: string, versionDescriptor?: GitInterfaces.GitVersionDescriptor): Promise<WikiInterfaces.WikiPageDetail[]>;
getPageData(project: string, wikiIdentifier: string, pageId: number, pageViewsForDays?: number): Promise<WikiInterfaces.WikiPageDetail>;
createOrUpdatePageViewStats(project: string, wikiIdentifier: string, wikiVersion: GitInterfaces.GitVersionDescriptor, path: string, oldPath?: string): Promise<WikiInterfaces.WikiPageViewStats>;
createWiki(wikiCreateParams: WikiInterfaces.WikiCreateParametersV2, project?: string): Promise<WikiInterfaces.WikiV2>;
deleteWiki(wikiIdentifier: string, project?: string): Promise<WikiInterfaces.WikiV2>;
getAllWikis(project?: string): Promise<WikiInterfaces.WikiV2[]>;
getWiki(wikiIdentifier: string, project?: string): Promise<WikiInterfaces.WikiV2>;
updateWiki(updateParameters: WikiInterfaces.WikiUpdateParameters, wikiIdentifier: string, project?: string): Promise<WikiInterfaces.WikiV2>;
}
export class WikiApi extends basem.ClientApiBase implements IWikiApi {
constructor(baseUrl: string, handlers: VsoBaseInterfaces.IRequestHandler[], options?: VsoBaseInterfaces.IRequestOptions) {
super(baseUrl, handlers, 'node-Wiki-api', options);
}
public static readonly RESOURCE_AREA_ID = "bf7d82a0-8aa5-4613-94ef-6172a5ea01f3";
/**
* Uploads an attachment on a comment on a wiki page.
*
* @param {NodeJS.ReadableStream} contentStream - Content to upload
* @param {string} project - Project ID or project name
* @param {string} wikiIdentifier - Wiki ID or wiki name.
* @param {number} pageId - Wiki page ID.
*/
public async createCommentAttachment(
customHeaders: any,
contentStream: NodeJS.ReadableStream,
project: string,
wikiIdentifier: string,
pageId: number
): Promise<Comments_Contracts.CommentAttachment> {
return new Promise<Comments_Contracts.CommentAttachment>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier,
pageId: pageId
};
customHeaders = customHeaders || {};
customHeaders["Content-Type"] = "application/octet-stream";
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"wiki",
"5100d976-363d-42e7-a19d-4171ecb44782",
routeValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
options.additionalHeaders = customHeaders;
let res: restm.IRestResponse<Comments_Contracts.CommentAttachment>;
res = await this.rest.uploadStream<Comments_Contracts.CommentAttachment>("POST", url, contentStream, options);
let ret = this.formatResponse(res.result,
Comments_Contracts.TypeInfo.CommentAttachment,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Downloads an attachment on a comment on a wiki page.
*
* @param {string} project - Project ID or project name
* @param {string} wikiIdentifier - Wiki ID or wiki name.
* @param {number} pageId - Wiki page ID.
* @param {string} attachmentId - Attachment ID.
*/
public async getAttachmentContent(
project: string,
wikiIdentifier: string,
pageId: number,
attachmentId: string
): Promise<NodeJS.ReadableStream> {
return new Promise<NodeJS.ReadableStream>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier,
pageId: pageId,
attachmentId: attachmentId
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"wiki",
"5100d976-363d-42e7-a19d-4171ecb44782",
routeValues);
let url: string = verData.requestUrl!;
let apiVersion: string = verData.apiVersion!;
let accept: string = this.createAcceptHeader("application/octet-stream", apiVersion);
resolve((await this.http.get(url, { "Accept": accept })).message);
}
catch (err) {
reject(err);
}
});
}
/**
* Add a reaction on a wiki page comment.
*
* @param {string} project - Project ID or project name
* @param {string} wikiIdentifier - Wiki ID or wiki name
* @param {number} pageId - Wiki page ID
* @param {number} commentId - ID of the associated comment
* @param {Comments_Contracts.CommentReactionType} type - Type of the reaction being added
*/
public async addCommentReaction(
project: string,
wikiIdentifier: string,
pageId: number,
commentId: number,
type: Comments_Contracts.CommentReactionType
): Promise<Comments_Contracts.CommentReaction> {
return new Promise<Comments_Contracts.CommentReaction>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier,
pageId: pageId,
commentId: commentId,
type: type
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"wiki",
"7a5bc693-aab7-4d48-8f34-36f373022063",
routeValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<Comments_Contracts.CommentReaction>;
res = await this.rest.replace<Comments_Contracts.CommentReaction>(url, null, options);
let ret = this.formatResponse(res.result,
Comments_Contracts.TypeInfo.CommentReaction,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Delete a reaction on a wiki page comment.
*
* @param {string} project - Project ID or project name
* @param {string} wikiIdentifier - Wiki ID or name
* @param {number} pageId - Wiki page ID
* @param {number} commentId - ID of the associated comment
* @param {Comments_Contracts.CommentReactionType} type - Type of the reaction being deleted
*/
public async deleteCommentReaction(
project: string,
wikiIdentifier: string,
pageId: number,
commentId: number,
type: Comments_Contracts.CommentReactionType
): Promise<Comments_Contracts.CommentReaction> {
return new Promise<Comments_Contracts.CommentReaction>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier,
pageId: pageId,
commentId: commentId,
type: type
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"wiki",
"7a5bc693-aab7-4d48-8f34-36f373022063",
routeValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<Comments_Contracts.CommentReaction>;
res = await this.rest.del<Comments_Contracts.CommentReaction>(url, options);
let ret = this.formatResponse(res.result,
Comments_Contracts.TypeInfo.CommentReaction,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Gets a list of users who have reacted for the given wiki comment with a given reaction type. Supports paging, with a default page size of 100 users at a time.
*
* @param {string} project - Project ID or project name
* @param {string} wikiIdentifier - Wiki ID or wiki name.
* @param {number} pageId - Wiki page ID.
* @param {number} commentId - ID of the associated comment
* @param {Comments_Contracts.CommentReactionType} type - Type of the reaction for which the engaged users are being requested
* @param {number} top - Number of enagaged users to be returned in a given page. Optional, defaults to 100
* @param {number} skip - Number of engaged users to be skipped to page the next set of engaged users, defaults to 0
*/
public async getEngagedUsers(
project: string,
wikiIdentifier: string,
pageId: number,
commentId: number,
type: Comments_Contracts.CommentReactionType,
top?: number,
skip?: number
): Promise<VSSInterfaces.IdentityRef[]> {
return new Promise<VSSInterfaces.IdentityRef[]>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier,
pageId: pageId,
commentId: commentId,
type: type
};
let queryValues: any = {
'$top': top,
'$skip': skip,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"wiki",
"598a5268-41a7-4162-b7dc-344131e4d1fa",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<VSSInterfaces.IdentityRef[]>;
res = await this.rest.get<VSSInterfaces.IdentityRef[]>(url, options);
let ret = this.formatResponse(res.result,
null,
true);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Add a comment on a wiki page.
*
* @param {Comments_Contracts.CommentCreateParameters} request - Comment create request.
* @param {string} project - Project ID or project name
* @param {string} wikiIdentifier - Wiki ID or wiki name.
* @param {number} pageId - Wiki page ID.
*/
public async addComment(
request: Comments_Contracts.CommentCreateParameters,
project: string,
wikiIdentifier: string,
pageId: number
): Promise<Comments_Contracts.Comment> {
return new Promise<Comments_Contracts.Comment>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier,
pageId: pageId
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"wiki",
"9b394e93-7db5-46cb-9c26-09a36aa5c895",
routeValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<Comments_Contracts.Comment>;
res = await this.rest.create<Comments_Contracts.Comment>(url, request, options);
let ret = this.formatResponse(res.result,
Comments_Contracts.TypeInfo.Comment,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Delete a comment on a wiki page.
*
* @param {string} project - Project ID or project name
* @param {string} wikiIdentifier - Wiki ID or name.
* @param {number} pageId - Wiki page ID.
* @param {number} id - Comment ID.
*/
public async deleteComment(
project: string,
wikiIdentifier: string,
pageId: number,
id: number
): Promise<void> {
return new Promise<void>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier,
pageId: pageId,
id: id
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"wiki",
"9b394e93-7db5-46cb-9c26-09a36aa5c895",
routeValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<void>;
res = await this.rest.del<void>(url, options);
let ret = this.formatResponse(res.result,
null,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Returns a comment associated with the Wiki Page.
*
* @param {string} project - Project ID or project name
* @param {string} wikiIdentifier - Wiki ID or wiki name.
* @param {number} pageId - Wiki page ID.
* @param {number} id - ID of the comment to return.
* @param {boolean} excludeDeleted - Specify if the deleted comment should be skipped.
* @param {Comments_Contracts.CommentExpandOptions} expand - Specifies the additional data retrieval options for comments.
*/
public async getComment(
project: string,
wikiIdentifier: string,
pageId: number,
id: number,
excludeDeleted?: boolean,
expand?: Comments_Contracts.CommentExpandOptions
): Promise<Comments_Contracts.Comment> {
return new Promise<Comments_Contracts.Comment>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier,
pageId: pageId,
id: id
};
let queryValues: any = {
excludeDeleted: excludeDeleted,
'$expand': expand,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"wiki",
"9b394e93-7db5-46cb-9c26-09a36aa5c895",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<Comments_Contracts.Comment>;
res = await this.rest.get<Comments_Contracts.Comment>(url, options);
let ret = this.formatResponse(res.result,
Comments_Contracts.TypeInfo.Comment,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Returns a pageable list of comments.
*
* @param {string} project - Project ID or project name
* @param {string} wikiIdentifier - Wiki ID or wiki name.
* @param {number} pageId - Wiki page ID.
* @param {number} top - Max number of comments to return.
* @param {string} continuationToken - Used to query for the next page of comments.
* @param {boolean} excludeDeleted - Specify if the deleted comments should be skipped.
* @param {Comments_Contracts.CommentExpandOptions} expand - Specifies the additional data retrieval options for comments.
* @param {Comments_Contracts.CommentSortOrder} order - Order in which the comments should be returned.
* @param {number} parentId - CommentId of the parent comment.
*/
public async listComments(
project: string,
wikiIdentifier: string,
pageId: number,
top?: number,
continuationToken?: string,
excludeDeleted?: boolean,
expand?: Comments_Contracts.CommentExpandOptions,
order?: Comments_Contracts.CommentSortOrder,
parentId?: number
): Promise<Comments_Contracts.CommentList> {
return new Promise<Comments_Contracts.CommentList>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier,
pageId: pageId
};
let queryValues: any = {
'$top': top,
continuationToken: continuationToken,
excludeDeleted: excludeDeleted,
'$expand': expand,
order: order,
parentId: parentId,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"wiki",
"9b394e93-7db5-46cb-9c26-09a36aa5c895",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<Comments_Contracts.CommentList>;
res = await this.rest.get<Comments_Contracts.CommentList>(url, options);
let ret = this.formatResponse(res.result,
Comments_Contracts.TypeInfo.CommentList,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Update a comment on a wiki page.
*
* @param {Comments_Contracts.CommentUpdateParameters} comment - Comment update request.
* @param {string} project - Project ID or project name
* @param {string} wikiIdentifier - Wiki ID or wiki name.
* @param {number} pageId - Wiki page ID.
* @param {number} id - Comment ID.
*/
public async updateComment(
comment: Comments_Contracts.CommentUpdateParameters,
project: string,
wikiIdentifier: string,
pageId: number,
id: number
): Promise<Comments_Contracts.Comment> {
return new Promise<Comments_Contracts.Comment>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier,
pageId: pageId,
id: id
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"wiki",
"9b394e93-7db5-46cb-9c26-09a36aa5c895",
routeValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<Comments_Contracts.Comment>;
res = await this.rest.update<Comments_Contracts.Comment>(url, comment, options);
let ret = this.formatResponse(res.result,
Comments_Contracts.TypeInfo.Comment,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Gets metadata or content of the wiki page for the provided path. Content negotiation is done based on the `Accept` header sent in the request.
*
* @param {string} project - Project ID or project name
* @param {string} wikiIdentifier - Wiki ID or wiki name.
* @param {string} path - Wiki page path.
* @param {GitInterfaces.VersionControlRecursionType} recursionLevel - Recursion level for subpages retrieval. Defaults to `None` (Optional).
* @param {GitInterfaces.GitVersionDescriptor} versionDescriptor - GitVersionDescriptor for the page. Defaults to the default branch (Optional).
* @param {boolean} includeContent - True to include the content of the page in the response for Json content type. Defaults to false (Optional)
*/
public async getPageText(
project: string,
wikiIdentifier: string,
path?: string,
recursionLevel?: GitInterfaces.VersionControlRecursionType,
versionDescriptor?: GitInterfaces.GitVersionDescriptor,
includeContent?: boolean
): Promise<NodeJS.ReadableStream> {
return new Promise<NodeJS.ReadableStream>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier
};
let queryValues: any = {
path: path,
recursionLevel: recursionLevel,
versionDescriptor: versionDescriptor,
includeContent: includeContent,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"wiki",
"25d3fbc7-fe3d-46cb-b5a5-0b6f79caf27b",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let apiVersion: string = verData.apiVersion!;
let accept: string = this.createAcceptHeader("text/plain", apiVersion);
resolve((await this.http.get(url, { "Accept": accept })).message);
}
catch (err) {
reject(err);
}
});
}
/**
* Gets metadata or content of the wiki page for the provided path. Content negotiation is done based on the `Accept` header sent in the request.
*
* @param {string} project - Project ID or project name
* @param {string} wikiIdentifier - Wiki ID or wiki name.
* @param {string} path - Wiki page path.
* @param {GitInterfaces.VersionControlRecursionType} recursionLevel - Recursion level for subpages retrieval. Defaults to `None` (Optional).
* @param {GitInterfaces.GitVersionDescriptor} versionDescriptor - GitVersionDescriptor for the page. Defaults to the default branch (Optional).
* @param {boolean} includeContent - True to include the content of the page in the response for Json content type. Defaults to false (Optional)
*/
public async getPageZip(
project: string,
wikiIdentifier: string,
path?: string,
recursionLevel?: GitInterfaces.VersionControlRecursionType,
versionDescriptor?: GitInterfaces.GitVersionDescriptor,
includeContent?: boolean
): Promise<NodeJS.ReadableStream> {
return new Promise<NodeJS.ReadableStream>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier
};
let queryValues: any = {
path: path,
recursionLevel: recursionLevel,
versionDescriptor: versionDescriptor,
includeContent: includeContent,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"wiki",
"25d3fbc7-fe3d-46cb-b5a5-0b6f79caf27b",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let apiVersion: string = verData.apiVersion!;
let accept: string = this.createAcceptHeader("application/zip", apiVersion);
resolve((await this.http.get(url, { "Accept": accept })).message);
}
catch (err) {
reject(err);
}
});
}
/**
* Gets metadata or content of the wiki page for the provided page id. Content negotiation is done based on the `Accept` header sent in the request.
*
* @param {string} project - Project ID or project name
* @param {string} wikiIdentifier - Wiki ID or wiki name..
* @param {number} id - Wiki page ID.
* @param {GitInterfaces.VersionControlRecursionType} recursionLevel - Recursion level for subpages retrieval. Defaults to `None` (Optional).
* @param {boolean} includeContent - True to include the content of the page in the response for Json content type. Defaults to false (Optional)
*/
public async getPageByIdText(
project: string,
wikiIdentifier: string,
id: number,
recursionLevel?: GitInterfaces.VersionControlRecursionType,
includeContent?: boolean
): Promise<NodeJS.ReadableStream> {
return new Promise<NodeJS.ReadableStream>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier,
id: id
};
let queryValues: any = {
recursionLevel: recursionLevel,
includeContent: includeContent,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"wiki",
"ceddcf75-1068-452d-8b13-2d4d76e1f970",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let apiVersion: string = verData.apiVersion!;
let accept: string = this.createAcceptHeader("text/plain", apiVersion);
resolve((await this.http.get(url, { "Accept": accept })).message);
}
catch (err) {
reject(err);
}
});
}
/**
* Gets metadata or content of the wiki page for the provided page id. Content negotiation is done based on the `Accept` header sent in the request.
*
* @param {string} project - Project ID or project name
* @param {string} wikiIdentifier - Wiki ID or wiki name..
* @param {number} id - Wiki page ID.
* @param {GitInterfaces.VersionControlRecursionType} recursionLevel - Recursion level for subpages retrieval. Defaults to `None` (Optional).
* @param {boolean} includeContent - True to include the content of the page in the response for Json content type. Defaults to false (Optional)
*/
public async getPageByIdZip(
project: string,
wikiIdentifier: string,
id: number,
recursionLevel?: GitInterfaces.VersionControlRecursionType,
includeContent?: boolean
): Promise<NodeJS.ReadableStream> {
return new Promise<NodeJS.ReadableStream>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier,
id: id
};
let queryValues: any = {
recursionLevel: recursionLevel,
includeContent: includeContent,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"wiki",
"ceddcf75-1068-452d-8b13-2d4d76e1f970",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let apiVersion: string = verData.apiVersion!;
let accept: string = this.createAcceptHeader("application/zip", apiVersion);
resolve((await this.http.get(url, { "Accept": accept })).message);
}
catch (err) {
reject(err);
}
});
}
/**
* Returns pageable list of Wiki Pages
*
* @param {WikiInterfaces.WikiPagesBatchRequest} pagesBatchRequest - Wiki batch page request.
* @param {string} project - Project ID or project name
* @param {string} wikiIdentifier - Wiki ID or wiki name.
* @param {GitInterfaces.GitVersionDescriptor} versionDescriptor - GitVersionDescriptor for the page. (Optional in case of ProjectWiki).
*/
public async getPagesBatch(
pagesBatchRequest: WikiInterfaces.WikiPagesBatchRequest,
project: string,
wikiIdentifier: string,
versionDescriptor?: GitInterfaces.GitVersionDescriptor
): Promise<WikiInterfaces.WikiPageDetail[]> {
return new Promise<WikiInterfaces.WikiPageDetail[]>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier
};
let queryValues: any = {
versionDescriptor: versionDescriptor,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"wiki",
"71323c46-2592-4398-8771-ced73dd87207",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<WikiInterfaces.WikiPageDetail[]>;
res = await this.rest.create<WikiInterfaces.WikiPageDetail[]>(url, pagesBatchRequest, options);
let ret = this.formatResponse(res.result,
WikiInterfaces.TypeInfo.WikiPageDetail,
true);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Returns page detail corresponding to Page ID.
*
* @param {string} project - Project ID or project name
* @param {string} wikiIdentifier - Wiki ID or wiki name.
* @param {number} pageId - Wiki page ID.
* @param {number} pageViewsForDays - last N days from the current day for which page views is to be returned. It's inclusive of current day.
*/
public async getPageData(
project: string,
wikiIdentifier: string,
pageId: number,
pageViewsForDays?: number
): Promise<WikiInterfaces.WikiPageDetail> {
return new Promise<WikiInterfaces.WikiPageDetail>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier,
pageId: pageId
};
let queryValues: any = {
pageViewsForDays: pageViewsForDays,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"wiki",
"81c4e0fe-7663-4d62-ad46-6ab78459f274",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<WikiInterfaces.WikiPageDetail>;
res = await this.rest.get<WikiInterfaces.WikiPageDetail>(url, options);
let ret = this.formatResponse(res.result,
WikiInterfaces.TypeInfo.WikiPageDetail,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Creates a new page view stats resource or updates an existing page view stats resource.
*
* @param {string} project - Project ID or project name
* @param {string} wikiIdentifier - Wiki ID or wiki name.
* @param {GitInterfaces.GitVersionDescriptor} wikiVersion - Wiki version.
* @param {string} path - Wiki page path.
* @param {string} oldPath - Old page path. This is optional and required to rename path in existing page view stats.
*/
public async createOrUpdatePageViewStats(
project: string,
wikiIdentifier: string,
wikiVersion: GitInterfaces.GitVersionDescriptor,
path: string,
oldPath?: string
): Promise<WikiInterfaces.WikiPageViewStats> {
if (wikiVersion == null) {
throw new TypeError('wikiVersion can not be null or undefined');
}
if (path == null) {
throw new TypeError('path can not be null or undefined');
}
return new Promise<WikiInterfaces.WikiPageViewStats>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier
};
let queryValues: any = {
wikiVersion: wikiVersion,
path: path,
oldPath: oldPath,
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.1",
"wiki",
"1087b746-5d15-41b9-bea6-14e325e7f880",
routeValues,
queryValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<WikiInterfaces.WikiPageViewStats>;
res = await this.rest.create<WikiInterfaces.WikiPageViewStats>(url, null, options);
let ret = this.formatResponse(res.result,
WikiInterfaces.TypeInfo.WikiPageViewStats,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Creates the wiki resource.
*
* @param {WikiInterfaces.WikiCreateParametersV2} wikiCreateParams - Parameters for the wiki creation.
* @param {string} project - Project ID or project name
*/
public async createWiki(
wikiCreateParams: WikiInterfaces.WikiCreateParametersV2,
project?: string
): Promise<WikiInterfaces.WikiV2> {
return new Promise<WikiInterfaces.WikiV2>(async (resolve, reject) => {
let routeValues: any = {
project: project
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.2",
"wiki",
"288d122c-dbd4-451d-aa5f-7dbbba070728",
routeValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<WikiInterfaces.WikiV2>;
res = await this.rest.create<WikiInterfaces.WikiV2>(url, wikiCreateParams, options);
let ret = this.formatResponse(res.result,
WikiInterfaces.TypeInfo.WikiV2,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Deletes the wiki corresponding to the wiki ID or wiki name provided.
*
* @param {string} wikiIdentifier - Wiki ID or wiki name.
* @param {string} project - Project ID or project name
*/
public async deleteWiki(
wikiIdentifier: string,
project?: string
): Promise<WikiInterfaces.WikiV2> {
return new Promise<WikiInterfaces.WikiV2>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.2",
"wiki",
"288d122c-dbd4-451d-aa5f-7dbbba070728",
routeValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<WikiInterfaces.WikiV2>;
res = await this.rest.del<WikiInterfaces.WikiV2>(url, options);
let ret = this.formatResponse(res.result,
WikiInterfaces.TypeInfo.WikiV2,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Gets all wikis in a project or collection.
*
* @param {string} project - Project ID or project name
*/
public async getAllWikis(
project?: string
): Promise<WikiInterfaces.WikiV2[]> {
return new Promise<WikiInterfaces.WikiV2[]>(async (resolve, reject) => {
let routeValues: any = {
project: project
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.2",
"wiki",
"288d122c-dbd4-451d-aa5f-7dbbba070728",
routeValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<WikiInterfaces.WikiV2[]>;
res = await this.rest.get<WikiInterfaces.WikiV2[]>(url, options);
let ret = this.formatResponse(res.result,
WikiInterfaces.TypeInfo.WikiV2,
true);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Gets the wiki corresponding to the wiki ID or wiki name provided.
*
* @param {string} wikiIdentifier - Wiki ID or wiki name.
* @param {string} project - Project ID or project name
*/
public async getWiki(
wikiIdentifier: string,
project?: string
): Promise<WikiInterfaces.WikiV2> {
return new Promise<WikiInterfaces.WikiV2>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.2",
"wiki",
"288d122c-dbd4-451d-aa5f-7dbbba070728",
routeValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<WikiInterfaces.WikiV2>;
res = await this.rest.get<WikiInterfaces.WikiV2>(url, options);
let ret = this.formatResponse(res.result,
WikiInterfaces.TypeInfo.WikiV2,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
/**
* Updates the wiki corresponding to the wiki ID or wiki name provided using the update parameters.
*
* @param {WikiInterfaces.WikiUpdateParameters} updateParameters - Update parameters.
* @param {string} wikiIdentifier - Wiki ID or wiki name.
* @param {string} project - Project ID or project name
*/
public async updateWiki(
updateParameters: WikiInterfaces.WikiUpdateParameters,
wikiIdentifier: string,
project?: string
): Promise<WikiInterfaces.WikiV2> {
return new Promise<WikiInterfaces.WikiV2>(async (resolve, reject) => {
let routeValues: any = {
project: project,
wikiIdentifier: wikiIdentifier
};
try {
let verData: vsom.ClientVersioningData = await this.vsoClient.getVersioningData(
"6.1-preview.2",
"wiki",
"288d122c-dbd4-451d-aa5f-7dbbba070728",
routeValues);
let url: string = verData.requestUrl!;
let options: restm.IRequestOptions = this.createRequestOptions('application/json',
verData.apiVersion);
let res: restm.IRestResponse<WikiInterfaces.WikiV2>;
res = await this.rest.update<WikiInterfaces.WikiV2>(url, updateParameters, options);
let ret = this.formatResponse(res.result,
WikiInterfaces.TypeInfo.WikiV2,
false);
resolve(ret);
}
catch (err) {
reject(err);
}
});
}
} | the_stack |
import { history } from 'src/routes/routes'
import { fireEvent, render, screen, waitForElementToBeRemoved } from 'src/utils/test-utils'
import Stepper, { StepElement } from './Stepper'
describe('<Stepper>', () => {
it('Renders Stepper component', () => {
render(
<Stepper testId="stepper-component">
<StepElement label={'Step 1 label'}>
<div>Step 1 content</div>
</StepElement>
<StepElement label={'Step 2 label'}>
<div>Step 2 content</div>
</StepElement>
<StepElement label={'Final step label'}>
<div>Final step content</div>
</StepElement>
</Stepper>,
)
const stepperNode = screen.getByTestId('stepper-component')
expect(stepperNode).toBeInTheDocument()
})
it('Renders first step by default', () => {
render(
<Stepper testId="stepper-component">
<StepElement label={'Step 1 label'}>
<div>Step 1 content</div>
</StepElement>
<StepElement label={'Step 2 label'}>
<div>Step 2 content</div>
</StepElement>
<StepElement label={'Final step label'}>
<div>Final step content</div>
</StepElement>
</Stepper>,
)
const stepOneNode = screen.getByText('Step 1 content')
expect(stepOneNode).toBeInTheDocument()
expect(screen.queryByText('Step 2 content')).not.toBeInTheDocument()
expect(screen.queryByText('Final step content')).not.toBeInTheDocument()
})
it('Renders all step labels', () => {
render(
<Stepper testId="stepper-component">
<StepElement label={'Step 1 label'}>
<div>Step 1 content</div>
</StepElement>
<StepElement label={'Step 2 label'}>
<div>Step 2 content</div>
</StepElement>
<StepElement label={'Final step label'}>
<div>Final step content</div>
</StepElement>
</Stepper>,
)
const stepOneLabelNode = screen.getByText('Step 1 label')
expect(stepOneLabelNode).toBeInTheDocument()
const stepTwoLabelNode = screen.getByText('Step 2 label')
expect(stepTwoLabelNode).toBeInTheDocument()
const finalStepLabelNode = screen.getByText('Final step label')
expect(finalStepLabelNode).toBeInTheDocument()
})
describe('Navigation', () => {
describe('Next button', () => {
it('Renders next step when clicks on next button', async () => {
render(
<Stepper testId="stepper-component">
<StepElement label={'Step 1 label'}>
<div>Step 1 content</div>
</StepElement>
<StepElement label={'Step 2 label'}>
<div>Step 2 content</div>
</StepElement>
<StepElement label={'Final step label'}>
<div>Final step content</div>
</StepElement>
</Stepper>,
)
// Step 1
const stepOneNode = screen.getByText('Step 1 content')
expect(stepOneNode).toBeInTheDocument()
expect(screen.queryByText('Step 2 content')).not.toBeInTheDocument()
expect(screen.queryByText('Final step content')).not.toBeInTheDocument()
// Step 2
fireEvent.click(screen.getByText('Next'))
await waitForElementToBeRemoved(() => screen.queryByText('Step 1 content'))
const stepTwoNode = screen.getByText('Step 2 content')
expect(stepTwoNode).toBeInTheDocument()
expect(screen.queryByText('Step 1 content')).not.toBeInTheDocument()
expect(screen.queryByText('Final step content')).not.toBeInTheDocument()
// Final Step
fireEvent.click(screen.getByText('Next'))
await waitForElementToBeRemoved(() => screen.queryByText('Step 2 content'))
const finalStepNode = screen.getByText('Final step content')
expect(finalStepNode).toBeInTheDocument()
expect(screen.queryByText('Step 1 content')).not.toBeInTheDocument()
expect(screen.queryByText('Step 2 content')).not.toBeInTheDocument()
})
})
describe('Back button', () => {
it('Returns to the previous step clicking on back button', async () => {
render(
<Stepper testId="stepper-component">
<StepElement label={'Step 1 label'}>
<div>Step 1 content</div>
</StepElement>
<StepElement label={'Step 2 label'}>
<div>Step 2 content</div>
</StepElement>
<StepElement label={'Final step label'}>
<div>Final step content</div>
</StepElement>
</Stepper>,
)
// we start in the Step 2
fireEvent.click(screen.getByText('Next'))
await waitForElementToBeRemoved(() => screen.queryByText('Step 1 content'))
const stepTwoNode = screen.getByText('Step 2 content')
expect(stepTwoNode).toBeInTheDocument()
expect(screen.queryByText('Step 1 content')).not.toBeInTheDocument()
expect(screen.queryByText('Final step content')).not.toBeInTheDocument()
// we go back to the step 1
fireEvent.click(screen.getByText('Back'))
await waitForElementToBeRemoved(() => screen.queryByText('Step 2 content'))
expect(screen.getByText('Step 1 content')).toBeInTheDocument()
expect(screen.queryByText('Step 2 content')).not.toBeInTheDocument()
expect(screen.queryByText('Final step content')).not.toBeInTheDocument()
})
it('Returns to the previous screen if we are in the first step and click on Cancel button', () => {
const goBackSpy = jest.spyOn(history, 'goBack')
render(
<Stepper testId="stepper-component">
<StepElement label={'Step 1 label'}>
<div>Step 1 content</div>
</StepElement>
<StepElement label={'Step 2 label'}>
<div>Step 2 content</div>
</StepElement>
<StepElement label={'Final step label'}>
<div>Final step content</div>
</StepElement>
</Stepper>,
)
expect(goBackSpy).not.toHaveBeenCalled()
fireEvent.click(screen.getByText('Cancel'))
expect(goBackSpy).toHaveBeenCalled()
goBackSpy.mockRestore()
})
})
describe('Label navigation', () => {
it('Previous steps labels are clickable', () => {
render(
<Stepper testId="stepper-component">
<StepElement label={'Step 1 label'}>
<div>Step 1 content</div>
</StepElement>
<StepElement label={'Step 2 label'}>
<div>Step 2 content</div>
</StepElement>
<StepElement label={'Final step label'}>
<div>Final step content</div>
</StepElement>
</Stepper>,
)
const stepOneLabelNode = screen.getByText('Step 1 label')
const stepTwoLabelNode = screen.getByText('Step 2 label')
// we go to step 2
const nextButtonNode = screen.getByText('Next')
fireEvent.click(nextButtonNode)
// we can go again to step 1 by clicking on the label
expect(screen.getByText('Step 2 content'))
fireEvent.click(stepOneLabelNode)
expect(screen.getByText('Step 1 content'))
// we go to final step
fireEvent.click(nextButtonNode)
fireEvent.click(nextButtonNode)
expect(screen.getByText('Final step content'))
// we can go again to step 2 by clicking on the label
fireEvent.click(stepTwoLabelNode)
expect(screen.getByText('Step 2 content'))
// we go to final step again
fireEvent.click(nextButtonNode)
expect(screen.getByText('Final step content'))
// we can go again to step 1 by clicking on the label
fireEvent.click(stepOneLabelNode)
expect(screen.getByText('Step 1 content'))
})
it('Next steps labels are NOT clickable', () => {
render(
<Stepper testId="stepper-component">
<StepElement label={'Step 1 label'}>
<div>Step 1 content</div>
</StepElement>
<StepElement label={'Step 2 label'}>
<div>Step 2 content</div>
</StepElement>
<StepElement label={'Final step label'}>
<div>Final step content</div>
</StepElement>
</Stepper>,
)
const stepTwoLabelNode = screen.getByText('Step 2 label')
const finalStepLabelNode = screen.getByText('Final step label')
// we click on the Step 2 label and nothing happens
expect(screen.getByText('Step 1 content')).toBeInTheDocument()
fireEvent.click(stepTwoLabelNode)
expect(screen.getByText('Step 1 content')).toBeInTheDocument()
// we click on the Final Step label and nothing happens
expect(screen.getByText('Step 1 content')).toBeInTheDocument()
fireEvent.click(finalStepLabelNode)
expect(screen.getByText('Step 1 content')).toBeInTheDocument()
// we go to step 2 and check the final label is not clickable
const nextButtonNode = screen.getByText('Next')
fireEvent.click(nextButtonNode)
expect(screen.getByText('Step 2 content')).toBeInTheDocument()
fireEvent.click(finalStepLabelNode)
expect(screen.getByText('Step 2 content')).toBeInTheDocument()
})
})
})
it('Customize next button label', async () => {
const customNextButtonLabel = 'my next button custom label'
render(
<Stepper testId="stepper-component">
<StepElement label={'Step 1 label'} nextButtonLabel={customNextButtonLabel}>
<div>Step 1 content</div>
</StepElement>
<StepElement label={'Step 2 label'}>
<div>Step 2 content</div>
</StepElement>
<StepElement label={'Final step label'}>
<div>Final step content</div>
</StepElement>
</Stepper>,
)
expect(screen.getByText(customNextButtonLabel)).toBeInTheDocument()
expect(screen.queryByText('Next')).not.toBeInTheDocument()
})
it('Perform onFinish callback in the last step', async () => {
const onFinishSpy = jest.fn()
render(
<Stepper testId="stepper-component" onFinish={onFinishSpy}>
<StepElement label={'Step 1 label'}>
<div>Step 1 content</div>
</StepElement>
<StepElement label={'Step 2 label'}>
<div>Step 2 content</div>
</StepElement>
<StepElement label={'Final step label'}>
<div>Final step content</div>
</StepElement>
</Stepper>,
)
// we go to the final step
fireEvent.click(screen.getByText('Next'))
await waitForElementToBeRemoved(() => screen.queryByText('Step 1 content'))
fireEvent.click(screen.getByText('Next'))
await waitForElementToBeRemoved(() => screen.queryByText('Step 2 content'))
expect(screen.getByText('Final step content')).toBeInTheDocument()
expect(onFinishSpy).not.toHaveBeenCalled()
fireEvent.click(screen.getByText('Next'))
expect(onFinishSpy).toHaveBeenCalled()
})
}) | the_stack |
"use strict";
import * as assert from "assert";
import { Context, Dispatcher, Store, StoreGroup, UseCase } from "../src/";
import { createStore } from "./helper/create-new-store";
import { SyncNoDispatchUseCase } from "./use-case/SyncNoDispatchUseCase";
import { DispatchUseCase } from "./use-case/DispatchUseCase";
import { createUpdatableStoreWithUseCase } from "./helper/create-update-store-usecase";
import { AsyncUseCase } from "./use-case/AsyncUseCase";
import { DispatchedPayload } from "../src/Dispatcher";
import { StoreLike } from "../src/StoreLike";
import { TransactionBeganPayload } from "../src/payload/TransactionBeganPayload";
import { TransactionEndedPayload } from "../src/payload/TransactionEndedPayload";
import { Commitment } from "../src/UnitOfWork/UnitOfWork";
import sinon = require("sinon");
import { TransactionContext } from "../src/UnitOfWork/TransactionContext";
/**
* create a Store that can handle receivePayload
*/
const createReceivePayloadStore = (receivePayloadHandler: (payload: DispatchedPayload) => void): Store => {
class MockStore extends Store {
constructor() {
super();
this.state = {};
}
receivePayload(payload: DispatchedPayload) {
receivePayloadHandler(payload);
}
getState() {
return this.state;
}
}
return new MockStore();
};
describe("Context#transaction", () => {
describe("id", () => {
it("should be difference id between transactions", () => {
const aStore = createStore({ name: "test" });
const storeGroup = new StoreGroup({ a: aStore });
const dispatcher = new Dispatcher();
const context = new Context({
dispatcher,
store: storeGroup,
options: {
strict: true
}
});
const getTransactionId = (): Promise<string> => {
let id: string | null = null;
return context
.transaction("transaction", (transactionContext) => {
id = transactionContext.id;
transactionContext.exit();
return Promise.resolve();
})
.then(() => {
return id as string;
});
};
const transactionA = getTransactionId();
const transactionB = getTransactionId();
return Promise.all([transactionA, transactionB]).then(([aId, bId]) => {
assert.strictEqual(typeof aId, "string");
assert.strictEqual(typeof bId, "string");
assert.notStrictEqual(aId, bId);
});
});
});
context("Warning(Transaction):", () => {
let consoleErrorStub: null | sinon.SinonStub = null;
beforeEach(() => {
consoleErrorStub = sinon.stub(console, "error");
});
afterEach(() => {
consoleErrorStub!.restore();
});
it("should be warned when no-commit and no-exit in a transaction", function () {
const aStore = createStore({ name: "test" });
const storeGroup = new StoreGroup({ a: aStore });
const dispatcher = new Dispatcher();
const context = new Context({
dispatcher,
store: storeGroup,
options: {
strict: true
}
});
// 1st transaction
return context
.transaction("transaction", (_transactionContext) => {
return Promise.resolve();
})
.then(() => {
assert.strictEqual(consoleErrorStub!.callCount, 1);
});
});
});
context("Error Pattern", () => {
it("should throw error when return non-promise value in the transaction", function () {
const aStore = createStore({ name: "test" });
const storeGroup = new StoreGroup({ a: aStore });
const context = new Context({
dispatcher: new Dispatcher(),
store: storeGroup,
options: {
strict: true
}
});
return context
.transaction("transaction name", () => {
return null as any; // non-promise value
})
.then(
() => {
assert.fail("DON'T CALL");
},
(error: Error) => {
const expectedMessage = "Error(Transaction): transactionHandler should return promise.";
assert.ok(error.message.indexOf(expectedMessage) !== -1);
}
);
});
it("have unique id for in transactions", function () {
const aStore = createStore({ name: "test" });
const storeGroup = new StoreGroup({ a: aStore });
const context = new Context({
dispatcher: new Dispatcher(),
store: storeGroup,
options: {
strict: true
}
});
return context.transaction("transaction name", (transactionContext) => {
assert.strictEqual(typeof transactionContext.id, "string");
transactionContext.exit();
return Promise.resolve();
});
});
it("should throw error when do multiple exit in a transaction", function () {
const aStore = createStore({ name: "test" });
const storeGroup = new StoreGroup({ a: aStore });
const context = new Context({
dispatcher: new Dispatcher(),
store: storeGroup,
options: {
strict: true
}
});
return context
.transaction("transaction name", (transactionContext) => {
transactionContext.exit();
transactionContext.exit();
return Promise.resolve();
})
.then(
() => {
assert.fail("DON'T CALL");
},
(error: Error) => {
const expectedMessage = `Error(Transaction): This unit of work is already commit() or exit().`;
assert.ok(error.message.indexOf(expectedMessage) !== -1);
}
);
});
it("should throw error when do multiple commit in a transaction", function () {
const aStore = createStore({ name: "test" });
const storeGroup = new StoreGroup({ a: aStore });
const context = new Context({
dispatcher: new Dispatcher(),
store: storeGroup,
options: {
strict: true
}
});
return context
.transaction("transaction name", (transactionContext) => {
transactionContext.commit();
transactionContext.commit();
return Promise.resolve();
})
.then(
() => {
assert.fail("DON'T CALL");
},
(error: Error) => {
const expectedMessage = `Error(Transaction): This unit of work is already commit() or exit().`;
assert.ok(error.message.indexOf(expectedMessage) !== -1);
}
);
});
});
context("When two unit of work is running", () => {
it("should not lock the updating of StoreGroup", () => {
const { MockStore: TransactionStore, MockUseCase: TransactionUseCase } = createUpdatableStoreWithUseCase(
"TransactionTarget"
);
const { MockStore: UseCaseStore, MockUseCase: UseCaseUseCase } = createUpdatableStoreWithUseCase(
"UseCaseTarget"
);
const transactionStore = new TransactionStore();
const useCaseStore = new UseCaseStore();
const storeGroup = new StoreGroup({ transactionStore, useCaseStore });
class ChangeByTransactionUseCase extends TransactionUseCase {
execute(state: any) {
this.requestUpdateState(state);
}
}
class ChangeByUseCase extends UseCaseUseCase {
execute(state: any) {
this.requestUpdateState(state);
}
}
const context = new Context({
dispatcher: new Dispatcher(),
store: storeGroup,
options: {
strict: true
}
});
// then - called change handler a one-time
let onChangeCount = 0;
let changedStores: StoreLike[] = [];
context.onChange((stores) => {
onChangeCount++;
changedStores = changedStores.concat(stores);
});
const runUseCase = (context: Context<any>) => {
return context.useCase(new ChangeByUseCase()).executor((useCase) => useCase.execute("useCase"));
};
const runTransaction = (transactionContext: TransactionContext) => {
return transactionContext
.useCase(new ChangeByTransactionUseCase())
.executor((useCase) => useCase.execute("transaction"));
};
// when
// `transaction` should not lock store-group
// different unit of work can affect the singleton store-group
return context
.transaction("transaction name", (transactionContext) => {
// `context`
return runUseCase(context)
.then(() => {
assert.strictEqual(
onChangeCount,
1,
"ChangeByUseCase can change store group, because transaction don't lock"
);
})
.then(() => {
return runTransaction(transactionContext);
})
.then(() => {
transactionContext.commit();
});
})
.then(() => {
assert.equal(onChangeCount, 2);
assert.equal(changedStores.length, 2);
assert.deepEqual(context.getState(), { transactionStore: "transaction", useCaseStore: "useCase" });
});
});
});
it("should collect up StoreGroup commit", function () {
class AStore extends Store {
constructor() {
super();
this.state = {};
}
receivePayload(payload: DispatchedPayload & { body: any }) {
if (payload.type === "UPDATE") {
this.setState(payload.body);
}
}
getState() {
return this.state;
}
}
const aStore = new AStore();
const storeGroup = new StoreGroup({ a: aStore });
class ChangeAUseCase extends UseCase {
execute(state: any) {
this.dispatch({
type: "UPDATE",
body: state
});
}
}
const context = new Context({
dispatcher: new Dispatcher(),
store: storeGroup,
options: {
strict: true
}
});
// then - called change handler a one-time
let onChangeCount = 0;
let changedStores: StoreLike[] = [];
context.onChange((stores) => {
onChangeCount++;
changedStores = changedStores.concat(stores);
});
// when
return context
.transaction("transaction name", (transactionContext) => {
return transactionContext
.useCase(new ChangeAUseCase())
.execute(1)
.then(() => transactionContext.useCase(new ChangeAUseCase()).execute(2))
.then(() => transactionContext.useCase(new ChangeAUseCase()).execute(3))
.then(() => transactionContext.useCase(new ChangeAUseCase()).execute(4))
.then(() => transactionContext.useCase(new ChangeAUseCase()).execute(5))
.then(() => {
transactionContext.commit();
});
})
.then(() => {
assert.equal(onChangeCount, 1);
assert.equal(changedStores.length, 1);
assert.deepEqual(context.getState(), {
a: 5
});
});
});
it("should collect up StoreGroup commit", function () {
const { MockStore: AStore, MockUseCase: AUseCase } = createUpdatableStoreWithUseCase("A");
const { MockStore: BStore, MockUseCase: BUseCase } = createUpdatableStoreWithUseCase("B");
const { MockStore: CStore, MockUseCase: CUseCase } = createUpdatableStoreWithUseCase("C");
const aStore = new AStore();
const bStore = new BStore();
const cStore = new CStore();
const storeGroup = new StoreGroup({ a: aStore, b: bStore, c: cStore });
class ChangeAUseCase extends AUseCase {
execute() {
this.requestUpdateState(1);
}
}
class ChangeBUseCase extends BUseCase {
execute() {
this.requestUpdateState(1);
}
}
class ChangeCUseCase extends CUseCase {
execute() {
this.requestUpdateState(1);
}
}
const context = new Context({
dispatcher: new Dispatcher(),
store: storeGroup,
options: {
strict: true
}
});
// then - called change handler a one-time
let onChangeCount = 0;
let changedStores: StoreLike[] = [];
context.onChange((stores) => {
onChangeCount++;
changedStores = changedStores.concat(stores);
});
// when
return context
.transaction("transaction name", (transactionContext) => {
return transactionContext
.useCase(new ChangeAUseCase())
.execute()
.then(() => {
return transactionContext.useCase(new ChangeBUseCase()).execute();
})
.then(() => {
return transactionContext.useCase(new ChangeCUseCase()).execute();
})
.then(() => {
// 1st commit
transactionContext.commit();
});
})
.then(() => {
assert.equal(onChangeCount, 1);
assert.equal(changedStores.length, 3);
assert.deepEqual(context.getState(), {
a: 1,
b: 1,
c: 1
});
});
});
it("commit and each store#receivePayload is called", function () {
const receivedPayloadList: DispatchedPayload[] = [];
const aStore = createReceivePayloadStore((payload) => {
receivedPayloadList.push(payload);
});
const storeGroup = new StoreGroup({ a: aStore });
const context = new Context({
dispatcher: new Dispatcher(),
store: storeGroup,
options: {
strict: true
}
});
// reset initialized
receivedPayloadList.length = 0;
return context
.transaction("transaction name", (transactionContext) => {
assert.strictEqual(receivedPayloadList.length, 0, "no commitment");
// Sync && No Dispatch UseCase call receivedPayloadList at once
return transactionContext
.useCase(new SyncNoDispatchUseCase())
.execute()
.then(() => {
assert.strictEqual(receivedPayloadList.length, 0, "no commitment");
transactionContext.commit();
assert.strictEqual(receivedPayloadList.length, 1, "1 UseCase executed commitment");
});
})
.then(() => {
return context.transaction("nest transaction", (transactionContext) => {
// AsyncUseCase call receivedPayloadList twice
return transactionContext
.useCase(new AsyncUseCase())
.execute()
.then(() => {
assert.strictEqual(receivedPayloadList.length, 1, "before: 1 UseCase executed commitment");
transactionContext.commit();
assert.strictEqual(
receivedPayloadList.length,
3,
"after: Async UseCase add (did + complete) commitment"
);
});
});
});
});
it("can receive begin/end payload of transaction via Context", function () {
const aStore = createStore({ name: "test" });
const storeGroup = new StoreGroup({ a: aStore });
const dispatcher = new Dispatcher();
const context = new Context({
dispatcher,
store: storeGroup,
options: {
strict: true
}
});
const beginTransactions: TransactionBeganPayload[] = [];
const endTransaction: TransactionEndedPayload[] = [];
context.events.onBeginTransaction((payload, meta) => {
beginTransactions.push(payload);
assert.strictEqual(meta.isTrusted, true, "meta.isTrusted should be true");
assert.strictEqual(meta.useCase, null, "meta.useCase should be null");
assert.strictEqual(meta.parentUseCase, null, "meta.parentUseCase should be null");
assert.strictEqual(typeof meta.timeStamp, "number");
assert.strictEqual(typeof meta.transaction, "object", "transaction object");
assert.strictEqual(typeof (meta.transaction as any).name, "string", "transaction object");
});
context.events.onEndTransaction((payload, meta) => {
endTransaction.push(payload);
assert.strictEqual(meta.isTrusted, true, "meta.isTrusted should be true");
assert.strictEqual(meta.useCase, null, "meta.useCase should be null");
assert.strictEqual(meta.parentUseCase, null, "meta.parentUseCase should be null");
assert.strictEqual(typeof meta.timeStamp, "number");
assert.strictEqual(typeof meta.transaction, "object", "transaction object");
assert.strictEqual(typeof (meta.transaction as any).name, "string", "transaction object");
});
// 1st transaction
return context
.transaction("1st transaction", (transactionContext) => {
return transactionContext
.useCase(new SyncNoDispatchUseCase())
.execute()
.then(() => {
transactionContext.commit();
})
.then(() => {
assert.strictEqual(beginTransactions.length, 1);
// commit does end
assert.strictEqual(endTransaction.length, 1);
});
})
.then(() => {
// assert 1st
assert.strictEqual(beginTransactions.length, 1);
const [beginPayload] = beginTransactions;
assert.strictEqual(beginPayload.name, "1st transaction");
assert.strictEqual(endTransaction.length, 1);
const [endPayload] = endTransaction;
assert.strictEqual(endPayload.name, "1st transaction");
// 2nd transaction
return context.transaction("2nd transaction", (transactionContext) => {
return transactionContext
.useCase(new SyncNoDispatchUseCase())
.execute()
.then(() => {
transactionContext.commit();
})
.then(() => {
assert.strictEqual(beginTransactions.length, 2);
assert.strictEqual(endTransaction.length, 2);
});
});
})
.then(() => {
// assert 2nd
assert.strictEqual(beginTransactions.length, 2);
const [, beginPayload] = beginTransactions;
assert.strictEqual(beginPayload.name, "2nd transaction");
assert.strictEqual(endTransaction.length, 2);
const [, endPayload] = endTransaction;
assert.strictEqual(endPayload.name, "2nd transaction");
});
});
it("should meta.transaction is current transaction", function () {
const { MockStore: AStore, MockUseCase: AUseCase } = createUpdatableStoreWithUseCase("A");
const aStore = new AStore();
const storeGroup = new StoreGroup({ a: aStore });
const dispatcher = new Dispatcher();
const context = new Context({
dispatcher,
store: storeGroup,
options: {
strict: true
}
});
class ChangeAUseCase extends AUseCase {
execute() {
this.requestUpdateState(1);
}
}
const transactionName = "My Transaction";
dispatcher.onDispatch((_payload, meta) => {
if (!meta.transaction) {
throw new Error("Not found meta.transaction");
}
assert.strictEqual(typeof meta.transaction.id, "string");
assert.strictEqual(meta.transaction.name, transactionName);
});
// 1st transaction
return context.transaction(transactionName, (transactionContext) => {
return transactionContext
.useCase(new SyncNoDispatchUseCase())
.execute()
.then(() => {
return transactionContext.useCase(new DispatchUseCase()).execute({
type: "test"
});
})
.then(() => {
return transactionContext.useCase(new ChangeAUseCase()).execute();
})
.then(() => {
transactionContext.commit();
});
});
});
it(
"commit and each Store#onDispatch is not called," +
"because, Store#onDispatch receive only dispatched the Payload by UseCase#dispatch.",
function () {
const receivedCommitments: Commitment[] = [];
const aStore = createStore({ name: "test" });
aStore.onDispatch((payload, meta) => {
receivedCommitments.push({
payload,
meta,
debugId: "x"
});
});
const storeGroup = new StoreGroup({ a: aStore });
const context = new Context({
dispatcher: new Dispatcher(),
store: storeGroup,
options: {
strict: true
}
});
// reset initialized
receivedCommitments.length = 0;
return context
.transaction("transaction 1", (transactionContext) => {
assert.strictEqual(receivedCommitments.length, 0, "no commitment");
return transactionContext
.useCase(new SyncNoDispatchUseCase())
.execute()
.then(() => {
assert.strictEqual(receivedCommitments.length, 0, "no commitment");
transactionContext.commit();
assert.strictEqual(receivedCommitments.length, 0, "1 UseCase executed commitment");
});
})
.then(() => {
return context.transaction("transaction 2", (transactionContext) => {
return transactionContext
.useCase(new SyncNoDispatchUseCase())
.execute()
.then(() => {
assert.strictEqual(
receivedCommitments.length,
0,
"before: 1 UseCase executed commitment"
);
transactionContext.commit();
assert.strictEqual(
receivedCommitments.length,
0,
"after: 2 UseCase executed 2 commitment"
);
});
});
});
}
);
}); | the_stack |
import * as THREE from "three";
import {
combineLatest as observableCombineLatest,
concat as observableConcat,
merge as observableMerge,
of as observableOf,
Observable,
} from "rxjs";
import {
distinctUntilChanged,
first,
map,
pairwise,
publishReplay,
refCount,
skip,
startWith,
switchMap,
withLatestFrom,
} from "rxjs/operators";
import { Component } from "../Component";
import { Image } from "../../graph/Image";
import { Container } from "../../viewer/Container";
import { Navigator } from "../../viewer/Navigator";
import { LngLat } from "../../api/interfaces/LngLat";
import { LngLatAlt } from "../../api/interfaces/LngLatAlt";
import { ViewportCoords } from "../../geo/ViewportCoords";
import { GraphCalculator } from "../../graph/GraphCalculator";
import { RenderPass } from "../../render/RenderPass";
import { GLRenderHash } from "../../render/interfaces/IGLRenderHash";
import { RenderCamera } from "../../render/RenderCamera";
import { AnimationFrame } from "../../state/interfaces/AnimationFrame";
import { MarkerConfiguration } from "../interfaces/MarkerConfiguration";
import { Marker } from "./marker/Marker";
import { MarkerSet } from "./MarkerSet";
import { MarkerScene } from "./MarkerScene";
import { ComponentEventType } from "../events/ComponentEventType";
import {
enuToGeodetic,
geodeticToEnu,
} from "../../geo/GeoCoords";
import { ComponentMarkerEvent } from "../events/ComponentMarkerEvent";
import { ComponentEvent } from "../events/ComponentEvent";
import { ComponentName } from "../ComponentName";
/**
* @class MarkerComponent
*
* @classdesc Component for showing and editing 3D marker objects.
*
* The `add` method is used for adding new markers or replacing
* markers already in the set.
*
* If a marker already in the set has the same
* id as one of the markers added, the old marker will be removed and
* the added marker will take its place.
*
* It is not possible to update markers in the set by updating any properties
* directly on the marker object. Markers need to be replaced by
* re-adding them for updates to geographic position or configuration
* to be reflected.
*
* Markers added to the marker component can be either interactive
* or non-interactive. Different marker types define their behavior.
* Markers with interaction support can be configured with options
* to respond to dragging inside the viewer and be detected when
* retrieving markers from pixel points with the `getMarkerIdAt` method.
*
* To retrive and use the marker component
*
* @example
* ```js
* var viewer = new Viewer({ component: { marker: true }, ... });
*
* var markerComponent = viewer.getComponent("marker");
* ```
*/
export class MarkerComponent extends Component<MarkerConfiguration> {
public static componentName: ComponentName = "marker";
private _graphCalculator: GraphCalculator;
private _markerScene: MarkerScene;
private _markerSet: MarkerSet;
private _viewportCoords: ViewportCoords;
private _relativeGroundAltitude: number;
/** @ignore */
constructor(
name: string,
container: Container,
navigator: Navigator) {
super(name, container, navigator);
this._graphCalculator = new GraphCalculator();
this._markerScene = new MarkerScene();
this._markerSet = new MarkerSet();
this._viewportCoords = new ViewportCoords();
this._relativeGroundAltitude = -2;
}
/**
* Add markers to the marker set or replace markers in the marker set.
*
* @description If a marker already in the set has the same
* id as one of the markers added, the old marker will be removed
* the added marker will take its place.
*
* Any marker inside the visible bounding bbox
* will be initialized and placed in the viewer.
*
* @param {Array<Marker>} markers - Markers to add.
*
* @example
* ```js
* markerComponent.add([marker1, marker2]);
* ```
*/
public add(markers: Marker[]): void {
this._markerSet.add(markers);
}
public fire(
type:
| "markerdragend"
| "markerdragstart"
| "markerposition",
event: ComponentMarkerEvent)
: void;
/** @ignore */
public fire(
type: ComponentEventType,
event: ComponentEvent)
: void;
public fire<T>(
type: ComponentEventType,
event: T)
: void {
super.fire(type, event);
}
/**
* Returns the marker in the marker set with the specified id, or
* undefined if the id matches no marker.
*
* @param {string} markerId - Id of the marker.
*
* @example
* ```js
* var marker = markerComponent.get("markerId");
* ```
*
*/
public get(markerId: string): Marker {
return this._markerSet.get(markerId);
}
/**
* Returns an array of all markers.
*
* @example
* ```js
* var markers = markerComponent.getAll();
* ```
*/
public getAll(): Marker[] {
return this._markerSet.getAll();
}
/**
* Returns the id of the interactive marker closest to the current camera
* position at the specified point.
*
* @description Notice that the pixelPoint argument requires x, y
* coordinates from pixel space.
*
* With this function, you can use the coordinates provided by mouse
* events to get information out of the marker component.
*
* If no interactive geometry of an interactive marker exist at the pixel
* point, `null` will be returned.
*
* @param {Array<number>} pixelPoint - Pixel coordinates on the viewer element.
* @returns {string} Id of the interactive marker closest to the camera. If no
* interactive marker exist at the pixel point, `null` will be returned.
*
* @example
* ```js
* markerComponent.getMarkerIdAt([100, 100])
* .then((markerId) => { console.log(markerId); });
* ```
*/
public getMarkerIdAt(pixelPoint: number[]): Promise<string> {
return new Promise<string>((resolve: (value: string) => void, reject: (reason: Error) => void): void => {
this._container.renderService.renderCamera$.pipe(
first(),
map(
(render: RenderCamera): string => {
const viewport = this._viewportCoords
.canvasToViewport(
pixelPoint[0],
pixelPoint[1],
this._container.container);
const id: string = this._markerScene.intersectObjects(viewport, render.perspective);
return id;
}))
.subscribe(
(id: string): void => {
resolve(id);
},
(error: Error): void => {
reject(error);
});
});
}
/**
* Check if a marker exist in the marker set.
*
* @param {string} markerId - Id of the marker.
*
* @example
* ```js
* var markerExists = markerComponent.has("markerId");
* ```
*/
public has(markerId: string): boolean {
return this._markerSet.has(markerId);
}
public off(
type:
| "markerdragend"
| "markerdragstart"
| "markerposition",
handler: (event: ComponentMarkerEvent) => void)
: void;
/** @ignore */
public off(
type: ComponentEventType,
handler: (event: ComponentEvent) => void)
: void;
public off<T>(
type: ComponentEventType,
handler: (event: T) => void)
: void {
super.off(type, handler);
}
/**
* Fired when a marker drag interaction ends.
*
* @event markerdragend
* @example
* ```js
* // Initialize the viewer
* var viewer = new Viewer({ // viewer options });
* var component = viewer.getComponent('<component-name>');
* // Set an event listener
* component.on('markerdragend', function() {
* console.log("A markerdragend event has occurred.");
* });
* ```
*/
public on(
type: "markerdragend",
handler: (event: ComponentMarkerEvent) => void)
: void;
/**
* Fired when a marker drag interaction starts.
*
* @event markerdragstart
* @example
* ```js
* // Initialize the viewer
* var viewer = new Viewer({ // viewer options });
* var component = viewer.getComponent('<component-name>');
* // Set an event listener
* component.on('markerdragstart', function() {
* console.log("A markerdragstart event has occurred.");
* });
* ```
*/
public on(
type: "markerdragstart",
handler: (event: ComponentMarkerEvent) => void)
: void;
/**
* Fired when the position of a marker is changed.
*
* @event markerposition
* @example
* ```js
* // Initialize the viewer
* var viewer = new Viewer({ // viewer options });
* var component = viewer.getComponent('<component-name>');
* // Set an event listener
* component.on('markerposition', function() {
* console.log("A markerposition event has occurred.");
* });
* ```
*/
public on(
type: "markerposition",
handler: (event: ComponentMarkerEvent) => void)
: void;
public on<T>(
type: ComponentEventType,
handler: (event: T) => void)
: void {
super.on(type, handler);
}
/**
* Remove markers with the specified ids from the marker set.
*
* @param {Array<string>} markerIds - Ids for markers to remove.
*
* @example
* ```js
* markerComponent.remove(["id-1", "id-2"]);
* ```
*/
public remove(markerIds: string[]): void {
this._markerSet.remove(markerIds);
}
/**
* Remove all markers from the marker set.
*
* @example
* ```js
* markerComponent.removeAll();
* ```
*/
public removeAll(): void {
this._markerSet.removeAll();
}
protected _activate(): void {
const groundAltitude$ = this._navigator.stateService.currentState$.pipe(
map(
(frame: AnimationFrame): number => {
return frame.state.camera.position.z + this._relativeGroundAltitude;
}),
distinctUntilChanged(
(a1: number, a2: number): boolean => {
return Math.abs(a1 - a2) < 0.01;
}),
publishReplay(1),
refCount());
const geoInitiated$ = observableCombineLatest(
groundAltitude$,
this._navigator.stateService.reference$).pipe(
first(),
map((): void => { /* noop */ }),
publishReplay(1),
refCount());
const clampedConfiguration$ = this._configuration$.pipe(
map(
(configuration: MarkerConfiguration): MarkerConfiguration => {
return { visibleBBoxSize: Math.max(1, Math.min(200, configuration.visibleBBoxSize)) };
}));
const currentLngLat$ = this._navigator.stateService.currentImage$.pipe(
map((image: Image): LngLat => { return image.lngLat; }),
publishReplay(1),
refCount());
const visibleBBox$ = observableCombineLatest(
clampedConfiguration$,
currentLngLat$).pipe(
map(
([configuration, lngLat]: [MarkerConfiguration, LngLat]): [LngLat, LngLat] => {
return this._graphCalculator
.boundingBoxCorners(lngLat, configuration.visibleBBoxSize / 2);
}),
publishReplay(1),
refCount());
const visibleMarkers$ = observableCombineLatest(
observableConcat(
observableOf<MarkerSet>(this._markerSet),
this._markerSet.changed$),
visibleBBox$).pipe(
map(
([set, bbox]: [MarkerSet, [LngLat, LngLat]]): Marker[] => {
return set.search(bbox);
}));
const subs = this._subscriptions;
subs.push(geoInitiated$.pipe(
switchMap(
(): Observable<[Marker[], LngLatAlt, number]> => {
return visibleMarkers$.pipe(
withLatestFrom(
this._navigator.stateService.reference$,
groundAltitude$));
}))
.subscribe(
(
[markers, reference, alt]
: [Marker[], LngLatAlt, number])
: void => {
const markerScene: MarkerScene = this._markerScene;
const sceneMarkers: { [id: string]: Marker } =
markerScene.markers;
const markersToRemove: { [id: string]: Marker } =
Object.assign({}, sceneMarkers);
for (const marker of markers) {
if (marker.id in sceneMarkers) {
delete markersToRemove[marker.id];
} else {
const point3d =
geodeticToEnu(
marker.lngLat.lng,
marker.lngLat.lat,
reference.alt + alt,
reference.lng,
reference.lat,
reference.alt);
markerScene.add(marker, point3d);
}
}
for (const id in markersToRemove) {
if (!markersToRemove.hasOwnProperty(id)) {
continue;
}
markerScene.remove(id);
}
}));
subs.push(geoInitiated$.pipe(
switchMap(
(): Observable<[Marker[], [LngLat, LngLat], LngLatAlt, number]> => {
return this._markerSet.updated$.pipe(
withLatestFrom(
visibleBBox$,
this._navigator.stateService.reference$,
groundAltitude$));
}))
.subscribe(
(
[markers, [sw, ne], reference, alt]
: [Marker[], [LngLat, LngLat], LngLatAlt, number])
: void => {
const markerScene: MarkerScene = this._markerScene;
for (const marker of markers) {
const exists = markerScene.has(marker.id);
const visible = marker.lngLat.lat > sw.lat &&
marker.lngLat.lat < ne.lat &&
marker.lngLat.lng > sw.lng &&
marker.lngLat.lng < ne.lng;
if (visible) {
const point3d =
geodeticToEnu(
marker.lngLat.lng,
marker.lngLat.lat,
reference.alt + alt,
reference.lng,
reference.lat,
reference.alt);
markerScene.add(marker, point3d);
} else if (!visible && exists) {
markerScene.remove(marker.id);
}
}
}));
subs.push(this._navigator.stateService.reference$.pipe(
skip(1),
withLatestFrom(groundAltitude$))
.subscribe(
([reference, alt]: [LngLatAlt, number]): void => {
const markerScene: MarkerScene = this._markerScene;
for (const marker of markerScene.getAll()) {
const point3d =
geodeticToEnu(
marker.lngLat.lng,
marker.lngLat.lat,
reference.alt + alt,
reference.lng,
reference.lat,
reference.alt);
markerScene.update(marker.id, point3d);
}
}));
subs.push(groundAltitude$.pipe(
skip(1),
withLatestFrom(
this._navigator.stateService.reference$,
currentLngLat$))
.subscribe(
(
[alt, reference, lngLat]
: [number, LngLatAlt, LngLat])
: void => {
const markerScene = this._markerScene;
const position =
geodeticToEnu(
lngLat.lng,
lngLat.lat,
reference.alt + alt,
reference.lng,
reference.lat,
reference.alt);
for (const marker of markerScene.getAll()) {
const point3d =
geodeticToEnu(
marker.lngLat.lng,
marker.lngLat.lat,
reference.alt + alt,
reference.lng,
reference.lat,
reference.alt);
const distanceX = point3d[0] - position[0];
const distanceY = point3d[1] - position[1];
const groundDistance = Math
.sqrt(distanceX * distanceX + distanceY * distanceY);
if (groundDistance > 50) {
continue;
}
markerScene.lerpAltitude(marker.id, alt, Math.min(1, Math.max(0, 1.2 - 1.2 * groundDistance / 50)));
}
}));
subs.push(this._navigator.stateService.currentState$
.pipe(
map(
(frame: AnimationFrame): GLRenderHash => {
const scene = this._markerScene;
return {
name: this._name,
renderer: {
frameId: frame.id,
needsRender: scene.needsRender,
render: scene.render.bind(scene),
pass: RenderPass.Opaque,
},
};
}))
.subscribe(this._container.glRenderer.render$));
const hoveredMarkerId$: Observable<string> =
observableCombineLatest(
this._container.renderService.renderCamera$,
this._container.mouseService.mouseMove$)
.pipe(
map(
([render, event]: [RenderCamera, MouseEvent]): string => {
const element = this._container.container;
const [canvasX, canvasY] = this._viewportCoords.canvasPosition(event, element);
const viewport = this._viewportCoords
.canvasToViewport(
canvasX,
canvasY,
element);
const markerId: string = this._markerScene.intersectObjects(viewport, render.perspective);
return markerId;
}),
publishReplay(1),
refCount());
const draggingStarted$: Observable<boolean> =
this._container.mouseService
.filtered$(this._name, this._container.mouseService.mouseDragStart$).pipe(
map(
(): boolean => {
return true;
}));
const draggingStopped$: Observable<boolean> =
this._container.mouseService
.filtered$(this._name, this._container.mouseService.mouseDragEnd$).pipe(
map(
(): boolean => {
return false;
}));
const filteredDragging$: Observable<boolean> =
observableMerge(
draggingStarted$,
draggingStopped$)
.pipe(
startWith(false));
subs.push(observableMerge(
draggingStarted$.pipe(
withLatestFrom(hoveredMarkerId$)),
observableCombineLatest(
draggingStopped$,
observableOf<string>(null))).pipe(
startWith<[boolean, string]>([false, null]),
pairwise())
.subscribe(
([previous, current]: [boolean, string][]): void => {
const dragging = current[0];
const type: ComponentEventType =
dragging ?
"markerdragstart" :
"markerdragend";
const id = dragging ? current[1] : previous[1];
const marker = this._markerScene.get(id);
const event: ComponentMarkerEvent = {
marker,
target: this,
type,
};
this.fire(type, event);
}));
const mouseDown$: Observable<boolean> = observableMerge(
this._container.mouseService.mouseDown$.pipe(
map((): boolean => { return true; })),
this._container.mouseService.documentMouseUp$.pipe(
map((): boolean => { return false; }))).pipe(
startWith(false));
subs.push(
observableCombineLatest(
this._container.mouseService.active$,
hoveredMarkerId$.pipe(distinctUntilChanged()),
mouseDown$,
filteredDragging$)
.pipe(
map(
(
[active, markerId, mouseDown, filteredDragging]
: [boolean, string, boolean, boolean])
: boolean => {
return (!active && markerId != null && mouseDown) ||
filteredDragging;
}),
distinctUntilChanged())
.subscribe(
(claim: boolean): void => {
if (claim) {
this._container.mouseService.claimMouse(this._name, 1);
this._container.mouseService.claimWheel(this._name, 1);
} else {
this._container.mouseService.unclaimMouse(this._name);
this._container.mouseService.unclaimWheel(this._name);
}
}));
const offset$: Observable<[Marker, number[], RenderCamera]> = this._container.mouseService
.filtered$(this._name, this._container.mouseService.mouseDragStart$).pipe(
withLatestFrom(
hoveredMarkerId$,
this._container.renderService.renderCamera$),
map(
(
[e, id, r]:
[MouseEvent, string, RenderCamera])
: [Marker, number[], RenderCamera] => {
const marker: Marker = this._markerScene.get(id);
const element = this._container.container;
const [groundCanvasX, groundCanvasY]: number[] =
this._viewportCoords
.projectToCanvas(
marker.geometry.position
.toArray(),
element,
r.perspective);
const [canvasX, canvasY] = this._viewportCoords
.canvasPosition(e, element);
const offset = [canvasX - groundCanvasX, canvasY - groundCanvasY];
return [marker, offset, r];
}),
publishReplay(1),
refCount());
subs.push(this._container.mouseService
.filtered$(
this._name,
this._container.mouseService.mouseDrag$)
.pipe(
withLatestFrom(
offset$,
this._navigator.stateService.reference$,
clampedConfiguration$))
.subscribe(
([event, [marker, offset, render], reference, configuration]:
[MouseEvent, [Marker, number[], RenderCamera], LngLatAlt, MarkerConfiguration]): void => {
if (!this._markerScene.has(marker.id)) {
return;
}
const element = this._container.container;
const [canvasX, canvasY] = this._viewportCoords
.canvasPosition(event, element);
const groundX = canvasX - offset[0];
const groundY = canvasY - offset[1];
const [viewportX, viewportY] = this._viewportCoords
.canvasToViewport(
groundX,
groundY,
element);
const direction =
new THREE.Vector3(viewportX, viewportY, 1)
.unproject(render.perspective)
.sub(render.perspective.position)
.normalize();
const distance = Math.min(
this._relativeGroundAltitude / direction.z,
configuration.visibleBBoxSize / 2 - 0.1);
if (distance < 0) {
return;
}
const intersection = direction
.clone()
.multiplyScalar(distance)
.add(render.perspective.position);
intersection.z =
render.perspective.position.z
+ this._relativeGroundAltitude;
const [lng, lat] =
enuToGeodetic(
intersection.x,
intersection.y,
intersection.z,
reference.lng,
reference.lat,
reference.alt);
this._markerScene
.update(
marker.id,
intersection.toArray(),
{ lat, lng });
this._markerSet.update(marker);
const type: ComponentEventType = "markerposition";
const markerEvent: ComponentMarkerEvent = {
marker,
target: this,
type,
};
this.fire(type, markerEvent);
}));
}
protected _deactivate(): void {
this._subscriptions.unsubscribe();
this._markerScene.clear();
}
protected _getDefaultConfiguration(): MarkerConfiguration {
return { visibleBBoxSize: 100 };
}
} | the_stack |
import { expect, test } from "@jest/globals";
import { LuaArray } from "@wowts/lua";
import { Deque } from "./Queue";
test("new queue", () => {
const q = new Deque<number>();
expect(q.capacity).toBe(1);
});
test("new queue sets size", () => {
const q = new Deque<number>(10);
expect(q.capacity).toBe(10);
});
test("new queue is empty", () => {
const q = new Deque<number>();
expect(q.isEmpty()).toBe(true);
expect(q.length).toBe(0);
expect(q.front()).toBe(undefined);
expect(q.back()).toBe(undefined);
});
test("new queue is not full", () => {
const q = new Deque<number>();
expect(q.isFull()).toBe(false);
});
test("indexOf from empty queue", () => {
const q = new Deque<number>();
expect(q.indexOf(10)).toBe(0);
});
test("push onto empty queue", () => {
const q = new Deque<number>();
q.push(10);
expect(q.length).toBe(1);
expect(q.back()).toBe(10);
});
test("from empty array", () => {
const q = new Deque<number>();
q.fromArray({});
expect(q.length).toBe(0);
expect(q.isEmpty()).toBe(true);
expect(q.asArray()).toEqual({});
});
test("from one-element array", () => {
const q = new Deque<number>();
const expected = { 1: 10 };
q.fromArray(expected);
expect(q.length).toBe(1);
expect(q.back()).toBe(10);
expect(q.asArray()).toEqual(expected);
});
test("from two-element array", () => {
const q = new Deque<number>();
const expected = { 1: 10, 2: 20 };
q.fromArray(expected);
expect(q.capacity).toBe(2);
expect(q.length).toBe(2);
expect(q.front()).toBe(10);
expect(q.back()).toBe(20);
expect(q.asArray()).toEqual(expected);
});
test("as array", () => {
const q = new Deque<number>();
const t = { 1: 10, 2: 20, 3: 30 };
q.fromArray(t);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30 });
expect(q.asArray(true)).toEqual({ 1: 30, 2: 20, 3: 10 });
});
test("unshift empty queue", () => {
const q = new Deque<number>();
q.unshift(10);
expect(q.length).toBe(1);
expect(q.front()).toBe(10);
expect(q.asArray()).toEqual({ 1: 10 });
});
test("one-element queue has same front and back", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10 });
expect(q.length).toBe(1);
expect(q.front()).toBe(q.back());
});
test("pop from one-element queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10 });
expect(q.pop()).toBe(10);
expect(q.length).toBe(0);
expect(q.isEmpty()).toBe(true);
});
test("shift one-element queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10 });
expect(q.shift()).toBe(10);
expect(q.length).toBe(0);
expect(q.isEmpty()).toBe(true);
});
test("remove at 1 of one-element queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10 });
q.removeAt(1);
expect(q.length).toBe(0);
expect(q.isEmpty()).toBe(true);
});
test("replace at 1 of one-element queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10 });
q.replaceAt(1, 20);
expect(q.asArray()).toEqual({ 1: 20 });
});
test("indexOf missing from one-element queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10 });
expect(q.indexOf(20)).toBe(0);
});
test("indexOf existing from one-element queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10 });
expect(q.indexOf(10)).toBe(1);
});
test("push onto queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20 });
q.push(30);
expect(q.length).toBe(3);
expect(q.front()).toBe(10);
expect(q.back()).toBe(30);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30 });
});
test("unshift queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20 });
q.unshift(30);
expect(q.length).toBe(3);
expect(q.front()).toBe(30);
expect(q.back()).toBe(20);
expect(q.asArray()).toEqual({ 1: 30, 2: 10, 3: 20 });
});
test("pop from queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30 });
const value = q.pop();
expect(q.length).toBe(2);
expect(q.front()).toBe(10);
expect(q.back()).toBe(20);
expect(value).toBe(30);
expect(q.asArray()).toEqual({ 1: 10, 2: 20 });
});
test("shift queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30 });
const value = q.shift();
expect(q.length).toBe(2);
expect(q.front()).toBe(20);
expect(q.back()).toBe(30);
expect(value).toBe(10);
expect(q.asArray()).toEqual({ 1: 20, 2: 30 });
});
test("remove at 1 of queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.removeAt(1);
expect(q.length).toBe(3);
expect(q.front()).toBe(20);
expect(q.back()).toBe(40);
expect(q.asArray()).toEqual({ 1: 20, 2: 30, 3: 40 });
});
test("remove at end of queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.removeAt(q.length);
expect(q.length).toBe(3);
expect(q.front()).toBe(10);
expect(q.back()).toBe(30);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30 });
});
test("remove at middle of queue near front", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.removeAt(2);
expect(q.length).toBe(3);
expect(q.front()).toBe(10);
expect(q.back()).toBe(40);
expect(q.asArray()).toEqual({ 1: 10, 2: 30, 3: 40 });
});
test("remove at middle of queue near back", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.removeAt(3);
expect(q.length).toBe(3);
expect(q.front()).toBe(10);
expect(q.back()).toBe(40);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 40 });
});
test("replace at end of queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.replaceAt(q.length, 50);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 50 });
});
test("replace at middle of queue near front", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.replaceAt(2, 50);
expect(q.asArray()).toEqual({ 1: 10, 2: 50, 3: 30, 4: 40 });
});
test("replace at middle of queue near back", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.replaceAt(3, 50);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 50, 4: 40 });
});
test("replace at 1 of queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.replaceAt(1, 50);
expect(q.asArray()).toEqual({ 1: 50, 2: 20, 3: 30, 4: 40 });
});
test("indexOf missing from queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30, 4: 40 });
expect(q.indexOf(50)).toBe(0);
});
test("indexOf existing from front of queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30, 4: 40 });
expect(q.indexOf(10)).toBe(1);
});
test("indexOf existing from back of queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30, 4: 40 });
expect(q.indexOf(40)).toBe(4);
});
test("indexOf existing from middle of queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30, 4: 40 });
expect(q.indexOf(20)).toBe(2);
});
test("grow queue", () => {
const q = new Deque<number>();
q.push(10);
expect(q.capacity).toBe(1);
q.push(20); // grow once
expect(q.capacity).toBe(2);
q.push(30); // grow twice
expect(q.capacity).toBe(4);
expect(q.length).toBe(3);
expect(q.front()).toBe(10);
expect(q.back()).toBe(30);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30 });
});
test("not full fixed queue", () => {
const q = new Deque<number>(3, true);
q.fromArray({ 1: 10, 2: 20 });
expect(q.capacity).toBe(3);
expect(q.length).toBe(2);
expect(q.front()).toBe(10);
expect(q.back()).toBe(20);
expect(q.isFull()).toBe(false);
});
test("full fixed queue", () => {
const q = new Deque<number>(3, true);
q.fromArray({ 1: 10, 2: 20, 3: 30 });
expect(q.capacity).toBe(3);
expect(q.length).toBe(3);
expect(q.front()).toBe(10);
expect(q.back()).toBe(30);
expect(q.isFull()).toBe(true);
});
test("push onto full queue", () => {
const q = new Deque<number>(3, true);
q.fromArray({ 1: 10, 2: 20, 3: 30 });
q.push(40);
expect(q.capacity).toBe(3);
expect(q.length).toBe(3);
expect(q.front()).toBe(20);
expect(q.back()).toBe(40);
expect(q.isFull()).toBe(true);
expect(q.asArray()).toEqual({ 1: 20, 2: 30, 3: 40 });
});
test("unshift full queue", () => {
const q = new Deque<number>(3, true);
q.fromArray({ 1: 10, 2: 20, 3: 30 });
q.unshift(40);
expect(q.capacity).toBe(3);
expect(q.length).toBe(3);
expect(q.front()).toBe(40);
expect(q.back()).toBe(20);
expect(q.isFull()).toBe(true);
expect(q.asArray()).toEqual({ 1: 40, 2: 10, 3: 20 });
});
function createWraparoundQueue(fixed?: boolean) {
/* Return a 4-element queue with capacity 5 that starts in the
* middle of the buffer.
*/
if (fixed == undefined) {
fixed = false;
}
const q = new Deque<number>(5, fixed);
q.push(-20);
q.push(-10);
q.push(0);
q.push(10);
q.push(20);
q.shift(); // remove -20
q.shift(); // remove -10
q.shift(); // remove 0
q.push(30);
q.push(40);
// queue.buffer: 30 40] nil [10 20
//expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
return q;
}
test("queue with wraparound indexing", () => {
const q = createWraparoundQueue();
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
expect(q.length).toBe(4);
expect(q.capacity).toBe(5);
expect(q.front()).toBe(10);
expect(q.back()).toBe(40);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
});
test("push onto queue with wrapround indexing", () => {
const q = createWraparoundQueue();
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.push(50);
expect(q.capacity).toBe(5);
expect(q.length).toBe(5);
expect(q.front()).toBe(10);
expect(q.back()).toBe(50);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40, 5: 50 });
});
test("unshift queue with wrapround indexing", () => {
const q = createWraparoundQueue();
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.unshift(50);
expect(q.capacity).toBe(5);
expect(q.length).toBe(5);
expect(q.front()).toBe(50);
expect(q.back()).toBe(40);
expect(q.asArray()).toEqual({ 1: 50, 2: 10, 3: 20, 4: 30, 5: 40 });
});
test("pop from queue with wrapround indexing", () => {
const q = createWraparoundQueue();
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
expect(q.pop()).toBe(40);
expect(q.capacity).toBe(5);
expect(q.length).toBe(3);
expect(q.front()).toBe(10);
expect(q.back()).toBe(30);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30 });
});
test("shift queue with wrapround indexing", () => {
const q = createWraparoundQueue();
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
expect(q.shift()).toBe(10);
expect(q.capacity).toBe(5);
expect(q.length).toBe(3);
expect(q.front()).toBe(20);
expect(q.back()).toBe(40);
expect(q.asArray()).toEqual({ 1: 20, 2: 30, 3: 40 });
});
test("remove at 1 of queue with wraparound indexing", () => {
const q = createWraparoundQueue();
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.removeAt(1);
expect(q.length).toBe(3);
expect(q.front()).toBe(20);
expect(q.back()).toBe(40);
expect(q.asArray()).toEqual({ 1: 20, 2: 30, 3: 40 });
});
test("remove at end of queue with wraparound indexing", () => {
const q = createWraparoundQueue();
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.removeAt(q.length);
expect(q.length).toBe(3);
expect(q.front()).toBe(10);
expect(q.back()).toBe(30);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30 });
});
test("remove at middle of queue near front with wraparound indexing", () => {
const q = createWraparoundQueue();
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.removeAt(2);
expect(q.length).toBe(3);
expect(q.front()).toBe(10);
expect(q.back()).toBe(40);
expect(q.asArray()).toEqual({ 1: 10, 2: 30, 3: 40 });
});
test("remove at middle of queue near back with wraparound indexing", () => {
const q = createWraparoundQueue();
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.removeAt(3);
expect(q.length).toBe(3);
expect(q.front()).toBe(10);
expect(q.back()).toBe(40);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 40 });
});
test("replace at 1 of queue with wraparound indexing", () => {
const q = createWraparoundQueue();
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.replaceAt(1, 50);
expect(q.asArray()).toEqual({ 1: 50, 2: 20, 3: 30, 4: 40 });
});
test("replace at end of queue with wraparound indexing", () => {
const q = createWraparoundQueue();
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.replaceAt(q.length, 50);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 50 });
});
test("replace at middle of queue near front with wraparound indexing", () => {
const q = createWraparoundQueue();
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.replaceAt(2, 50);
expect(q.asArray()).toEqual({ 1: 10, 2: 50, 3: 30, 4: 40 });
});
test("replace at middle of queue near back with wraparound indexing", () => {
const q = createWraparoundQueue();
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.replaceAt(3, 50);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 50, 4: 40 });
});
test("indexOf missing from queue with wraparound indexing", () => {
const q = createWraparoundQueue();
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
expect(q.indexOf(50)).toBe(0);
});
test("indexOf existing from front of queue with wraparound indexing", () => {
const q = createWraparoundQueue();
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
expect(q.indexOf(10)).toBe(1);
});
test("indexOf existing from back of queue with wraparound indexing", () => {
const q = createWraparoundQueue();
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
expect(q.indexOf(40)).toBe(4);
});
test("indexOf existing from middle of queue with wraparound indexing", () => {
const q = createWraparoundQueue();
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
expect(q.indexOf(20)).toBe(2);
});
test("grow queue with wraparound indexing", () => {
const q = createWraparoundQueue();
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.push(50); // buffer at full capacity
q.push(60);
expect(q.length).toBe(6);
expect(q.capacity).toBe(10);
expect(q.front()).toBe(10);
expect(q.back()).toBe(60);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60 });
});
test("full queue with wraparound indexing", () => {
const q = createWraparoundQueue(true);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.push(50); // buffer at full capacity
expect(q.capacity).toBe(5);
expect(q.length).toBe(5);
expect(q.front()).toBe(10);
expect(q.back()).toBe(50);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40, 5: 50 });
});
test("push onto full queue with wraparound indexing", () => {
const q = createWraparoundQueue(true);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.push(50); // buffer at full capacity
q.push(60);
expect(q.capacity).toBe(5);
expect(q.length).toBe(5);
expect(q.front()).toBe(20);
expect(q.back()).toBe(60);
expect(q.asArray()).toEqual({ 1: 20, 2: 30, 3: 40, 4: 50, 5: 60 });
});
test("unshift full queue with wraparound indexing", () => {
const q = createWraparoundQueue(true);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.push(50); // buffer at full capacity
q.unshift(60);
expect(q.capacity).toBe(5);
expect(q.length).toBe(5);
expect(q.front()).toBe(60);
expect(q.back()).toBe(40);
expect(q.asArray()).toEqual({ 1: 60, 2: 10, 3: 20, 4: 30, 5: 40 });
});
test("pop from full queue with wraparound indexing", () => {
const q = createWraparoundQueue(true);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.push(50); // buffer at full capacity
expect(q.pop()).toBe(50);
expect(q.capacity).toBe(5);
expect(q.length).toBe(4);
expect(q.front()).toBe(10);
expect(q.back()).toBe(40);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
});
test("shift from full queue with wraparound indexing", () => {
const q = createWraparoundQueue(true);
expect(q.asArray()).toEqual({ 1: 10, 2: 20, 3: 30, 4: 40 });
q.push(50); // buffer at full capacity
expect(q.shift()).toBe(10);
expect(q.capacity).toBe(5);
expect(q.length).toBe(4);
expect(q.front()).toBe(20);
expect(q.back()).toBe(50);
expect(q.asArray()).toEqual({ 1: 20, 2: 30, 3: 40, 4: 50 });
});
test("back to front iterator of empty queue", () => {
const q = new Deque<number>();
const iterator = q.backToFrontIterator();
expect(iterator.next()).toBe(false);
});
test("back to front iterator of one-element queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10 });
const t: LuaArray<number> = {};
const iterator = q.backToFrontIterator();
for (let i = 1; iterator.next(); i++) {
t[i] = iterator.value;
}
expect(t).toEqual(q.asArray());
});
test("back to front iterator of queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30 });
const t: LuaArray<number> = {};
const iterator = q.backToFrontIterator();
for (let i = 1; iterator.next(); i++) {
t[i] = iterator.value;
}
expect(t).toEqual(q.asArray(true));
});
test("replace with back to front iterator of queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30 });
const iterator = q.backToFrontIterator();
expect(iterator.next()).toBe(true);
expect(iterator.value).toBe(30);
expect(iterator.next()).toBe(true);
expect(iterator.value).toBe(20);
iterator.replace(40);
expect(iterator.value).toBe(40);
expect(iterator.next()).toBe(true);
expect(iterator.value).toBe(10);
expect(iterator.next()).toBe(false);
expect(q.asArray()).toEqual({ 1: 10, 2: 40, 3: 30 });
});
test("front to back iterator of empty queue", () => {
const q = new Deque<number>();
const iterator = q.frontToBackIterator();
expect(iterator.next()).toBe(false);
});
test("front to back iterator of one-element queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10 });
const t: LuaArray<number> = {};
const iterator = q.frontToBackIterator();
for (let i = 1; iterator.next(); i++) {
t[i] = iterator.value;
}
expect(t).toEqual(q.asArray());
});
test("front to back iterator of queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30 });
const t: LuaArray<number> = {};
const iterator = q.frontToBackIterator();
for (let i = 1; iterator.next(); i++) {
t[i] = iterator.value;
}
expect(t).toEqual(q.asArray());
});
test("replace with front to back iterator of queue", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30 });
const iterator = q.frontToBackIterator();
expect(iterator.next()).toBe(true);
expect(iterator.value).toBe(10);
expect(iterator.next()).toBe(true);
expect(iterator.value).toBe(20);
iterator.replace(40);
expect(iterator.value).toBe(40);
expect(iterator.next()).toBe(true);
expect(iterator.value).toBe(30);
expect(iterator.next()).toBe(false);
expect(q.asArray()).toEqual({ 1: 10, 2: 40, 3: 30 });
});
test("cleared queue is empty", () => {
const q = new Deque<number>();
q.fromArray({ 1: 10, 2: 20, 3: 30 });
q.clear();
expect(q.isEmpty()).toBe(true);
}); | the_stack |
import {Class, FromAny, Creatable, InitType, Initable} from "@swim/util";
import {Fastener, Provider, ComponentFlags, ComponentInit, Component} from "@swim/component";
import {ExecuteService} from "../execute/ExecuteService";
import {ExecuteProvider} from "../execute/ExecuteProvider";
import {HistoryService} from "../history/HistoryService";
import {HistoryProvider} from "../history/HistoryProvider";
import {StorageService} from "../storage/StorageService";
import {StorageProvider} from "../storage/StorageProvider";
import {ControllerContext} from "./ControllerContext";
import type {ControllerObserver} from "./ControllerObserver";
import {ControllerRelation} from "./"; // forward import
/** @public */
export type ControllerContextType<C extends Controller> =
C extends {readonly contextType?: Class<infer T>} ? T : never;
/** @public */
export type ControllerFlags = ComponentFlags;
/** @public */
export type AnyController<C extends Controller = Controller> = C | ControllerFactory<C> | InitType<C>;
/** @public */
export interface ControllerInit extends ComponentInit {
/** @internal */
uid?: never, // force type ambiguity between Controller and ControllerInit
type?: Creatable<Controller>;
key?: string;
children?: AnyController[];
}
/** @public */
export interface ControllerFactory<C extends Controller = Controller, U = AnyController<C>> extends Creatable<C>, FromAny<C, U> {
fromInit(init: InitType<C>): C;
}
/** @public */
export interface ControllerClass<C extends Controller = Controller, U = AnyController<C>> extends Function, ControllerFactory<C, U> {
readonly prototype: C;
}
/** @public */
export interface ControllerConstructor<C extends Controller = Controller, U = AnyController<C>> extends ControllerClass<C, U> {
new(): C;
}
/** @public */
export type ControllerCreator<F extends (abstract new (...args: any) => C) & Creatable<InstanceType<F>>, C extends Controller = Controller> =
(abstract new (...args: any) => InstanceType<F>) & Creatable<InstanceType<F>>;
/** @public */
export class Controller extends Component<Controller> implements Initable<ControllerInit> {
override get componentType(): Class<Controller> {
return Controller;
}
override readonly observerType?: Class<ControllerObserver>;
readonly contextType?: Class<ControllerContext>;
protected override willAttachParent(parent: Controller): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerWillAttachParent !== void 0) {
observer.controllerWillAttachParent(parent, this);
}
}
}
protected override onAttachParent(parent: Controller): void {
// hook
}
protected override didAttachParent(parent: Controller): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerDidAttachParent !== void 0) {
observer.controllerDidAttachParent(parent, this);
}
}
}
protected override willDetachParent(parent: Controller): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerWillDetachParent !== void 0) {
observer.controllerWillDetachParent(parent, this);
}
}
}
protected override onDetachParent(parent: Controller): void {
// hook
}
protected override didDetachParent(parent: Controller): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerDidDetachParent !== void 0) {
observer.controllerDidDetachParent(parent, this);
}
}
}
override setChild<C extends Controller>(key: string, newChild: C): Controller | null;
override setChild<F extends ControllerCreator<F>>(key: string, factory: F): Controller | null;
override setChild(key: string, newChild: AnyController | null): Controller | null;
override setChild(key: string, newChild: AnyController | null): Controller | null {
if (newChild !== null) {
newChild = Controller.fromAny(newChild);
}
return super.setChild(key, newChild) as Controller | null;
}
override appendChild<C extends Controller>(child: C, key?: string): C;
override appendChild<F extends ControllerCreator<F>>(factory: F, key?: string): InstanceType<F>;
override appendChild(child: AnyController, key?: string): Controller;
override appendChild(child: AnyController, key?: string): Controller {
child = Controller.fromAny(child);
return super.appendChild(child, key);
}
override prependChild<C extends Controller>(child: C, key?: string): C;
override prependChild<F extends ControllerCreator<F>>(factory: F, key?: string): InstanceType<F>;
override prependChild(child: AnyController, key?: string): Controller;
override prependChild(child: AnyController, key?: string): Controller {
child = Controller.fromAny(child);
return super.prependChild(child, key);
}
override insertChild<C extends Controller>(child: C, target: Controller | null, key?: string): C;
override insertChild<F extends ControllerCreator<F>>(factory: F, target: Controller | null, key?: string): InstanceType<F>;
override insertChild(child: AnyController, target: Controller | null, key?: string): Controller;
override insertChild(child: AnyController, target: Controller | null, key?: string): Controller {
child = Controller.fromAny(child);
return super.insertChild(child, target, key);
}
override replaceChild<C extends Controller>(newChild: Controller, oldChild: C): C;
override replaceChild<C extends Controller>(newChild: AnyController, oldChild: C): C;
override replaceChild(newChild: AnyController, oldChild: Controller): Controller {
newChild = Controller.fromAny(newChild);
return super.replaceChild(newChild, oldChild);
}
protected override willInsertChild(child: Controller, target: Controller | null): void {
super.willInsertChild(child, target);
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerWillInsertChild !== void 0) {
observer.controllerWillInsertChild(child, target, this);
}
}
}
protected override onInsertChild(child: Controller, target: Controller | null): void {
super.onInsertChild(child, target);
}
protected override didInsertChild(child: Controller, target: Controller | null): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerDidInsertChild !== void 0) {
observer.controllerDidInsertChild(child, target, this);
}
}
super.didInsertChild(child, target);
}
/** @internal */
override cascadeInsert(updateFlags?: ControllerFlags, controllerContext?: ControllerContext): void {
if ((this.flags & Controller.MountedFlag) !== 0) {
if (updateFlags === void 0) {
updateFlags = 0;
}
updateFlags |= this.flags & Controller.UpdateMask;
if ((updateFlags & Controller.CompileMask) !== 0) {
if (controllerContext === void 0) {
controllerContext = this.superControllerContext;
}
this.cascadeCompile(updateFlags, controllerContext);
}
}
}
protected override willRemoveChild(child: Controller): void {
super.willRemoveChild(child);
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerWillRemoveChild !== void 0) {
observer.controllerWillRemoveChild(child, this);
}
}
}
protected override onRemoveChild(child: Controller): void {
super.onRemoveChild(child);
}
protected override didRemoveChild(child: Controller): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerDidRemoveChild !== void 0) {
observer.controllerDidRemoveChild(child, this);
}
}
super.didRemoveChild(child);
}
protected override willMount(): void {
super.willMount();
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerWillMount !== void 0) {
observer.controllerWillMount(this);
}
}
}
protected override onMount(): void {
// subsume super
this.requestUpdate(this, this.flags & Controller.UpdateMask, false);
this.requireUpdate(this.mountFlags);
if (this.decoherent !== null && this.decoherent.length !== 0) {
this.requireUpdate(Controller.NeedsRevise);
}
this.mountFasteners();
}
protected override didMount(): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerDidMount !== void 0) {
observer.controllerDidMount(this);
}
}
super.didMount();
}
protected override willUnmount(): void {
super.willUnmount();
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerWillUnmount !== void 0) {
observer.controllerWillUnmount(this);
}
}
}
protected override didUnmount(): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerDidUnmount !== void 0) {
observer.controllerDidUnmount(this);
}
}
super.didUnmount();
}
override requireUpdate(updateFlags: ControllerFlags, immediate: boolean = false): void {
const flags = this.flags;
const deltaUpdateFlags = updateFlags & ~flags & Controller.UpdateMask;
if (deltaUpdateFlags !== 0) {
this.setFlags(flags | deltaUpdateFlags);
this.requestUpdate(this, deltaUpdateFlags, immediate);
}
}
protected needsUpdate(updateFlags: ControllerFlags, immediate: boolean): ControllerFlags {
return updateFlags;
}
requestUpdate(target: Controller, updateFlags: ControllerFlags, immediate: boolean): void {
updateFlags = this.needsUpdate(updateFlags, immediate);
let deltaUpdateFlags = this.flags & ~updateFlags & Controller.UpdateMask;
if ((updateFlags & Controller.CompileMask) !== 0) {
deltaUpdateFlags |= Controller.NeedsCompile;
}
if ((updateFlags & Controller.ExecuteMask) !== 0) {
deltaUpdateFlags |= Controller.NeedsExecute;
}
if (deltaUpdateFlags !== 0 || immediate) {
this.setFlags(this.flags | deltaUpdateFlags);
const parent = this.parent;
if (parent !== null) {
parent.requestUpdate(target, updateFlags, immediate);
} else if (this.mounted) {
const executeService = this.executeProvider.service;
if (executeService !== void 0 && executeService !== null) {
executeService.requestUpdate(target, updateFlags, immediate);
}
}
}
}
get updating(): boolean {
return (this.flags & Controller.UpdatingMask) !== 0;
}
get compiling(): boolean {
return (this.flags & Controller.CompilingFlag) !== 0;
}
protected needsCompile(compileFlags: ControllerFlags, controllerContext: ControllerContextType<this>): ControllerFlags {
return compileFlags;
}
cascadeCompile(compileFlags: ControllerFlags, baseControllerContext: ControllerContext): void {
const controllerContext = this.extendControllerContext(baseControllerContext);
const outerControllerContext = ControllerContext.current;
try {
ControllerContext.current = controllerContext;
compileFlags &= ~Controller.NeedsCompile;
compileFlags |= this.flags & Controller.UpdateMask;
compileFlags = this.needsCompile(compileFlags, controllerContext);
if ((compileFlags & Controller.CompileMask) !== 0) {
let cascadeFlags = compileFlags;
this.setFlags(this.flags & ~Controller.NeedsCompile | (Controller.CompilingFlag | Controller.ContextualFlag));
this.willCompile(cascadeFlags, controllerContext);
if (((this.flags | compileFlags) & Controller.NeedsResolve) !== 0) {
cascadeFlags |= Controller.NeedsResolve;
this.setFlags(this.flags & ~Controller.NeedsResolve);
this.willResolve(controllerContext);
}
if (((this.flags | compileFlags) & Controller.NeedsGenerate) !== 0) {
cascadeFlags |= Controller.NeedsGenerate;
this.setFlags(this.flags & ~Controller.NeedsGenerate);
this.willGenerate(controllerContext);
}
if (((this.flags | compileFlags) & Controller.NeedsAssemble) !== 0) {
cascadeFlags |= Controller.NeedsAssemble;
this.setFlags(this.flags & ~Controller.NeedsAssemble);
this.willAssemble(controllerContext);
}
this.onCompile(cascadeFlags, controllerContext);
if ((cascadeFlags & Controller.NeedsResolve) !== 0) {
this.onResolve(controllerContext);
}
if ((cascadeFlags & Controller.NeedsGenerate) !== 0) {
this.onGenerate(controllerContext);
}
if ((cascadeFlags & Controller.NeedsAssemble) !== 0) {
this.onAssemble(controllerContext);
}
if ((cascadeFlags & Controller.CompileMask) !== 0) {
this.setFlags(this.flags & ~Controller.ContextualFlag);
this.compileChildren(cascadeFlags, controllerContext, this.compileChild);
this.setFlags(this.flags | Controller.ContextualFlag);
}
if ((cascadeFlags & Controller.NeedsAssemble) !== 0) {
this.didAssemble(controllerContext);
}
if ((cascadeFlags & Controller.NeedsGenerate) !== 0) {
this.didGenerate(controllerContext);
}
if ((cascadeFlags & Controller.NeedsResolve) !== 0) {
this.didResolve(controllerContext);
}
this.didCompile(cascadeFlags, controllerContext);
}
} finally {
this.setFlags(this.flags & ~(Controller.CompilingFlag | Controller.ContextualFlag));
ControllerContext.current = outerControllerContext;
}
}
protected willCompile(compileFlags: ControllerFlags, controllerContext: ControllerContextType<this>): void {
// hook
}
protected onCompile(compileFlags: ControllerFlags, controllerContext: ControllerContextType<this>): void {
// hook
}
protected didCompile(compileFlags: ControllerFlags, controllerContext: ControllerContextType<this>): void {
// hook
}
protected willResolve(controllerContext: ControllerContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerWillResolve !== void 0) {
observer.controllerWillResolve(controllerContext, this);
}
}
}
protected onResolve(controllerContext: ControllerContextType<this>): void {
// hook
}
protected didResolve(controllerContext: ControllerContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerDidResolve !== void 0) {
observer.controllerDidResolve(controllerContext, this);
}
}
}
protected willGenerate(controllerContext: ControllerContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerWillGenerate !== void 0) {
observer.controllerWillGenerate(controllerContext, this);
}
}
}
protected onGenerate(controllerContext: ControllerContextType<this>): void {
// hook
}
protected didGenerate(controllerContext: ControllerContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerDidGenerate !== void 0) {
observer.controllerDidGenerate(controllerContext, this);
}
}
}
protected willAssemble(controllerContext: ControllerContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerWillAssemble !== void 0) {
observer.controllerWillAssemble(controllerContext, this);
}
}
}
protected onAssemble(controllerContext: ControllerContextType<this>): void {
// hook
}
protected didAssemble(controllerContext: ControllerContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerDidAssemble !== void 0) {
observer.controllerDidAssemble(controllerContext, this);
}
}
}
protected compileChildren(compileFlags: ControllerFlags, controllerContext: ControllerContextType<this>,
compileChild: (this: this, child: Controller, compileFlags: ControllerFlags,
controllerContext: ControllerContextType<this>) => void): void {
let child = this.firstChild;
while (child !== null) {
const next = child.nextSibling;
compileChild.call(this, child, compileFlags, controllerContext);
if (next !== null && next.parent !== this) {
throw new Error("inconsistent compile pass");
}
child = next;
}
}
protected compileChild(child: Controller, compileFlags: ControllerFlags, controllerContext: ControllerContextType<this>): void {
child.cascadeCompile(compileFlags, controllerContext);
}
get executing(): boolean {
return (this.flags & Controller.ExecutingFlag) !== 0;
}
protected needsExecute(executeFlags: ControllerFlags, controllerContext: ControllerContextType<this>): ControllerFlags {
return executeFlags;
}
cascadeExecute(executeFlags: ControllerFlags, baseControllerContext: ControllerContext): void {
const controllerContext = this.extendControllerContext(baseControllerContext);
const outerControllerContext = ControllerContext.current;
try {
ControllerContext.current = controllerContext;
executeFlags &= ~Controller.NeedsExecute;
executeFlags |= this.flags & Controller.UpdateMask;
executeFlags = this.needsExecute(executeFlags, controllerContext);
if ((executeFlags & Controller.ExecuteMask) !== 0) {
let cascadeFlags = executeFlags;
this.setFlags(this.flags & ~Controller.NeedsExecute | (Controller.ExecutingFlag | Controller.ContextualFlag));
this.willExecute(cascadeFlags, controllerContext);
if (((this.flags | executeFlags) & Controller.NeedsRevise) !== 0) {
cascadeFlags |= Controller.NeedsRevise;
this.setFlags(this.flags & ~Controller.NeedsRevise);
this.willRevise(controllerContext);
}
if (((this.flags | executeFlags) & Controller.NeedsCompute) !== 0) {
cascadeFlags |= Controller.NeedsCompute;
this.setFlags(this.flags & ~Controller.NeedsCompute);
this.willCompute(controllerContext);
}
this.onExecute(cascadeFlags, controllerContext);
if ((cascadeFlags & Controller.NeedsRevise) !== 0) {
this.onRevise(controllerContext);
}
if ((cascadeFlags & Controller.NeedsCompute) !== 0) {
this.onCompute(controllerContext);
}
if ((cascadeFlags & Controller.ExecuteMask) !== 0) {
this.setFlags(this.flags & ~Controller.ContextualFlag);
this.executeChildren(cascadeFlags, controllerContext, this.executeChild);
this.setFlags(this.flags | Controller.ContextualFlag);
}
if ((cascadeFlags & Controller.NeedsCompute) !== 0) {
this.didCompute(controllerContext);
}
if ((cascadeFlags & Controller.NeedsRevise) !== 0) {
this.didRevise(controllerContext);
}
this.didExecute(cascadeFlags, controllerContext);
}
} finally {
this.setFlags(this.flags & ~(Controller.ExecutingFlag | Controller.ContextualFlag));
ControllerContext.current = outerControllerContext;
}
}
protected willExecute(executeFlags: ControllerFlags, controllerContext: ControllerContextType<this>): void {
// hook
}
protected onExecute(executeFlags: ControllerFlags, controllerContext: ControllerContextType<this>): void {
// hook
}
protected didExecute(executeFlags: ControllerFlags, controllerContext: ControllerContextType<this>): void {
// hook
}
protected willRevise(controllerContext: ControllerContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerWillRevise !== void 0) {
observer.controllerWillRevise(controllerContext, this);
}
}
}
protected onRevise(controllerContext: ControllerContextType<this>): void {
this.recohereFasteners(controllerContext.updateTime);
}
protected didRevise(controllerContext: ControllerContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerDidRevise !== void 0) {
observer.controllerDidRevise(controllerContext, this);
}
}
}
protected willCompute(controllerContext: ControllerContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerWillCompute !== void 0) {
observer.controllerWillCompute(controllerContext, this);
}
}
}
protected onCompute(controllerContext: ControllerContextType<this>): void {
// hook
}
protected didCompute(controllerContext: ControllerContextType<this>): void {
const observers = this.observers;
for (let i = 0, n = observers.length; i < n; i += 1) {
const observer = observers[i]!;
if (observer.controllerDidCompute !== void 0) {
observer.controllerDidCompute(controllerContext, this);
}
}
}
protected executeChildren(executeFlags: ControllerFlags, controllerContext: ControllerContextType<this>,
executeChild: (this: this, child: Controller, executeFlags: ControllerFlags,
controllerContext: ControllerContextType<this>) => void): void {
let child = this.firstChild;
while (child !== null) {
const next = child.nextSibling;
executeChild.call(this, child, executeFlags, controllerContext);
if (next !== null && next.parent !== this) {
throw new Error("inconsistent execute pass");
}
child = next;
}
}
/** @internal */
protected executeChild(child: Controller, executeFlags: ControllerFlags, controllerContext: ControllerContextType<this>): void {
child.cascadeExecute(executeFlags, controllerContext);
}
/** @internal */
protected override bindChildFastener(fastener: Fastener, child: Controller, target: Controller | null): void {
super.bindChildFastener(fastener, child, target);
if (fastener instanceof ControllerRelation) {
fastener.bindController(child, target);
}
}
/** @internal */
protected override unbindChildFastener(fastener: Fastener, child: Controller): void {
if (fastener instanceof ControllerRelation) {
fastener.unbindController(child);
}
super.unbindChildFastener(fastener, child);
}
/** @internal @override */
override decohereFastener(fastener: Fastener): void {
super.decohereFastener(fastener);
this.requireUpdate(Controller.NeedsRevise);
}
@Provider({
extends: ExecuteProvider,
type: ExecuteService,
observes: false,
service: ExecuteService.global(),
})
readonly executeProvider!: ExecuteProvider<this>;
@Provider({
extends: HistoryProvider,
type: HistoryService,
observes: false,
service: HistoryService.global(),
})
readonly historyProvider!: HistoryProvider<this>;
@Provider({
extends: StorageProvider,
type: StorageService,
observes: false,
service: StorageService.global(),
})
readonly storageProvider!: StorageProvider<this>;
/** @internal */
get superControllerContext(): ControllerContext {
const parent = this.parent;
if (parent !== null) {
return parent.controllerContext;
} else {
return this.executeProvider.updatedControllerContext();
}
}
/** @internal */
extendControllerContext(controllerContext: ControllerContext): ControllerContextType<this> {
return controllerContext as ControllerContextType<this>;
}
get controllerContext(): ControllerContextType<this> {
if ((this.flags & Controller.ContextualFlag) !== 0) {
return ControllerContext.current as ControllerContextType<this>;
} else {
return this.extendControllerContext(this.superControllerContext);
}
}
/** @override */
override init(init: ControllerInit): void {
// hook
}
static override create<S extends new () => InstanceType<S>>(this: S): InstanceType<S> {
return new this();
}
static override fromInit<S extends abstract new (...args: any) => InstanceType<S>>(this: S, init: InitType<InstanceType<S>>): InstanceType<S> {
let type: Creatable<Controller>;
if ((typeof init === "object" && init !== null || typeof init === "function") && Creatable.is((init as ControllerInit).type)) {
type = (init as ControllerInit).type!;
} else {
type = this as unknown as Creatable<Controller>;
}
const controller = type.create();
controller.init(init as ControllerInit);
return controller as InstanceType<S>;
}
static override fromAny<S extends abstract new (...args: any) => InstanceType<S>>(this: S, value: AnyController<InstanceType<S>>): InstanceType<S> {
if (value === void 0 || value === null) {
return value as InstanceType<S>;
} else if (value instanceof Controller) {
if (value instanceof this) {
return value;
} else {
throw new TypeError(value + " not an instance of " + this);
}
} else if (Creatable.is(value)) {
return (value as Creatable<InstanceType<S>>).create();
} else {
return (this as unknown as ControllerFactory<InstanceType<S>>).fromInit(value);
}
}
/** @internal */
static override uid: () => number = (function () {
let nextId = 1;
return function uid(): number {
const id = ~~nextId;
nextId += 1;
return id;
}
})();
/** @internal */
static override readonly MountedFlag: ControllerFlags = Component.MountedFlag;
/** @internal */
static override readonly RemovingFlag: ControllerFlags = Component.RemovingFlag;
/** @internal */
static readonly CompilingFlag: ControllerFlags = 1 << (Component.FlagShift + 0);
/** @internal */
static readonly ExecutingFlag: ControllerFlags = 1 << (Component.FlagShift + 1);
/** @internal */
static readonly ContextualFlag: ControllerFlags = 1 << (Component.FlagShift + 2);
/** @internal */
static readonly UpdatingMask: ControllerFlags = Controller.CompilingFlag
| Controller.ExecutingFlag;
/** @internal */
static readonly StatusMask: ControllerFlags = Controller.MountedFlag
| Controller.RemovingFlag
| Controller.CompilingFlag
| Controller.ExecutingFlag
| Controller.ContextualFlag;
static readonly NeedsCompile: ControllerFlags = 1 << (Component.FlagShift + 3);
static readonly NeedsResolve: ControllerFlags = 1 << (Component.FlagShift + 4);
static readonly NeedsGenerate: ControllerFlags = 1 << (Component.FlagShift + 5);
static readonly NeedsAssemble: ControllerFlags = 1 << (Component.FlagShift + 6);
/** @internal */
static readonly CompileMask: ControllerFlags = Controller.NeedsCompile
| Controller.NeedsResolve
| Controller.NeedsGenerate
| Controller.NeedsAssemble;
static readonly NeedsExecute: ControllerFlags = 1 << (Component.FlagShift + 7);
static readonly NeedsRevise: ControllerFlags = 1 << (Component.FlagShift + 8);
static readonly NeedsCompute: ControllerFlags = 1 << (Component.FlagShift + 9);
/** @internal */
static readonly ExecuteMask: ControllerFlags = Controller.NeedsExecute
| Controller.NeedsRevise
| Controller.NeedsCompute;
/** @internal */
static readonly UpdateMask: ControllerFlags = Controller.CompileMask
| Controller.ExecuteMask;
/** @internal */
static override readonly FlagShift: number = Component.FlagShift + 10;
/** @internal */
static override readonly FlagMask: ControllerFlags = (1 << Controller.FlagShift) - 1;
static override readonly MountFlags: ControllerFlags = 0;
static override readonly InsertChildFlags: ControllerFlags = 0;
static override readonly RemoveChildFlags: ControllerFlags = 0;
} | the_stack |
import rule from '.';
import { getHtmlRuleTester, getInvalidTestFactory } from '../../test-helper.spec';
const htmlRuleTester = getHtmlRuleTester();
const getInvalidIconTest = getInvalidTestFactory('clrIconFailure');
htmlRuleTester.run('no-clr-icon', rule, {
invalid: [
getInvalidIconTest({
code: `<clr-icon></clr-icon>`,
output: `<cds-icon></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
/**
* Direction attribute
*/
getInvalidIconTest({
code: `<clr-icon dir="left"></clr-icon>`,
output: `<cds-icon direction="left"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon dir="right"></clr-icon>`,
output: `<cds-icon direction="right"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon dir="up"></clr-icon>`,
output: `<cds-icon direction="up"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon dir="down"></clr-icon>`,
output: `<cds-icon direction="down"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
/**
* Direction attribute: already migrated tag (cds-icon)
*/
getInvalidIconTest({
code: `<cds-icon dir="left"></cds-icon>`,
output: `<cds-icon direction="left"></cds-icon>`,
locations: [{ line: 1, column: 11 }],
}),
getInvalidIconTest({
code: `<cds-icon dir="right"></cds-icon>`,
output: `<cds-icon direction="right"></cds-icon>`,
locations: [{ line: 1, column: 11 }],
}),
getInvalidIconTest({
code: `<cds-icon dir="up"></cds-icon>`,
output: `<cds-icon direction="up"></cds-icon>`,
locations: [{ line: 1, column: 11 }],
}),
getInvalidIconTest({
code: `<cds-icon dir="down"></cds-icon>`,
output: `<cds-icon direction="down"></cds-icon>`,
locations: [{ line: 1, column: 11 }],
}),
/**
* Status attribute
*/
getInvalidIconTest({
code: `<clr-icon class="is-green"></clr-icon>`,
output: `<cds-icon status="success"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon class="is-success"></clr-icon>`,
output: `<cds-icon status="success"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon class="is-danger"></clr-icon>`,
output: `<cds-icon status="danger"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon class="is-red"></clr-icon>`,
output: `<cds-icon status="danger"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon class="is-error"></clr-icon>`,
output: `<cds-icon status="danger"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon class="is-warning"></clr-icon>`,
output: `<cds-icon status="warning"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon class="is-info"></clr-icon>`,
output: `<cds-icon status="info"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon class="is-blue"></clr-icon>`,
output: `<cds-icon status="info"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon class="is-highlight"></clr-icon>`,
output: `<cds-icon status="info"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon class="is-white"></clr-icon>`,
output: `<cds-icon inverse></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon class="is-inverse"></clr-icon>`,
output: `<cds-icon inverse></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon class="is-solid"></clr-icon>`,
output: `<cds-icon solid></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
/**
* Status attribute: already migrated tag (cds-icon)
*/
getInvalidIconTest({
code: `<cds-icon class="is-inverse"></cds-icon>`,
output: `<cds-icon inverse></cds-icon>`,
locations: [{ line: 1, column: 18 }],
}),
getInvalidIconTest({
code: `<cds-icon random-attribute class="is-success"></cds-icon>`,
output: `<cds-icon random-attribute status="success"></cds-icon>`,
locations: [{ line: 1, column: 35 }],
}),
getInvalidIconTest({
code: `<cds-icon random-attribute class="is-success is-inverse is-solid"></cds-icon>`,
output: `<cds-icon random-attribute status="success" inverse solid></cds-icon>`,
locations: [{ line: 1, column: 35 }],
}),
getInvalidIconTest({
code: `<cds-icon random-attribute class="is-success my-class is-inverse is-solid"></cds-icon>`,
output: `<cds-icon random-attribute class="my-class" status="success" inverse solid></cds-icon>`,
locations: [{ line: 1, column: 35 }],
}),
/**
* Status attribute: More than one class
*/
getInvalidIconTest({
code: `<clr-icon class="is-inverse my-class"></clr-icon>`,
output: `<cds-icon class="my-class" inverse></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon class="is-inverse is-solid is-success my-class"></clr-icon>`,
output: `<cds-icon class="my-class" inverse solid status="success"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon class="is-inverse is-solid is-success"></clr-icon>`,
output: `<cds-icon inverse solid status="success"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
/**
* Badge attribute
*/
getInvalidIconTest({
code: `<clr-icon class="has-badge"></clr-icon>`,
output: `<cds-icon badge></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon class="has-badge--success"></clr-icon>`,
output: `<cds-icon badge="success"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon class="has-badge--error"></clr-icon>`,
output: `<cds-icon badge="error"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon class="has-badge--info"></clr-icon>`,
output: `<cds-icon badge="info"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon class="has-alert"></clr-icon>`,
output: `<cds-icon badge="triangle"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
/**
* Badge attribute: already migrated tag (cds-icon)
*/
getInvalidIconTest({
code: `<cds-icon class="has-badge"></cds-icon>`,
output: `<cds-icon badge></cds-icon>`,
locations: [{ line: 1, column: 18 }],
}),
getInvalidIconTest({
code: `<cds-icon class="has-badge--success"></cds-icon>`,
output: `<cds-icon badge="success"></cds-icon>`,
locations: [{ line: 1, column: 18 }],
}),
getInvalidIconTest({
code: `<cds-icon class="has-badge--info"></cds-icon>`,
output: `<cds-icon badge="info"></cds-icon>`,
locations: [{ line: 1, column: 18 }],
}),
getInvalidIconTest({
code: `<cds-icon class="has-badge--error"></cds-icon>`,
output: `<cds-icon badge="error"></cds-icon>`,
locations: [{ line: 1, column: 18 }],
}),
getInvalidIconTest({
code: `<cds-icon class="has-alert"></cds-icon>`,
output: `<cds-icon badge="triangle"></cds-icon>`,
locations: [{ line: 1, column: 18 }],
}),
/**
* Shape attribute
*/
getInvalidIconTest({
code: `<clr-icon shape="caret up"></clr-icon>`,
output: `<cds-icon shape="angle" direction="up"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon shape="caret down"></clr-icon>`,
output: `<cds-icon shape="angle" direction="down"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon shape="caret left"></clr-icon>`,
output: `<cds-icon shape="angle" direction="left"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon shape="caret right"></clr-icon>`,
output: `<cds-icon shape="angle" direction="right"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon shape="collapse up"></clr-icon>`,
output: `<cds-icon shape="angle-double" direction="up"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon shape="collapse down"></clr-icon>`,
output: `<cds-icon shape="angle-double" direction="down"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon shape="collapse left"></clr-icon>`,
output: `<cds-icon shape="angle-double" direction="left"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon shape="collapse right"></clr-icon>`,
output: `<cds-icon shape="angle-double" direction="right"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon shape="arrow up"></clr-icon>`,
output: `<cds-icon shape="arrow" direction="up"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon shape="arrow down"></clr-icon>`,
output: `<cds-icon shape="arrow" direction="down"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon shape="arrow left"></clr-icon>`,
output: `<cds-icon shape="arrow" direction="left"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon shape="arrow right"></clr-icon>`,
output: `<cds-icon shape="arrow" direction="right"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
/**
* Shape attribute: already migrated tag (cds-icon)
*/
getInvalidIconTest({
code: `<cds-icon shape="caret up"></cds-icon>`,
output: `<cds-icon shape="angle" direction="up"></cds-icon>`,
locations: [{ line: 1, column: 11 }],
}),
getInvalidIconTest({
code: `<cds-icon shape="caret down"></cds-icon>`,
output: `<cds-icon shape="angle" direction="down"></cds-icon>`,
locations: [{ line: 1, column: 11 }],
}),
getInvalidIconTest({
code: `<cds-icon shape="caret left"></cds-icon>`,
output: `<cds-icon shape="angle" direction="left"></cds-icon>`,
locations: [{ line: 1, column: 11 }],
}),
getInvalidIconTest({
code: `<cds-icon shape="caret right"></cds-icon>`,
output: `<cds-icon shape="angle" direction="right"></cds-icon>`,
locations: [{ line: 1, column: 11 }],
}),
getInvalidIconTest({
code: `<cds-icon shape="collapse up"></cds-icon>`,
output: `<cds-icon shape="angle-double" direction="up"></cds-icon>`,
locations: [{ line: 1, column: 11 }],
}),
getInvalidIconTest({
code: `<cds-icon shape="collapse down"></cds-icon>`,
output: `<cds-icon shape="angle-double" direction="down"></cds-icon>`,
locations: [{ line: 1, column: 11 }],
}),
getInvalidIconTest({
code: `<cds-icon shape="collapse left"></cds-icon>`,
output: `<cds-icon shape="angle-double" direction="left"></cds-icon>`,
locations: [{ line: 1, column: 11 }],
}),
getInvalidIconTest({
code: `<cds-icon shape="collapse right"></cds-icon>`,
output: `<cds-icon shape="angle-double" direction="right"></cds-icon>`,
locations: [{ line: 1, column: 11 }],
}),
getInvalidIconTest({
code: `<cds-icon shape="arrow up"></cds-icon>`,
output: `<cds-icon shape="arrow" direction="up"></cds-icon>`,
locations: [{ line: 1, column: 11 }],
}),
getInvalidIconTest({
code: `<cds-icon shape="arrow down"></cds-icon>`,
output: `<cds-icon shape="arrow" direction="down"></cds-icon>`,
locations: [{ line: 1, column: 11 }],
}),
getInvalidIconTest({
code: `<cds-icon shape="arrow left"></cds-icon>`,
output: `<cds-icon shape="arrow" direction="left"></cds-icon>`,
locations: [{ line: 1, column: 11 }],
}),
getInvalidIconTest({
code: `<cds-icon shape="arrow right"></cds-icon>`,
output: `<cds-icon shape="arrow" direction="right"></cds-icon>`,
locations: [{ line: 1, column: 11 }],
}),
/**
* All attributes
*/
getInvalidIconTest({
code: `<clr-icon dir="left" class="is-inverse my-class is-solid has-badge--info"></clr-icon>`,
output: `<cds-icon direction="left" class="my-class" inverse solid badge="info"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon shape="caret up" class="is-inverse my-class is-solid has-badge--info"></clr-icon>`,
output: `<cds-icon shape="angle" direction="up" class="my-class" inverse solid badge="info"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
/**
* Multiple root elements
*/
getInvalidIconTest({
code: `
<div></div>
<clr-icon shape="caret up" class="is-inverse my-class is-solid has-badge--info"></clr-icon>
`,
output: `
<div></div>
<cds-icon shape="angle" direction="up" class="my-class" inverse solid badge="info"></cds-icon>
`,
locations: [{ line: 3, column: 7 }],
}),
/**
* Persisting extra attributes
*/
getInvalidIconTest({
code: `<clr-icon *ngIf="true"></clr-icon>`,
output: `<cds-icon *ngIf="true"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
getInvalidIconTest({
code: `<clr-icon dir="left" *ngIf="true"></clr-icon>`,
output: `<cds-icon direction="left" *ngIf="true"></cds-icon>`,
locations: [{ line: 1, column: 1 }],
}),
/**
* Two components on the same line
*/
getInvalidIconTest({
code: `<clr-icon></clr-icon><clr-icon></clr-icon>`,
output: `<cds-icon></cds-icon><cds-icon></cds-icon>`,
locations: [
{ line: 1, column: 1 },
{ line: 1, column: 22 },
],
}),
],
valid: [],
}); | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.