UNPKG

@simbachain/simbats

Version:
334 lines 13.7 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SimbaConfig = exports.LogLevel = exports.AUTHKEY = exports.simbaEnvFilesArray = exports.SimbaEnvVarKeys = void 0; const configstore_1 = __importDefault(require("configstore")); const path = __importStar(require("path")); const process_1 = require("process"); const tslog_1 = require("tslog"); const dotenv = __importStar(require("dotenv")); const os = __importStar(require("os")); const SIMBA_HOME = process.env.SIMBA_HOME || os.homedir(); const DEFAULT_AUTH_ENDPOINT = "/o/"; var SimbaEnvVarKeys; (function (SimbaEnvVarKeys) { SimbaEnvVarKeys["SIMBA_AUTH_CLIENT_ID"] = "SIMBA_AUTH_CLIENT_ID"; SimbaEnvVarKeys["SIMBA_AUTH_CLIENT_SECRET"] = "SIMBA_AUTH_CLIENT_SECRET"; SimbaEnvVarKeys["SIMBA_API_BASE_URL"] = "SIMBA_API_BASE_URL"; SimbaEnvVarKeys["SIMBA_AUTH_BASE_URL"] = "SIMBA_AUTH_BASE_URL"; SimbaEnvVarKeys["SIMBA_AUTH_SCOPE"] = "SIMBA_AUTH_SCOPE"; SimbaEnvVarKeys["SIMBA_AUTH_REALM"] = "SIMBA_AUTH_REALM"; SimbaEnvVarKeys["SIMBA_AUTH_ENDPOINT"] = "SIMBA_AUTH_ENDPOINT"; SimbaEnvVarKeys["SIMBA_LOGGING_HOME"] = "SIMBA_LOGGING_HOME"; SimbaEnvVarKeys["SIMBA_HOME"] = "SIMBA_HOME"; SimbaEnvVarKeys["SIMBA_LOG_LEVEL"] = "SIMBA_LOG_LEVEL"; })(SimbaEnvVarKeys = exports.SimbaEnvVarKeys || (exports.SimbaEnvVarKeys = {})); var SimbaEnvFiles; (function (SimbaEnvFiles) { SimbaEnvFiles["DOT_SIMBACHAIN_DOT_ENV"] = ".simbachain.env"; SimbaEnvFiles["SIMBACHAIN_DOT_ENV"] = "simbachain.env"; SimbaEnvFiles["DOT_ENV"] = ".env"; })(SimbaEnvFiles || (SimbaEnvFiles = {})); // for ordered iteration purposes exports.simbaEnvFilesArray = [ SimbaEnvFiles.DOT_SIMBACHAIN_DOT_ENV, SimbaEnvFiles.SIMBACHAIN_DOT_ENV, SimbaEnvFiles.DOT_ENV, ]; exports.AUTHKEY = "SIMBAAUTH"; var LogLevel; (function (LogLevel) { LogLevel["SILLY"] = "silly"; LogLevel["TRACE"] = "trace"; LogLevel["DEBUG"] = "debug"; LogLevel["INFO"] = "info"; LogLevel["WARN"] = "warn"; LogLevel["ERROR"] = "error"; LogLevel["FATAL"] = "fatal"; })(LogLevel = exports.LogLevel || (exports.LogLevel = {})); class SimbaConfig { /** * handles our auth / access token info */ static get authConfig() { if (!this._authConfig) { this._authConfig = new configstore_1.default(`@simbachain/SimbaTS`, null, { configPath: path.join(process_1.cwd(), 'authconfig.json'), }); } return this._authConfig; } /** * handles project info, contained in simba.json * simba.json is not currently used in SimbaTS, but * there may be a use case for storing project info in the future */ static get ProjectConfigStore() { if (!this._projectConfigStore) { this._projectConfigStore = new configstore_1.default(`@simbachain/simbats`, null, { configPath: path.join(process_1.cwd(), 'simba.json'), }); } return this._projectConfigStore; } /** * this is what we use for logging */ static get log() { const logLevel = SimbaConfig.logLevel; const logger = new tslog_1.Logger({ minLevel: logLevel }); return logger; } /** * how we get loglevel */ static get logLevel() { const level = SimbaConfig.retrieveEnvVar(SimbaEnvVarKeys.SIMBA_LOG_LEVEL); if (level && !Object.values(LogLevel).includes(level)) { console.error(`SimbaConfig.logLevel :: SIMBA : EXIT : unrecognized SIMBA_LOG_LEVEL - ${level} set in ${SimbaConfig.simbaEnvVarFile} : ${level} : using level "info" instead. Please note that LOG_LEVEL can be one of ${Object.values(LogLevel)}`); return LogLevel.INFO; } if (!level) { return LogLevel.INFO; } return process.env[SimbaEnvVarKeys.SIMBA_LOG_LEVEL]; } /** * retrieves SIMBA_API_BASE_URL from env file */ static get baseURL() { SimbaConfig.log.debug(`:: SIMBA : ENTER :`); const baseURL = SimbaConfig.retrieveEnvVar(SimbaEnvVarKeys.SIMBA_API_BASE_URL); SimbaConfig.log.debug(`:: SIMBA : EXIT : baseURL : ${baseURL}`); return baseURL; } /** * helper function for setting env vars, so we're not repeating loop code * @param dir * @param foundKeys * @returns */ static setEnvVarsFromDirectory(dir, foundKeys) { if (!foundKeys.length) { foundKeys.push(SimbaEnvVarKeys.SIMBA_AUTH_ENDPOINT); SimbaConfig.envVars[SimbaEnvVarKeys.SIMBA_AUTH_ENDPOINT] = DEFAULT_AUTH_ENDPOINT; } for (let i = 0; i < exports.simbaEnvFilesArray.length; i++) { if (foundKeys.length === Object.values(SimbaEnvVarKeys).length) { SimbaConfig.log.debug(`:: EXIT : ${JSON.stringify(SimbaConfig.envVars)}`); return; } const fileName = exports.simbaEnvFilesArray[i]; dotenv.config({ override: true, path: path.resolve(dir, fileName), }); for (let j = 0; j < Object.values(SimbaEnvVarKeys).length; j++) { const envVarKey = Object.values(SimbaEnvVarKeys)[j]; if (foundKeys.includes(envVarKey)) { continue; } else { const simbaKey = Object.values(SimbaEnvVarKeys)[j]; const val = process.env[simbaKey]; if (val) { SimbaConfig.envVars[simbaKey] = val; foundKeys.push(envVarKey); } } } } } /** * this method only gets called once, when a process first tries to retrieve an env var * if SimbaConfig.envVars's values is zero length, then we call this method * * The code is a bit convoluted, so here's the process: * 1. iterate through file names of (.simbachain.env, simbachain.env, .env) in our project root * 2. we then loop through each of our SimbaEnvVarKeys until we find all of them, or * we have finished going through all files (not all env vars are necessary to be set) * 3. we then run through 1-4 again, but we use SIMBA_HOME instead of project root * 4. set as SimbaConfig.envVars once finished * @returns {Promise<Record<any, any>>} */ static setEnvVars() { const foundKeys = []; SimbaConfig.setEnvVarsFromDirectory(process_1.cwd(), foundKeys); SimbaConfig.setEnvVarsFromDirectory(SIMBA_HOME, foundKeys); return SimbaConfig.envVars; } /** * retrieves value for env var key. looks for: * * if SimbaConfig.envVars values has zero length, we first call SimbaConfig.setEnvVars * @param SimbaEnvVarKeys * @returns */ static retrieveEnvVar(envVarKey) { let envVars; if (!Object.values(SimbaConfig.envVars).length) { envVars = SimbaConfig.setEnvVars(); } else { envVars = SimbaConfig.envVars; } const val = envVars[envVarKey]; if (val) { return val; } const message = `Unable to find value for ${envVarKey}. You can set this in one of the following file names: .simbachain.env, simbachain.env, or .env; and these files can live in your local project root (best option) or in the directory that SIMBA_HOME points to in your system env vars.`; // SimbaConfig.log.error(`${chalk.redBright(`:: EXIT : ${message}`)}`); throw new Error(message); } /** * sets auth token in authconfig.json * @param authToken * @returns */ static setAuthToken(authToken) { SimbaConfig.log.debug(`:: SIMBA : ENTER :`); SimbaConfig.authConfig.set(exports.AUTHKEY, authToken); SimbaConfig.log.debug(`:: SIMBA : EXIT :`); return; } /** * retrieves auth token from authconfig.json * @returns {Record<any, any>} */ static getAuthTokenFromConfig() { SimbaConfig.log.debug(`:: SIMBA : ENTER :`); const authToken = SimbaConfig.authConfig.get(exports.AUTHKEY) ? SimbaConfig.authConfig.get(exports.AUTHKEY) : {}; SimbaConfig.log.debug(`:: SIMBA : EXIT :`); return authToken; } /** * takes in an auth token and adds new fields, such as retrieved_at and expires_at * @param authToken * @returns {Record<any, any>} */ static parseExpiry(authToken) { SimbaConfig.log.debug(`:: SIMBA : ENTER :`); if ('expires_in' in authToken) { const retrievedAt = new Date(); const expiresIn = parseInt(authToken.expires_in, 10) * 1000; const expiresAt = new Date(Date.parse(retrievedAt.toISOString()) + expiresIn); authToken.retrieved_at = retrievedAt.toISOString(); authToken.expires_at = expiresAt.toISOString(); if (authToken.refresh_expires_in) { const refreshExpiresIn = parseInt(authToken.refresh_expires_in, 10) * 1000; const refreshExpiresAt = new Date(Date.parse(retrievedAt.toISOString()) + refreshExpiresIn); authToken.refresh_expires_at = refreshExpiresAt.toISOString(); } } SimbaConfig.log.debug(`:: SIMBA : EXIT :`); return authToken; } /** * parses auth token and sets it in authconfig.json * @param authToken * @returns {Record<any, any>} */ static getAndSetParsedAuthToken(authToken) { SimbaConfig.log.debug(`:: SIMBA : ENTER :`); const parsedToken = SimbaConfig.parseExpiry(authToken); SimbaConfig.setAuthToken(parsedToken); SimbaConfig.log.debug(`:: SIMBA : EXIT :`); return parsedToken; } /** * checks if auth token is expired. used as a check before we make http call * idea is to check for bad token before http call, if possible * @returns {boolean} */ static tokenExpired() { SimbaConfig.log.debug(`:: SIMBA : ENTER :`); if (!SimbaConfig.authConfig.has(exports.AUTHKEY)) { SimbaConfig.log.debug(`:: SIMBA : EXIT : no auth token exists, exiting with true`); return true; } const authToken = SimbaConfig.authConfig.get(exports.AUTHKEY); if (!authToken.expires_at) { SimbaConfig.log.debug(`:: SIMBA : EXIT : true`); return true; } if (new Date(authToken.expires_at) <= new Date()) { SimbaConfig.log.debug(`:: SIMBA : EXIT : auth token expired, returning true`); return true; } SimbaConfig.log.debug(`:: SIMBA : EXIT : false`); return false; } /** * checks if refresh token is expired. used as a check before we make http call * idea is to check for bad token before http call, if possible * * Note: likely won't use, since the SDK will use client creds, and the * access token for client creds does not have a refresh token * @returns {boolean} */ refreshTokenExpired() { SimbaConfig.log.debug(`:: SIMBA : ENTER :`); if (!SimbaConfig.authConfig.has(exports.AUTHKEY)) { SimbaConfig.log.debug(`:: SIMBA : EXIT : true`); return true; } const authToken = SimbaConfig.authConfig.get(exports.AUTHKEY); if (!authToken.refresh_expires_at) { SimbaConfig.log.debug(`:: SIMBA : EXIT : true`); return true; } if (new Date(authToken.refresh_expires_at) <= new Date()) { SimbaConfig.log.debug(`:: SIMBA : EXIT : refresh_token expired, returning true`); return true; } SimbaConfig.log.debug(`:: SIMBA : EXIT : false`); return false; } /** * set a field in auth token in authconfig.json * @param fieldKey * @param fieldVal * @returns */ static setAuthTokenField(fieldKey, fieldVal) { const params = { fieldKey, fieldVal, }; const authToken = SimbaConfig.authConfig.get(exports.AUTHKEY) ? SimbaConfig.authConfig.get(exports.AUTHKEY) : {}; SimbaConfig.log.debug(`:: SIMBA : ENTER : ${JSON.stringify(params)}`); authToken[fieldKey] = fieldVal; SimbaConfig.authConfig.set(exports.AUTHKEY, authToken); SimbaConfig.log.debug(`:: SIMBA : EXIT`); return; } } exports.SimbaConfig = SimbaConfig; SimbaConfig.simbaEnvVarFileConfigured = false; SimbaConfig.envVars = {}; //# sourceMappingURL=config.js.map