@salesforce/core
Version:
Core libraries to interact with SFDX projects, orgs, and APIs.
350 lines • 12.3 kB
JavaScript
"use strict";
/*
* Copyright (c) 2020, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseConfigStore = void 0;
const kit_1 = require("@salesforce/kit");
const ts_types_1 = require("@salesforce/ts-types");
const ts_types_2 = require("@salesforce/ts-types");
const crypto_1 = require("../crypto/crypto");
const sfError_1 = require("../sfError");
/**
* An abstract class that implements all the config management functions but
* none of the storage functions.
*
* **Note:** To see the interface, look in typescripts autocomplete help or the npm package's ConfigStore.d.ts file.
*/
class BaseConfigStore extends kit_1.AsyncOptionalCreatable {
/**
* Constructor.
*
* @param options The options for the class instance.
* @ignore
*/
constructor(options) {
super(options);
this.statics = this.constructor;
this.options = options || {};
this.setContents(this.initialContents());
}
/**
* Returns an array of {@link ConfigEntry} for each element in the config.
*/
entries() {
return (0, ts_types_2.definiteEntriesOf)(this.contents);
}
get(key, decrypt = false) {
const k = key;
let value = this.getMethod(this.contents, k);
if (this.hasEncryption() && decrypt) {
if ((0, ts_types_2.isJsonMap)(value)) {
value = this.recursiveDecrypt((0, kit_1.cloneJson)(value), k);
}
else if (this.isCryptoKey(k)) {
value = this.decrypt(value);
}
}
return value;
}
/**
* Returns the list of keys that contain a value.
*
* @param value The value to filter keys on.
*/
getKeysByValue(value) {
const matchedEntries = this.entries().filter((entry) => entry[1] === value);
// Only return the keys
return matchedEntries.map((entry) => entry[0]);
}
/**
* Returns a boolean asserting whether a value has been associated to the key in the config object or not.
*
* @param key The key. Supports query key like `a.b[0]`.
*/
has(key) {
return !!this.getMethod(this.contents, key);
}
/**
* Returns an array that contains the keys for each element in the config object.
*/
keys() {
return Object.keys(this.contents);
}
set(key, value) {
if (this.hasEncryption()) {
if ((0, ts_types_2.isJsonMap)(value)) {
value = this.recursiveEncrypt(value, key);
}
else if (this.isCryptoKey(key)) {
value = this.encrypt(value);
}
}
this.setMethod(this.contents, key, value);
}
update(key, value) {
const existingValue = this.get(key, true);
if ((0, ts_types_1.isPlainObject)(existingValue) && (0, ts_types_1.isPlainObject)(value)) {
value = Object.assign({}, existingValue, value);
}
this.set(key, value);
}
/**
* Returns `true` if an element in the config object existed and has been removed, or `false` if the element does not
* exist. {@link BaseConfigStore.has} will return false afterwards.
*
* @param key The key. Supports query key like `a.b[0]`.
*/
unset(key) {
if (this.has(key)) {
if (this.contents[key]) {
delete this.contents[key];
}
else {
// It is a query key, so just set it to undefined
this.setMethod(this.contents, key, undefined);
}
return true;
}
return false;
}
/**
* Returns `true` if all elements in the config object existed and have been removed, or `false` if all the elements
* do not exist (some may have been removed). {@link BaseConfigStore.has(key)} will return false afterwards.
*
* @param keys The keys. Supports query keys like `a.b[0]`.
*/
unsetAll(keys) {
return keys.reduce((val, key) => val && this.unset(key), true);
}
/**
* Removes all key/value pairs from the config object.
*/
clear() {
this.contents = {};
}
/**
* Returns an array that contains the values for each element in the config object.
*/
values() {
return (0, ts_types_2.definiteValuesOf)(this.contents);
}
/**
* Returns the entire config contents.
*
* *NOTE:* Data will still be encrypted unless decrypt is passed in. A clone of
* the data will be returned to prevent storing un-encrypted data in memory and
* potentially saving to the file system.
*
* @param decrypt: decrypt all data in the config. A clone of the data will be returned.
*
*/
getContents(decrypt = false) {
if (!this.contents) {
this.setContents();
}
if (this.hasEncryption() && decrypt) {
return this.recursiveDecrypt((0, kit_1.cloneJson)(this.contents));
}
return this.contents;
}
/**
* Sets the entire config contents.
*
* @param contents The contents.
*/
setContents(contents = {}) {
if (this.hasEncryption()) {
contents = this.recursiveEncrypt(contents);
}
this.contents = contents;
}
/**
* Invokes `actionFn` once for each key-value pair present in the config object.
*
* @param {function} actionFn The function `(key: string, value: ConfigValue) => void` to be called for each element.
*/
forEach(actionFn) {
const entries = this.entries();
for (const entry of entries) {
actionFn(entry[0], entry[1]);
}
}
/**
* Asynchronously invokes `actionFn` once for each key-value pair present in the config object.
*
* @param {function} actionFn The function `(key: string, value: ConfigValue) => Promise<void>` to be called for
* each element.
* @returns {Promise<void>}
*/
async awaitEach(actionFn) {
const entries = this.entries();
for (const entry of entries) {
await actionFn(entry[0], entry[1]);
}
}
/**
* Convert the config object to a JSON object. Returns the config contents.
* Same as calling {@link ConfigStore.getContents}
*/
toObject() {
return this.contents;
}
/**
* Convert an object to a {@link ConfigContents} and set it as the config contents.
*
* @param obj The object.
*/
setContentsFromObject(obj) {
this.contents = (this.hasEncryption() ? this.recursiveEncrypt(obj) : {});
Object.entries(obj).forEach(([key, value]) => {
this.setMethod(this.contents, key, value);
});
}
getEncryptedKeys() {
return [...(this.options?.encryptedKeys || []), ...(this.statics?.encryptedKeys || [])];
}
/**
* This config file has encrypted keys and it should attempt to encrypt them.
*
* @returns Has encrypted keys
*/
hasEncryption() {
return this.getEncryptedKeys().length > 0;
}
// Allows extended classes the ability to override the set method. i.e. maybe they want
// nested object set from kit.
setMethod(contents, key, value) {
(0, kit_1.set)(contents, key, value);
}
// Allows extended classes the ability to override the get method. i.e. maybe they want
// nested object get from ts-types.
// NOTE: Key must stay string to be reliably overwritten.
getMethod(contents, key) {
return (0, ts_types_2.get)(contents, key);
}
initialContents() {
return {};
}
/**
* Used to initialize asynchronous components.
*/
async init() {
if (this.hasEncryption()) {
await this.initCrypto();
}
}
/**
* Initialize the crypto dependency.
*/
async initCrypto() {
if (!this.crypto) {
this.crypto = await crypto_1.Crypto.create();
}
}
/**
* Closes the crypto dependency. Crypto should be close after it's used and no longer needed.
*/
// eslint-disable-next-line @typescript-eslint/require-await
async clearCrypto() {
if (this.crypto) {
this.crypto.close();
delete this.crypto;
}
}
/**
* Should the given key be encrypted on set methods and decrypted on get methods.
*
* @param key The key. Supports query key like `a.b[0]`.
* @returns Should encrypt/decrypt
*/
isCryptoKey(key) {
function resolveProperty() {
// Handle query keys
const dotAccessor = /\.([a-zA-Z0-9@._-]+)$/;
const singleQuoteAccessor = /\['([a-zA-Z0-9@._-]+)'\]$/;
const doubleQuoteAccessor = /\["([a-zA-Z0-9@._-]+)"\]$/;
const matcher = dotAccessor.exec(key) || singleQuoteAccessor.exec(key) || doubleQuoteAccessor.exec(key);
return matcher ? matcher[1] : key;
}
// Any keys named the following should be encrypted/decrypted
return (this.statics.encryptedKeys || []).find((keyOrExp) => {
const property = resolveProperty();
if (keyOrExp instanceof RegExp) {
return keyOrExp.test(property);
}
else {
return keyOrExp === property;
}
});
}
encrypt(value) {
if (!value)
return;
if (!this.crypto)
throw new sfError_1.SfError('crypto is not initialized', 'CryptoNotInitializedError');
if (!(0, ts_types_2.isString)(value))
throw new sfError_1.SfError(`can only encrypt strings but found: ${typeof value} : ${value}`, 'InvalidCryptoValueError');
return this.crypto.isEncrypted(value) ? value : this.crypto.encrypt(value);
}
decrypt(value) {
if (!value)
return;
if (!this.crypto)
throw new sfError_1.SfError('crypto is not initialized', 'CryptoNotInitializedError');
if (!(0, ts_types_2.isString)(value))
throw new sfError_1.SfError(`can only encrypt strings but found: ${typeof value} : ${value}`, 'InvalidCryptoValueError');
return this.crypto.isEncrypted(value) ? this.crypto.decrypt(value) : value;
}
/**
* Encrypt all values in a nested JsonMap.
*
* @param keyPaths: The complete path of the (nested) data
* @param data: The current (nested) data being worked on.
*/
recursiveEncrypt(data, parentKey) {
for (const key of Object.keys(data)) {
this.recursiveCrypto(this.encrypt.bind(this), [...(parentKey ? [parentKey] : []), key], data);
}
return data;
}
/**
* Decrypt all values in a nested JsonMap.
*
* @param keyPaths: The complete path of the (nested) data
* @param data: The current (nested) data being worked on.
*/
recursiveDecrypt(data, parentKey) {
for (const key of Object.keys(data)) {
this.recursiveCrypto(this.decrypt.bind(this), [...(parentKey ? [parentKey] : []), key], data);
}
return data;
}
/**
* Encrypt/Decrypt all values in a nested JsonMap.
*
* @param keyPaths: The complete path of the (nested) data
* @param data: The current (nested) data being worked on.
*/
recursiveCrypto(method, keyPaths, data) {
const key = keyPaths.pop();
const value = data[key];
if ((0, ts_types_2.isJsonMap)(value)) {
for (const newKey of Object.keys(value)) {
this.recursiveCrypto(method, [...keyPaths, key, newKey], value);
}
}
else {
if (this.isCryptoKey(key)) {
data[key] = method(value);
}
}
}
}
exports.BaseConfigStore = BaseConfigStore;
// If encryptedKeys is an array of RegExps, they should not contain the /g (global) or /y (sticky) flags to avoid stateful issues.
BaseConfigStore.encryptedKeys = [];
//# sourceMappingURL=configStore.js.map