UNPKG

@sasjs/cli

Version:

Command line interface for SASjs

978 lines 62.4 kB
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getSASjsAndAuthConfig = exports.getSASjs = exports.getTestTearDown = exports.getTestSetUp = exports.overrideEnvVariables = exports.getAccessToken = exports.getAuthConfigSAS9 = exports.saveTokens = exports.getAuthConfig = exports.getProjectRoot = exports.sanitizeAppLoc = exports.getStreamConfig = exports.getMacroFolders = exports.getBinaryFolders = exports.getProgramFolders = exports.getFolders = exports.saveToLocalConfig = exports.saveLocalConfigFile = exports.getSyncDirectories = exports.getLocalOrGlobalConfig = exports.getLocalConfig = exports.removeFromLocalConfig = exports.removeFromGlobalConfig = exports.saveToGlobalConfig = exports.saveGlobalRcFile = exports.getLocalRcFile = exports.getGlobalRcFile = exports.findTargetInConfiguration = exports.getConfiguration = void 0; var node_1 = __importDefault(require("@sasjs/adapter/node")); var utils_1 = require("@sasjs/utils"); var auth_1 = require("./auth"); var path_1 = __importDefault(require("path")); var dotenv_1 = __importDefault(require("dotenv")); var targetScope_1 = require("../types/targetScope"); var utils_2 = require("./utils"); var ERROR_MESSAGE = function (targetName) { if (targetName === void 0) { targetName = ''; } return { NOT_FOUND_TARGET_NAME: "Target `".concat(targetName, "` was not found.\nPlease check the target name and try again, or use `sasjs add` to add a new target.\nMore info: https://cli.sasjs.io/faq/#what-is-the-difference-between-local-and-global-targets\n"), NOT_FOUND_FALLBACK: "No target was found.\nPlease check the target name and try again, or use `sasjs add` to add a new target.\nMore info: https://cli.sasjs.io/faq/#what-is-the-difference-between-local-and-global-targets\n" }; }; /** * Returns an object that represents the SASjs CLI configuration in a given file. * @param {string} pathToFile - the path to the file in question. * @returns {Configuration} configuration object if available. */ function getConfiguration(pathToFile) { return __awaiter(this, void 0, void 0, function () { var config, configJson; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, (0, utils_1.readFile)(pathToFile).catch(function () { return null; })]; case 1: config = _a.sent(); if (config) { configJson = JSON.parse(config); return [2 /*return*/, (configJson.config ? configJson.config : configJson)]; } throw new Error("No configuration was found at path ".concat(pathToFile, " .")); } }); }); } exports.getConfiguration = getConfiguration; /** * Returns the target with the given name. * If the target is not found in the local configuration, * this function then looks in the global configuration. * If it is still unable to find it, it throws an error. * @param {string} targetName - the name of the target in question. * @param {TargetScope} targetScope - if specified will either consider only Local OR only Global targets. * @returns {Target} target or fallback when one is found. */ function findTargetInConfiguration(targetName, targetScope) { return __awaiter(this, void 0, void 0, function () { var rootDir, _a, _b, target, e_1, e_2, e_3, e_4; var _c, _d, _e, _f; return __generator(this, function (_g) { switch (_g.label) { case 0: return [4 /*yield*/, getProjectRoot()]; case 1: rootDir = _g.sent(); if (rootDir !== process.projectDir) process.projectDir = rootDir; if (!(targetScope === targetScope_1.TargetScope.Local)) return [3 /*break*/, 6]; if (!targetName) return [3 /*break*/, 3]; _c = {}; return [4 /*yield*/, getLocalTarget(targetName)]; case 2: _a = (_c.target = _g.sent(), _c.isLocal = true, _c); return [3 /*break*/, 5]; case 3: _d = {}; return [4 /*yield*/, getLocalFallbackTarget()]; case 4: _a = (_d.target = _g.sent(), _d.isLocal = true, _d); _g.label = 5; case 5: return [2 /*return*/, _a]; case 6: if (!(targetScope === targetScope_1.TargetScope.Global)) return [3 /*break*/, 11]; if (!targetName) return [3 /*break*/, 8]; _e = {}; return [4 /*yield*/, getGlobalTarget(targetName)]; case 7: _b = (_e.target = _g.sent(), _e.isLocal = false, _e); return [3 /*break*/, 10]; case 8: _f = {}; return [4 /*yield*/, getGlobalFallbackTarget()]; case 9: _b = (_f.target = _g.sent(), _f.isLocal = false, _f); _g.label = 10; case 10: return [2 /*return*/, _b]; case 11: if (!targetName) return [3 /*break*/, 20]; _g.label = 12; case 12: _g.trys.push([12, 14, , 15]); return [4 /*yield*/, getLocalTarget(targetName)]; case 13: target = _g.sent(); return [3 /*break*/, 15]; case 14: e_1 = _g.sent(); if (e_1.message !== ERROR_MESSAGE(targetName).NOT_FOUND_TARGET_NAME) throw e_1; return [3 /*break*/, 15]; case 15: if (target) return [2 /*return*/, { target: target, isLocal: true }]; _g.label = 16; case 16: _g.trys.push([16, 18, , 19]); return [4 /*yield*/, getGlobalTarget(targetName)]; case 17: target = _g.sent(); return [3 /*break*/, 19]; case 18: e_2 = _g.sent(); if (e_2.message !== ERROR_MESSAGE(targetName).NOT_FOUND_TARGET_NAME) throw e_2; return [3 /*break*/, 19]; case 19: if (target) return [2 /*return*/, { target: target, isLocal: false }]; throw new Error(ERROR_MESSAGE(targetName).NOT_FOUND_TARGET_NAME); case 20: _g.trys.push([20, 22, , 23]); return [4 /*yield*/, getLocalFallbackTarget()]; case 21: target = _g.sent(); return [3 /*break*/, 23]; case 22: e_3 = _g.sent(); if (e_3.message !== ERROR_MESSAGE().NOT_FOUND_FALLBACK) throw e_3; return [3 /*break*/, 23]; case 23: if (target) return [2 /*return*/, { target: target, isLocal: true }]; _g.label = 24; case 24: _g.trys.push([24, 26, , 27]); return [4 /*yield*/, getGlobalFallbackTarget()]; case 25: target = _g.sent(); return [3 /*break*/, 27]; case 26: e_4 = _g.sent(); if (e_4.message !== ERROR_MESSAGE().NOT_FOUND_FALLBACK) throw e_4; return [3 /*break*/, 27]; case 27: if (target) return [2 /*return*/, { target: target, isLocal: false }]; throw new Error("Unable to find any default target.\nPlease check the target name and try again, or use `sasjs add` to add a new target.\nMore info: https://cli.sasjs.io/sasjsconfig.html#defaultTarget\n"); } }); }); } exports.findTargetInConfiguration = findTargetInConfiguration; function getLocalTarget(targetName) { var _a; return __awaiter(this, void 0, void 0, function () { var localConfig, targetJson, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: return [4 /*yield*/, getConfiguration(path_1.default.join(process.projectDir, 'sasjs', 'sasjsconfig.json')).catch(function () { return null; })]; case 1: localConfig = _c.sent(); if (!(localConfig === null || localConfig === void 0 ? void 0 : localConfig.targets)) return [3 /*break*/, 3]; targetJson = localConfig.targets.find(function (t) { return t.name === targetName; }); if (!targetJson) return [3 /*break*/, 3]; (_a = process.logger) === null || _a === void 0 ? void 0 : _a.info("Target ".concat(targetName, " was found in your local sasjsconfig.json file.")); targetJson.appLoc = sanitizeAppLoc(targetJson.appLoc); if (!targetJson.hasOwnProperty('serverUrl')) { targetJson.serverUrl = ''; } targetJson.serverUrl = (0, utils_1.urlOrigin)(targetJson.serverUrl); _b = targetJson; return [4 /*yield*/, getPrecedenceOfHttpsAgentOptionsAndContent(localConfig, targetJson)]; case 2: _b.httpsAgentOptions = _c.sent(); return [2 /*return*/, new utils_1.Target(targetJson, localConfig)]; case 3: throw new Error(ERROR_MESSAGE(targetName).NOT_FOUND_TARGET_NAME); } }); }); } function getLocalFallbackTarget() { var _a, _b; return __awaiter(this, void 0, void 0, function () { var localConfig, fallBackTargetJson, defaultTargetName_1, _c; return __generator(this, function (_d) { switch (_d.label) { case 0: return [4 /*yield*/, getConfiguration(path_1.default.join(process.projectDir, 'sasjs', 'sasjsconfig.json')).catch(function () { return null; })]; case 1: localConfig = _d.sent(); if (!(localConfig === null || localConfig === void 0 ? void 0 : localConfig.targets)) return [3 /*break*/, 4]; defaultTargetName_1 = localConfig === null || localConfig === void 0 ? void 0 : localConfig.defaultTarget; if (defaultTargetName_1) { fallBackTargetJson = (_a = localConfig === null || localConfig === void 0 ? void 0 : localConfig.targets) === null || _a === void 0 ? void 0 : _a.find(function (t) { return t.name === defaultTargetName_1; }); } if (!fallBackTargetJson) return [3 /*break*/, 4]; (_b = process.logger) === null || _b === void 0 ? void 0 : _b.info("No target was specified. Falling back to default target '".concat(fallBackTargetJson.name, "' from your local sasjsconfig.json file.")); fallBackTargetJson.appLoc = sanitizeAppLoc(fallBackTargetJson.appLoc); if (!fallBackTargetJson.hasOwnProperty('serverUrl')) { fallBackTargetJson.serverUrl = ''; } fallBackTargetJson.serverUrl = (0, utils_1.urlOrigin)(fallBackTargetJson.serverUrl); _c = fallBackTargetJson; return [4 /*yield*/, getPrecedenceOfHttpsAgentOptionsAndContent(localConfig, fallBackTargetJson)]; case 2: _c.httpsAgentOptions = _d.sent(); return [4 /*yield*/, (0, utils_2.loadEnvVariables)(".env.".concat(fallBackTargetJson.name))]; case 3: _d.sent(); return [2 /*return*/, new utils_1.Target(fallBackTargetJson, localConfig)]; case 4: throw new Error(ERROR_MESSAGE().NOT_FOUND_FALLBACK); } }); }); } function getGlobalTarget(targetName) { var _a; return __awaiter(this, void 0, void 0, function () { var globalConfig, targetJson, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: return [4 /*yield*/, getGlobalRcFile()]; case 1: globalConfig = _c.sent(); if (!(globalConfig === null || globalConfig === void 0 ? void 0 : globalConfig.targets)) return [3 /*break*/, 3]; targetJson = globalConfig.targets.find(function (t) { return t.name === targetName; }); if (!targetJson) return [3 /*break*/, 3]; (_a = process.logger) === null || _a === void 0 ? void 0 : _a.info("Target ".concat(targetName, " was found in your global .sasjsrc file.")); targetJson.appLoc = sanitizeAppLoc(targetJson.appLoc); if (!targetJson.hasOwnProperty('serverUrl')) { targetJson.serverUrl = ''; } targetJson.serverUrl = (0, utils_1.urlOrigin)(targetJson.serverUrl); _b = targetJson; return [4 /*yield*/, getPrecedenceOfHttpsAgentOptionsAndContent(globalConfig, targetJson)]; case 2: _b.httpsAgentOptions = _c.sent(); return [2 /*return*/, new utils_1.Target(targetJson, globalConfig)]; case 3: throw new Error(ERROR_MESSAGE(targetName).NOT_FOUND_TARGET_NAME); } }); }); } function getGlobalFallbackTarget() { var _a, _b; return __awaiter(this, void 0, void 0, function () { var globalConfig, fallBackTargetJson, defaultTargetName, _c; return __generator(this, function (_d) { switch (_d.label) { case 0: return [4 /*yield*/, getGlobalRcFile()]; case 1: globalConfig = (_d.sent()); defaultTargetName = globalConfig === null || globalConfig === void 0 ? void 0 : globalConfig.defaultTarget; if (defaultTargetName) { fallBackTargetJson = (_a = globalConfig === null || globalConfig === void 0 ? void 0 : globalConfig.targets) === null || _a === void 0 ? void 0 : _a.find(function (t) { return t.name === defaultTargetName; }); } if (!fallBackTargetJson) return [3 /*break*/, 3]; (_b = process.logger) === null || _b === void 0 ? void 0 : _b.info("No target was specified. Falling back to default target '".concat(fallBackTargetJson.name, "' from your global .sasjsrc file.")); fallBackTargetJson.appLoc = sanitizeAppLoc(fallBackTargetJson.appLoc); if (!fallBackTargetJson.hasOwnProperty('serverUrl')) { fallBackTargetJson.serverUrl = ''; } fallBackTargetJson.serverUrl = (0, utils_1.urlOrigin)(fallBackTargetJson.serverUrl); _c = fallBackTargetJson; return [4 /*yield*/, getPrecedenceOfHttpsAgentOptionsAndContent(globalConfig, fallBackTargetJson)]; case 2: _c.httpsAgentOptions = _d.sent(); return [2 /*return*/, new utils_1.Target(fallBackTargetJson, globalConfig)]; case 3: throw new Error(ERROR_MESSAGE().NOT_FOUND_FALLBACK); } }); }); } function getGlobalRcFile() { return __awaiter(this, void 0, void 0, function () { var homeDir, sasjsRcFileContent; return __generator(this, function (_a) { switch (_a.label) { case 0: homeDir = require('os').homedir(); return [4 /*yield*/, (0, utils_1.readFile)(path_1.default.join(homeDir, '.sasjsrc')).catch(function () { return null; })]; case 1: sasjsRcFileContent = _a.sent(); return [2 /*return*/, sasjsRcFileContent ? JSON.parse(sasjsRcFileContent) : sasjsRcFileContent]; } }); }); } exports.getGlobalRcFile = getGlobalRcFile; function getLocalRcFile() { return __awaiter(this, void 0, void 0, function () { var projectRoot, config; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, getProjectRoot()]; case 1: projectRoot = _a.sent(); if (!projectRoot) { return [2 /*return*/, null]; } return [4 /*yield*/, getConfiguration(path_1.default.join(projectRoot, '.sasjsrc'))]; case 2: config = _a.sent(); return [2 /*return*/, config]; } }); }); } exports.getLocalRcFile = getLocalRcFile; function saveGlobalRcFile(content) { return __awaiter(this, void 0, void 0, function () { var homeDir, rcFilePath; return __generator(this, function (_a) { switch (_a.label) { case 0: homeDir = require('os').homedir(); rcFilePath = path_1.default.join(homeDir, '.sasjsrc'); return [4 /*yield*/, (0, utils_1.createFile)(rcFilePath, content)]; case 1: _a.sent(); return [2 /*return*/, rcFilePath]; } }); }); } exports.saveGlobalRcFile = saveGlobalRcFile; function saveToGlobalConfig(target, isDefault, saveWithDefaultValues) { var _a; if (isDefault === void 0) { isDefault = false; } if (saveWithDefaultValues === void 0) { saveWithDefaultValues = true; } return __awaiter(this, void 0, void 0, function () { var globalConfig, targetJson, existingTargetIndex; return __generator(this, function (_b) { switch (_b.label) { case 0: return [4 /*yield*/, getGlobalRcFile()]; case 1: globalConfig = _b.sent(); targetJson = target.toJson(saveWithDefaultValues); if ((_a = targetJson.httpsAgentOptions) === null || _a === void 0 ? void 0 : _a.ca) { targetJson.httpsAgentOptions.ca = undefined; } if (globalConfig) { if (globalConfig.targets && globalConfig.targets.length) { existingTargetIndex = globalConfig.targets.findIndex(function (t) { return t.name === target.name; }); if (existingTargetIndex > -1) { globalConfig.targets[existingTargetIndex] = targetJson; } else { globalConfig.targets.push(targetJson); } } else { globalConfig.targets = [targetJson]; } } else { globalConfig = { targets: [targetJson] }; } if (isDefault) { globalConfig.defaultTarget = target.name; } return [4 /*yield*/, saveGlobalRcFile(JSON.stringify(globalConfig, null, 2))]; case 2: return [2 /*return*/, _b.sent()]; } }); }); } exports.saveToGlobalConfig = saveToGlobalConfig; function removeFromGlobalConfig(targetName) { return __awaiter(this, void 0, void 0, function () { var globalConfig, targets; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, getGlobalRcFile()]; case 1: globalConfig = (_a.sent()); if (!(globalConfig && globalConfig.targets && globalConfig.targets.length)) return [3 /*break*/, 3]; targets = globalConfig.targets.filter(function (t) { return t.name !== targetName; }); if (globalConfig.defaultTarget === targetName) { globalConfig.defaultTarget = ''; } return [4 /*yield*/, saveGlobalRcFile(JSON.stringify(__assign(__assign({}, globalConfig), { targets: targets }), null, 2))]; case 2: _a.sent(); _a.label = 3; case 3: return [2 /*return*/]; } }); }); } exports.removeFromGlobalConfig = removeFromGlobalConfig; function removeFromLocalConfig(targetName) { return __awaiter(this, void 0, void 0, function () { var config, targets, configPath; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, getLocalConfig()]; case 1: config = (_a.sent()); if (!(config && config.targets && config.targets.length)) return [3 /*break*/, 3]; targets = config.targets.filter(function (t) { return t.name !== targetName; }); if (config.defaultTarget === targetName) { config.defaultTarget = ''; } configPath = path_1.default.join(process.projectDir, 'sasjs', 'sasjsconfig.json'); return [4 /*yield*/, (0, utils_1.createFile)(configPath, JSON.stringify(__assign(__assign({}, config), { targets: targets }), null, 2))]; case 2: _a.sent(); _a.label = 3; case 3: return [2 /*return*/]; } }); }); } exports.removeFromLocalConfig = removeFromLocalConfig; function getLocalConfig() { return __awaiter(this, void 0, void 0, function () { var config; return __generator(this, function (_a) { switch (_a.label) { case 0: return [4 /*yield*/, getConfiguration(path_1.default.join(process.projectDir, 'sasjs', 'sasjsconfig.json'))]; case 1: config = _a.sent(); return [2 /*return*/, config]; } }); }); } exports.getLocalConfig = getLocalConfig; function getLocalOrGlobalConfig() { return __awaiter(this, void 0, void 0, function () { var e_5; var _a, _b; return __generator(this, function (_c) { switch (_c.label) { case 0: _c.trys.push([0, 2, , 4]); _a = {}; return [4 /*yield*/, getLocalConfig()]; case 1: return [2 /*return*/, (_a.configuration = _c.sent(), _a.isLocal = true, _a)]; case 2: e_5 = _c.sent(); _b = {}; return [4 /*yield*/, getGlobalRcFile()]; case 3: return [2 /*return*/, (_b.configuration = _c.sent(), _b.isLocal = false, _b)]; case 4: return [2 /*return*/]; } }); }); } exports.getLocalOrGlobalConfig = getLocalOrGlobalConfig; function getSyncDirectories(target, isLocal) { return __awaiter(this, void 0, void 0, function () { var config, _a, rootLevelSyncDirectories, targetLevelSyncDirectories; return __generator(this, function (_b) { switch (_b.label) { case 0: if (!isLocal) return [3 /*break*/, 2]; return [4 /*yield*/, getLocalConfig()]; case 1: _a = _b.sent(); return [3 /*break*/, 4]; case 2: return [4 /*yield*/, getGlobalRcFile()]; case 3: _a = _b.sent(); _b.label = 4; case 4: config = _a; rootLevelSyncDirectories = config.syncDirectories || []; targetLevelSyncDirectories = target.syncDirectories || []; return [2 /*return*/, __spreadArray(__spreadArray([], __read(rootLevelSyncDirectories), false), __read(targetLevelSyncDirectories), false)]; } }); }); } exports.getSyncDirectories = getSyncDirectories; function saveLocalConfigFile(content) { return __awaiter(this, void 0, void 0, function () { var configPath; return __generator(this, function (_a) { switch (_a.label) { case 0: configPath = path_1.default.join(process.projectDir, 'sasjs', 'sasjsconfig.json'); return [4 /*yield*/, (0, utils_1.createFile)(configPath, content)]; case 1: _a.sent(); return [2 /*return*/, configPath]; } }); }); } exports.saveLocalConfigFile = saveLocalConfigFile; function saveToLocalConfig(target, isDefault, saveWithDefaultValues) { var _a, _b; if (isDefault === void 0) { isDefault = false; } if (saveWithDefaultValues === void 0) { saveWithDefaultValues = true; } return __awaiter(this, void 0, void 0, function () { var targetJson, config, existingTargetIndex, configPath; return __generator(this, function (_c) { switch (_c.label) { case 0: targetJson = target.toJson(saveWithDefaultValues); if ((_a = targetJson.httpsAgentOptions) === null || _a === void 0 ? void 0 : _a.ca) { targetJson.httpsAgentOptions.ca = undefined; } return [4 /*yield*/, getLocalConfig()]; case 1: config = _c.sent(); if (config) { if ((_b = config === null || config === void 0 ? void 0 : config.targets) === null || _b === void 0 ? void 0 : _b.length) { existingTargetIndex = config.targets.findIndex(function (t) { return t.name === target.name; }); if (existingTargetIndex > -1) { config.targets[existingTargetIndex] = targetJson; } else { config.targets.push(targetJson); } } else { config.targets = [targetJson]; } } else { config = { targets: [targetJson] }; } if (isDefault) { config.defaultTarget = target.name; } configPath = path_1.default.join(process.projectDir, 'sasjs', 'sasjsconfig.json'); return [4 /*yield*/, (0, utils_1.createFile)(configPath, JSON.stringify(config, null, 2))]; case 2: _c.sent(); return [2 /*return*/, configPath]; } }); }); } exports.saveToLocalConfig = saveToLocalConfig; function getFolders() { return __awaiter(this, void 0, void 0, function () { var configPath, config, configJson; return __generator(this, function (_a) { switch (_a.label) { case 0: configPath = '../config.json'; return [4 /*yield*/, (0, utils_1.readFile)(path_1.default.join(__dirname, configPath))]; case 1: config = _a.sent(); if (config) { configJson = JSON.parse(config); return [2 /*return*/, Promise.resolve(configJson.folders)]; } return [2 /*return*/, Promise.reject()]; } }); }); } exports.getFolders = getFolders; /** * Returns SAS program folders from configuration. * This list includes both common and target-specific folders. * @param {Target} target- the target to check program folders for. */ function getProgramFolders(target) { return __awaiter(this, void 0, void 0, function () { var programFolders, configuration, buildSourceFolder, programFoldersWithAbsolutePath; return __generator(this, function (_a) { programFolders = []; configuration = process.sasjsConfig; if (configuration === null || configuration === void 0 ? void 0 : configuration.programFolders) { programFolders.push.apply(programFolders, __spreadArray([], __read(configuration.programFolders), false)); } if (target === null || target === void 0 ? void 0 : target.programFolders) { programFolders.push.apply(programFolders, __spreadArray([], __read(target.programFolders), false)); } buildSourceFolder = process.sasjsConstants.buildSourceFolder; programFoldersWithAbsolutePath = programFolders.map(function (programFolder) { return (0, utils_1.getAbsolutePath)(programFolder, buildSourceFolder); }); return [2 /*return*/, __spreadArray([], __read(new Set(programFoldersWithAbsolutePath)), false)]; }); }); } exports.getProgramFolders = getProgramFolders; function getBinaryFolders(target) { return __awaiter(this, void 0, void 0, function () { var binaryFolders, configuration, buildSourceFolder, binaryFoldersWithAbsolutePath; return __generator(this, function (_a) { binaryFolders = []; configuration = process.sasjsConfig; if (configuration === null || configuration === void 0 ? void 0 : configuration.binaryFolders) { binaryFolders.push.apply(binaryFolders, __spreadArray([], __read(configuration.binaryFolders), false)); } if (target === null || target === void 0 ? void 0 : target.binaryFolders) { binaryFolders.push.apply(binaryFolders, __spreadArray([], __read(target.binaryFolders), false)); } buildSourceFolder = process.sasjsConstants.buildSourceFolder; binaryFoldersWithAbsolutePath = binaryFolders.map(function (binaryFolder) { return (0, utils_1.getAbsolutePath)(binaryFolder, buildSourceFolder); }); return [2 /*return*/, __spreadArray([], __read(new Set(binaryFoldersWithAbsolutePath)), false)]; }); }); } exports.getBinaryFolders = getBinaryFolders; /** * Returns SAS macro folders from configuration. * This list includes both common and target-specific folders. * @param {Target} target- the target to check macro folders for. */ function getMacroFolders(target) { return __awaiter(this, void 0, void 0, function () { var configuration, macroFolders, buildSourceFolder, macroFoldersWithAbsolutePath; return __generator(this, function (_a) { configuration = process.sasjsConfig; macroFolders = []; if (configuration === null || configuration === void 0 ? void 0 : configuration.macroFolders) { macroFolders.push.apply(macroFolders, __spreadArray([], __read(configuration.macroFolders), false)); } if (target === null || target === void 0 ? void 0 : target.macroFolders) macroFolders.push.apply(macroFolders, __spreadArray([], __read(target.macroFolders), false)); buildSourceFolder = process.sasjsConstants.buildSourceFolder; macroFoldersWithAbsolutePath = macroFolders.map(function (macroFolder) { return (0, utils_1.getAbsolutePath)(macroFolder, buildSourceFolder); }); return [2 /*return*/, __spreadArray([], __read(new Set(macroFoldersWithAbsolutePath)), false)]; }); }); } exports.getMacroFolders = getMacroFolders; /** * Returns StreamConfig from configuration. * This configuration includes both common and target-specific configuration. * @param {Target} target- the target to check stream configuration for. */ function getStreamConfig(target) { return __awaiter(this, void 0, void 0, function () { var configuration; return __generator(this, function (_a) { configuration = process.sasjsConfig; return [2 /*return*/, __assign(__assign({ streamServiceName: 'clickme' }, configuration === null || configuration === void 0 ? void 0 : configuration.streamConfig), target === null || target === void 0 ? void 0 : target.streamConfig)]; }); }); } exports.getStreamConfig = getStreamConfig; /** * Sanitizes app location string. * @param {string} appLoc - app location */ function sanitizeAppLoc(appLoc) { if (!appLoc || typeof appLoc !== 'string') return '/'; // Removes trailing '/' appLoc = appLoc.replace(/\/{1,}$/, ''); // Adds leading '/' if (!/^\//.test(appLoc)) appLoc = '/' + appLoc; // Replaces multiple leading '/' with a single '/' appLoc = appLoc.replace(/^\/{2,}/, '/'); return appLoc; } exports.sanitizeAppLoc = sanitizeAppLoc; function getProjectRoot() { return __awaiter(this, void 0, void 0, function () { var root, rootFound, i, currentLocation, maxLevels, isRoot, _a; return __generator(this, function (_b) { switch (_b.label) { case 0: root = ''; rootFound = false; i = 1; currentLocation = process.projectDir; maxLevels = currentLocation.split(path_1.default.sep).length; _b.label = 1; case 1: if (!(!rootFound && i <= maxLevels)) return [3 /*break*/, 5]; return [4 /*yield*/, (0, utils_1.folderExists)(path_1.default.join(currentLocation, 'sasjs'))]; case 2: _a = (_b.sent()); if (!_a) return [3 /*break*/, 4]; return [4 /*yield*/, (0, utils_1.fileExists)(path_1.default.join(currentLocation, 'sasjs', 'sasjsconfig.json'))]; case 3: _a = (_b.sent()); _b.label = 4; case 4: isRoot = _a; if (isRoot) { rootFound = true; root = currentLocation; return [3 /*break*/, 5]; } else { currentLocation = path_1.default.join(currentLocation, '..'); i++; } return [3 /*break*/, 1]; case 5: return [2 /*return*/, root]; } }); }); } exports.getProjectRoot = getProjectRoot; /** * Gets the auth config for the specified target. * @param {Target} target - the target to get an access token for. * @returns {AuthConfig} - an object containing an access token, refresh token, client ID and secret. */ function getAuthConfig(target) { var _a, _b, _c, _d; return __awaiter(this, void 0, void 0, function () { var access_token, refresh_token, client, secret, sasjs, tokens; return __generator(this, function (_e) { switch (_e.label) { case 0: access_token = ((_a = target === null || target === void 0 ? void 0 : target.authConfig) === null || _a === void 0 ? void 0 : _a.access_token) ? target.authConfig.access_token : ''; if (!(!access_token || access_token.trim() === 'null' || access_token.trim() === 'undefined')) return [3 /*break*/, 2]; return [4 /*yield*/, (0, exports.overrideEnvVariables)(target === null || target === void 0 ? void 0 : target.name)]; case 1: _e.sent(); access_token = process.env.ACCESS_TOKEN; _e.label = 2; case 2: refresh_token = ((_b = target === null || target === void 0 ? void 0 : target.authConfig) === null || _b === void 0 ? void 0 : _b.refresh_token) ? target.authConfig.refresh_token : process.env.REFRESH_TOKEN; refresh_token = refresh_token && (refresh_token.trim() === 'null' || refresh_token.trim() === 'undefined') ? undefined : refresh_token; client = ((_c = target === null || target === void 0 ? void 0 : target.authConfig) === null || _c === void 0 ? void 0 : _c.client) ? target.authConfig.client : process.env.CLIENT; client = client && (client.trim() === 'null' || client.trim() === 'undefined') ? undefined : client; if (!client) { throw new Error("Client ID was not found.\n Please make sure that the 'client' property is set in your local .env file or in the correct target authConfig in your global ~".concat(path_1.default.sep, ".sasjsrc file.")); } secret = ((_d = target === null || target === void 0 ? void 0 : target.authConfig) === null || _d === void 0 ? void 0 : _d.secret) ? target.authConfig.secret : process.env.SECRET; secret = secret && (secret.trim() === 'null' || secret.trim() === 'undefined') ? undefined : secret; if (!secret) { if (target.serverType === utils_1.ServerType.Sasjs) secret = ''; else throw new Error("Client secret was not found.\n Please make sure that the 'secret' property is set in your local .env file or in the correct target authConfig in your global ~".concat(path_1.default.sep, ".sasjsrc file.")); } if (!(0, auth_1.isAccessTokenExpiring)(access_token)) return [3 /*break*/, 8]; sasjs = getSASjs(target); tokens = void 0; if (!(0, auth_1.isRefreshTokenExpiring)(refresh_token)) return [3 /*break*/, 4]; return [4 /*yield*/, (0, auth_1.getNewAccessToken)(sasjs, client, secret, target)]; case 3: tokens = _e.sent(); return [3 /*break*/, 6]; case 4: return [4 /*yield*/, (0, auth_1.refreshTokens)(sasjs, client, secret, refresh_token)]; case 5: tokens = _e.sent(); _e.label = 6; case 6: access_token = (tokens === null || tokens === void 0 ? void 0 : tokens.access_token) || access_token; refresh_token = (tokens === null || tokens === void 0 ? void 0 : tokens.refresh_token) || refresh_token; return [4 /*yield*/, (0, exports.saveTokens)(target.name, client, secret, access_token, refresh_token || '')]; case 7: _e.sent(); _e.label = 8; case 8: return [2 /*return*/, { access_token: access_token, refresh_token: refresh_token, client: client, secret: secret }]; } }); }); } exports.getAuthConfig = getAuthConfig; var saveTokens = function (targetName, client, secret, access_token, refresh_token) { return __awaiter(void 0, void 0, void 0, function () { var isLocalTarget, VERBOSE, envFileContent, envFilePath, globalConfig, target, targetJson; var _a, _b, _c; return __generator(this, function (_d) { switch (_d.label) { case 0: return [4 /*yield*/, getLocalConfig() .then(function (localConfig) { var _a; return (_a = localConfig.targets) === null || _a === void 0 ? void 0 : _a.some(function (t) { return t.name === targetName; }); }) .catch(function () { var _a; (_a = process.logger) === null || _a === void 0 ? void 0 : _a.info('Local sasjsconfig.json file could not be found! Now finding target in global .sasjsrc file'); return false; })]; case 1: isLocalTarget = _d.sent(); if (!isLocalTarget) return [3 /*break*/, 3]; VERBOSE = process.env.VERBOSE; envFileContent = "CLIENT=".concat(client, "\nSECRET=").concat(secret, "\nACCESS_TOKEN=").concat(access_token, "\nREFRESH_TOKEN=").concat(refresh_token, "\n").concat(VERBOSE ? 'VERBOSE=' + VERBOSE + '\n' : ''); envFilePath = path_1.default.join(process.projectDir, ".env.".concat(targetName)); return [4 /*yield*/, (0, utils_1.createFile)(envFilePath, envFileContent)]; case 2: _d.sent(); (_a = process.logger) === null || _a === void 0 ? void 0 : _a.success("Environment file saved at ".concat(envFilePath)); return [3 /*break*/, 6]; case 3: return [4 /*yield*/, getGlobalRcFile()]; case 4: globalConfig = _d.sent(); target = (_b = globalConfig.targets) === null || _b === void 0 ? void 0 : _b.find(function (t) { return t.name === targetName; }); if (!target) { throw new Error(ERROR_MESSAGE(targetName).NOT_FOUND_TARGET_NAME); } targetJson = target.toJson(); targetJson.authConfig = { client: client, secret: secret, access_token: access_token, refresh_token: refresh_token }; return [4 /*yield*/, saveToGlobalConfig(new utils_1.Target(targetJson), globalConfig.defaultTarget === targetName)]; case 5: _d.sent(); (_c = process.logger) === null || _c === void 0 ? void 0 : _c.success("Target saved to global .sasjsrc file at ~/.sasjsrc."); _d.label = 6; case 6: return [2 /*return*/]; } }); }); }; exports.saveTokens = saveTokens; /** * Gets the auth config for the specified SAS9 target. * @param {Target} target - the target to get an access token for. * @returns {AuthConfigSas9} - an object containing an userName and password. */ function getAuthConfigSAS9(target) { var _a = target.authConfigSas9 ? { userName: target.authConfigSas9.userName, password: target.authConfigSas9.password } : { userName: process.env.SAS_USERNAME, password: process.env.SAS_PASSWORD }, userName = _a.userName, password = _a.password; if (!userName || !password) { var sas9CredentialsError = process.sasjsConstants.sas9CredentialsError; throw new Error(sas9CredentialsError); } return { userName: userName, password: password }; } exports.getAuthConfigSAS9 = getAuthConfigSAS9; /** * Gets an access token for the specified target. * If the target is from the global `.sasjsrc` file, * the auth info should be contained in it. * It should be in the form: * @example: { targets: [{ "name": "targetName", "authConfig": { "client": "client ID", "secret": "Client Secret", "access_token": "Token", "refresh_token": "Token" }}]} * If the access token is going to expire in the next hour, * it is refreshed using a refresh token if available. * If a refresh token is unavailable, we will use the client ID and secret * to obtain a new access token. Manual intervention is required in this case * to navigate to the URL shown and type in an authorization code. * @param {object} target - the target to get an access token for. * @param {string} checkIfExpiring - flag that indicates whether to do an expiry check. */ function getAccessToken(target, checkIfExpiring) { if (checkIfExpiring === void 0) { checkIfExpiring = true; } return __awaiter(this, void 0, void 0, function () { var accessToken, sasjs, client, secret, refreshToken, tokens; return __generator(this, function (_a) { switch (_a.label) { case 0: accessToken = target && target.authConfig && target.authConfig.access_token ? target.authConfig.access_token : ''; if (!(!accessToken || accessToken.trim() === 'null' || accessToken.trim() === 'undefined')) return [3 /*break*/, 2]; return [4 /*yield*/, (0, exports.overrideEnvVariables)(target === null || target === void 0 ? void 0 : target.name)]; case 1: _a.sent(); accessToken = process.env.ACCESS_TOKEN; _a.label = 2; case 2: if (!accessToken || accessT