@sasjs/cli
Version:
Command line interface for SASjs
740 lines (739 loc) • 36.7 kB
JavaScript
"use strict";
var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
return cooked;
};
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 __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isSasJsServerInServerMode = exports.getNodeModulePath = exports.isSASjsProject = exports.terminateProcess = exports.prefixAppLoc = exports.loadEnvVariables = exports.displaySasjsRunnerError = exports.getAdapterInstance = exports.checkNodeVersion = exports.millisecondsToDdHhMmSs = exports.arrToObj = exports.convertToSASStatements = exports.parseLogLines = exports.executePowerShellScript = exports.executeShellScript = exports.getUniqServicesObj = exports.setupDoxygen = exports.setupGitIgnore = exports.setupNpmProject = exports.createTemplateApp = exports.createMinimalApp = exports.createAngularApp = exports.createReactApp = exports.diff = exports.inExistingProject = void 0;
var shelljs_1 = __importDefault(require("shelljs"));
var node_powershell_1 = require("node-powershell");
var path_1 = __importDefault(require("path"));
var ora_1 = __importDefault(require("ora"));
var axios_1 = __importDefault(require("axios"));
var utils_1 = require("@sasjs/utils");
var displayResult_1 = require("./displayResult");
var dotenv_1 = __importDefault(require("dotenv"));
var adm_zip_1 = __importDefault(require("adm-zip"));
var config_1 = require("./config");
function inExistingProject(folderPath) {
return __awaiter(this, void 0, void 0, function () {
var packageJsonExists;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, (0, utils_1.fileExists)(path_1.default.join(process.projectDir, folderPath, 'package.json'))];
case 1:
packageJsonExists = _a.sent();
return [2 /*return*/, packageJsonExists];
}
});
});
}
exports.inExistingProject = inExistingProject;
function diff(a, b) {
var notInA = a.filter(function (item) {
return typeof item === 'object'
? !JSON.stringify(b).includes(JSON.stringify(item))
: !b.includes(item);
});
var notInB = b.filter(function (item) {
return typeof item === 'object'
? !JSON.stringify(a).includes(JSON.stringify(item))
: !a.includes(item);
});
return __spreadArray(__spreadArray([], __read(notInA), false), __read(notInB), false);
}
exports.diff = diff;
function createReactApp(folderPath) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
createApp(folderPath, 'https://github.com/sasjs/react-seed-app', 'https://github.com/sasjs/docs', function (err) {
return reject(new Error(err));
});
return [2 /*return*/, resolve()];
});
}); })];
});
});
}
exports.createReactApp = createReactApp;
function createAngularApp(folderPath) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
createApp(folderPath, 'https://github.com/sasjs/angular-seed-app', 'https://github.com/sasjs/docs', function (err) {
return reject(new Error(err));
});
return [2 /*return*/, resolve()];
});
}); })];
});
});
}
exports.createAngularApp = createAngularApp;
function createMinimalApp(folderPath) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
createApp(folderPath, 'https://github.com/sasjs/minimal-seed-app', 'https://github.com/sasjs/docs', function (err) {
return reject(new Error(err));
});
return [2 /*return*/, resolve()];
});
}); })];
});
});
}
exports.createMinimalApp = createMinimalApp;
function createTemplateApp(folderPath, template) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
var _a, stdout, stderr, code;
return __generator(this, function (_b) {
_a = downloadFile("https://username:password@github.com/sasjs/template_".concat(template), 'response.txt'), stdout = _a.stdout, stderr = _a.stderr, code = _a.code;
if (stderr.includes('404: Not Found') || code) {
return [2 /*return*/, reject(new Error("Template \"".concat(template, "\" is not a SASjs template")))];
}
createApp(folderPath, "https://github.com/sasjs/template_".concat(template), 'https://github.com/sasjs/docs', function (err) {
return reject(new Error(err));
});
return [2 /*return*/, resolve()];
});
}); })];
});
});
}
exports.createTemplateApp = createTemplateApp;
/**
* This function will first download / unzip the target app from repoUrl, then download / unzip the sasjs/docs repo into a subdirectory named 'docs'.
* Finally, if installDependencies is true, the npm install command will be executed.
* @param folderPath full path of the directory where desired seed app will be created
* @param repoUrl sasjs/{seed-app} repo url
* @param docsUrl sasjs/docs repo url
* @params installDependencies whether or not to do `npm install`
*/
function createApp(folderPath, repoUrl, docsUrl, errorCallback, installDependencies) {
if (installDependencies === void 0) { installDependencies = true; }
//In past we used GIT to clone the repos. But many users potentially won't have GIT installed.
//So we will use shell tools to set up the apps.
var zipName = 'main.zip';
var zipPath = "/archive/refs/heads/";
var fullZipPath = "".concat(zipPath).concat(zipName);
var spinner = (0, ora_1.default)("Creating SASjs project in ".concat(folderPath, "."));
spinner.start();
//Get repo zip, assuming main branch is called `main`
var _a = downloadFile("".concat(repoUrl).concat(fullZipPath), zipName), stdout = _a.stdout, stderr = _a.stderr, code = _a.code;
// If doesn't exist, we try again, but with master.zip for the zip name.
// Since that's the name generated from branch name.
if (stderr.includes('404: Not Found') || code) {
zipName = 'master.zip';
var _b = downloadFile("".concat(repoUrl).concat(zipPath).concat(zipName), zipName), stdout_1 = _b.stdout, stderr_1 = _b.stderr, code_1 = _b.code;
if (stderr_1.includes('404: Not Found') || code_1) {
errorCallback("".concat(repoUrl).concat(zipPath, " is not SASjs repository!"));
return;
}
}
var zipWithoutExtension = zipName.replace('.zip', '');
var zip = new adm_zip_1.default(zipName);
zip.extractAllTo("./", true);
shelljs_1.default.cp('-r', "./*".concat(zipWithoutExtension, "/."), folderPath);
shelljs_1.default.rm('-rf', ["./*".concat(zipWithoutExtension)]);
shelljs_1.default.rm('-rf', ["./".concat(zipName)]);
loadDocsSubmodule(docsUrl, folderPath, fullZipPath);
shelljs_1.default.rm('-f', [path_1.default.join(folderPath, '.gitmodules')]);
spinner.stop();
if (installDependencies) {
spinner.text = 'Installing dependencies...';
spinner.start();
shelljs_1.default.exec("cd \"".concat(folderPath, "\" && npm install"), {
silent: true
});
spinner.stop();
}
}
/**
* It will download and unzip `sasjs/docs` into newly created folder into `docs` subfolder
* @param docsUrl sasjs/docs repo url
* @param folderPath full path to the newly created folder that contains the seed app
* @param zipPath fixed path of where github puts zip for repo download
*/
var loadDocsSubmodule = function (docsUrl, folderPath, zipPath) { return __awaiter(void 0, void 0, void 0, function () {
var docsFolderPath, zip;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
docsFolderPath = "".concat(folderPath, "/public/docs") // We first look if docs submodule is inside `public` folder. (react-seed-app for example)
;
return [4 /*yield*/, (0, utils_1.fileExists)(docsFolderPath)];
case 1:
if (!(_a.sent()))
docsFolderPath = "".concat(folderPath, "/docs"); // If not, we load submodule in root
downloadFile("".concat(docsUrl).concat(zipPath), 'main.zip');
zip = new adm_zip_1.default('main.zip');
zip.extractAllTo('./', true);
shelljs_1.default.cp('-r', "./*-main/.", docsFolderPath);
shelljs_1.default.rm('-rf', ["./*-main"]);
shelljs_1.default.rm('-rf', ["./main.zip"]);
return [2 /*return*/];
}
});
}); };
function downloadFile(url, filename) {
if ((0, utils_1.isLinux)()) {
return shelljs_1.default.exec("wget ".concat(url), { silent: true });
}
else if ((0, utils_1.isWindows)()) {
// First We set TLS12 & then we invoke request to download file.
return shelljs_1.default.exec("powershell.exe \"[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12; Invoke-WebRequest ".concat(url, " ").concat(filename ? '-O ' + filename : '', "\""), { silent: true });
}
else {
return shelljs_1.default.exec("curl ".concat(url, " -LO -f"), { silent: true });
}
}
function setupNpmProject(folderName) {
return __awaiter(this, void 0, void 0, function () {
var folderPath;
var _this = this;
return __generator(this, function (_a) {
folderPath = path_1.default.join(process.projectDir, folderName);
return [2 /*return*/, new Promise(function (resolve, _) { return __awaiter(_this, void 0, void 0, function () {
var isExistingProject;
var _a, _b, _c;
return __generator(this, function (_d) {
switch (_d.label) {
case 0: return [4 /*yield*/, inExistingProject(folderName)];
case 1:
isExistingProject = _d.sent();
if (!isExistingProject) {
(_a = process.logger) === null || _a === void 0 ? void 0 : _a.info("Initialising NPM project in ".concat(folderPath));
shelljs_1.default.exec("cd \"".concat(folderPath, "\" && npm init --yes"), {
silent: true
});
}
else {
(_b = process.logger) === null || _b === void 0 ? void 0 : _b.success('Existing NPM project detected.');
}
(_c = process.logger) === null || _c === void 0 ? void 0 : _c.info('Installing @sasjs/core');
shelljs_1.default.exec("cd \"".concat(folderPath, "\" && npm i @sasjs/core --save"), {
silent: true
});
return [2 /*return*/, resolve()];
}
});
}); })];
});
});
}
exports.setupNpmProject = setupNpmProject;
function setupGitIgnore(folderName) {
var _a, _b;
return __awaiter(this, void 0, void 0, function () {
var gitIgnoreFilePath, gitIgnoreExists, gitIgnoreContent, newgitIgnoreContent, regExpSasjsBuild, regExpSasjsResults, regExpNodeModules, regExpEnv;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
gitIgnoreFilePath = path_1.default.join(process.projectDir, folderName, '.gitignore');
return [4 /*yield*/, (0, utils_1.fileExists)(gitIgnoreFilePath)];
case 1:
gitIgnoreExists = _c.sent();
if (!gitIgnoreExists) return [3 /*break*/, 5];
return [4 /*yield*/, (0, utils_1.readFile)(gitIgnoreFilePath)];
case 2:
gitIgnoreContent = _c.sent();
newgitIgnoreContent = gitIgnoreContent;
regExpSasjsBuild = new RegExp("^sasjsbuild", 'gm');
regExpSasjsResults = new RegExp("^sasjsresults", 'gm');
regExpNodeModules = new RegExp("^node_modules", 'gm');
regExpEnv = new RegExp("^.env*", 'gm');
if (newgitIgnoreContent) {
if (!regExpSasjsBuild.test(newgitIgnoreContent)) {
newgitIgnoreContent += '\nsasjsbuild';
}
if (!regExpSasjsResults.test(newgitIgnoreContent)) {
newgitIgnoreContent += '\nsasjsresults';
}
if (!regExpNodeModules.test(newgitIgnoreContent)) {
newgitIgnoreContent += '\nnode_modules';
}
if (!regExpEnv.test(newgitIgnoreContent)) {
newgitIgnoreContent += '\n.env*';
}
}
else {
newgitIgnoreContent = 'node_modules\nsasjsbuild\nsasjsresults\n.env*\n';
}
if (!(gitIgnoreContent !== newgitIgnoreContent)) return [3 /*break*/, 4];
return [4 /*yield*/, (0, utils_1.createFile)(gitIgnoreFilePath, newgitIgnoreContent)];
case 3:
_c.sent();
(_a = process.logger) === null || _a === void 0 ? void 0 : _a.success('Existing .gitignore has been updated.');
_c.label = 4;
case 4: return [3 /*break*/, 7];
case 5: return [4 /*yield*/, (0, utils_1.createFile)(gitIgnoreFilePath, 'node_modules\nsasjsbuild\nsasjsresults\n.env*\n')];
case 6:
_c.sent();
(_b = process.logger) === null || _b === void 0 ? void 0 : _b.success('.gitignore file has been created.');
_c.label = 7;
case 7: return [2 /*return*/];
}
});
});
}
exports.setupGitIgnore = setupGitIgnore;
function setupDoxygen(folderPath) {
return __awaiter(this, void 0, void 0, function () {
var doxyFilesPath, doxyFolderPathSource, doxyFolderPath;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
doxyFilesPath = '../doxy';
doxyFolderPathSource = path_1.default.join(__dirname, doxyFilesPath);
doxyFolderPath = path_1.default.join(process.projectDir, folderPath, 'sasjs', 'doxy');
return [4 /*yield*/, (0, utils_1.copy)(doxyFolderPathSource, doxyFolderPath)];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
}
exports.setupDoxygen = setupDoxygen;
function getUniqServicesObj(services) {
var returnObj = {};
if (!services)
return returnObj;
services.forEach(function (service) {
var serviceName = service.split('/').pop();
if (returnObj[serviceName])
return;
returnObj[serviceName] = service;
});
return returnObj;
}
exports.getUniqServicesObj = getUniqServicesObj;
function executeShellScript(filePath, logFilePath) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
return [2 /*return*/, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
var shellCommand, result;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
shellCommand = (0, utils_1.isWindows)() ? "".concat(filePath) : "bash ".concat(filePath);
result = shelljs_1.default.exec(shellCommand, { silent: true });
if (!result.code) return [3 /*break*/, 1];
(_a = process.logger) === null || _a === void 0 ? void 0 : _a.error("Error: ".concat(result.stderr));
reject(result.code);
throw new Error('Error executing shell script: Code ' + result.code);
case 1:
if (!logFilePath) return [3 /*break*/, 3];
return [4 /*yield*/, (0, utils_1.createFile)(logFilePath, result.stdout)];
case 2:
_b.sent();
_b.label = 3;
case 3:
resolve(result.stdout);
_b.label = 4;
case 4: return [2 /*return*/];
}
});
}); })];
});
});
}
exports.executeShellScript = executeShellScript;
function executePowerShellScript(filePath, logFilePath) {
return __awaiter(this, void 0, void 0, function () {
var ps, scriptCommand;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
ps = new node_powershell_1.PowerShell({
executableOptions: {
'-ExecutionPolicy': 'Bypass',
'-NoProfile': true
}
});
scriptCommand = node_powershell_1.PowerShell.command(templateObject_1 || (templateObject_1 = __makeTemplateObject([". ", ""], [". ", ""])), filePath);
return [4 /*yield*/, ps
.invoke(scriptCommand)
.then(function (result) { return __awaiter(_this, void 0, void 0, function () {
var content;
var _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
if (result.hadErrors) {
(_a = process.logger) === null || _a === void 0 ? void 0 : _a.error("Error: ".concat(result.stderr));
throw new Error('Error executing shell script:' + result.stderr);
}
if (!logFilePath) return [3 /*break*/, 2];
content = (_b = result.stdout) === null || _b === void 0 ? void 0 : _b.toString().replace(/\u001b\[\?1h\u001b\[\?1l/g, '');
return [4 /*yield*/, (0, utils_1.createFile)(logFilePath, content !== null && content !== void 0 ? content : '')];
case 1:
_c.sent();
_c.label = 2;
case 2: return [2 /*return*/];
}
});
}); })
.catch(function (error) {
var _a;
(_a = process.logger) === null || _a === void 0 ? void 0 : _a.error("Error: ".concat(error));
throw new Error('Error executing shell script: ' + error);
})
.finally(function () { return __awaiter(_this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, ps.dispose()];
case 1:
_a.sent();
return [2 /*return*/];
}
});
}); })];
case 1:
_a.sent();
return [2 /*return*/];
}
});
});
}
exports.executePowerShellScript = executePowerShellScript;
/**
* Extracts plain text job log from fetched json log
* @param {object} logJson
*/
function parseLogLines(logJson) {
var e_1, _a;
var logLines = '';
try {
for (var _b = __values(logJson.items), _c = _b.next(); !_c.done; _c = _b.next()) {
var item = _c.value;
logLines += "".concat(item.line, "\n");
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
return logLines;
}
exports.parseLogLines = parseLogLines;
/**
* Converts MacroVars JSON from command source param to sas statements
* The JSON must have the following structure:
* {"macroVars": {"var1": "val1", "var2": "val2"}}
*
* @param {object} json
*/
function convertToSASStatements(json) {
var e_2, _a;
var sasStatements = '';
try {
for (var _b = __values(Object.keys(json.macroVars)), _c = _b.next(); !_c.done; _c = _b.next()) {
var macroVar = _c.value;
var key = macroVar;
var value = json.macroVars[macroVar];
var line = "%let ".concat(key, "=").concat(value, ";\n");
sasStatements += line;
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_2) throw e_2.error; }
}
return sasStatements;
}
exports.convertToSASStatements = convertToSASStatements;
var arrToObj = function (arr) {
return arr.reduce(function (o, key) {
var _a;
return (__assign(__assign({}, o), (_a = {}, _a[key] = key, _a)));
}, {});
};
exports.arrToObj = arrToObj;
var millisecondsToDdHhMmSs = function (milliseconds) {
if (typeof milliseconds !== 'number')
throw 'Not supported attribute type.';
milliseconds = Math.abs(milliseconds);
var days = Math.floor(milliseconds / 1000 / 60 / 60 / 24);
var hours = Math.floor(milliseconds / 1000 / 60 / 60) % 24;
var minutes = Math.floor(milliseconds / 1000 / 60) % 60;
var seconds = Math.floor(milliseconds / 1000) % 60;
return "".concat(days, " day(s); ").concat(hours, " hour(s); ").concat(minutes, " minute(s); ").concat(seconds, " second(s)");
};
exports.millisecondsToDdHhMmSs = millisecondsToDdHhMmSs;
function checkNodeVersion() {
var _a;
var nodeVersion = process.versions.node;
var majorVersion = parseInt(nodeVersion.substr(0, 2));
if (majorVersion < 12) {
(_a = process.logger) === null || _a === void 0 ? void 0 : _a.error('SASjs CLI requires at least NodeJS version 12. Please upgrade NodeJS and try again.');
process.exit(1);
}
}
exports.checkNodeVersion = checkNodeVersion;
function getAdapterInstance(target) {
if (!target) {
throw new Error('Unable to create SASjs adapter instance: Invalid target.');
}
if (!target.serverUrl) {
throw new Error("Unable to create SASjs adapter instance: Target ".concat(target.name, " is missing a `serverUrl`."));
}
if (!target.serverType) {
throw new Error("Unable to create SASjs adapter instance: Target ".concat(target.name, " is missing a `serverType`."));
}
var sasjs = (0, config_1.getSASjs)(target);
return sasjs;
}
exports.getAdapterInstance = getAdapterInstance;
function displaySasjsRunnerError(username) {
var _a;
var sasjsRunnerCode = "\nfilename mc url \"https://raw.githubusercontent.com/sasjs/core/main/all.sas\";\n%inc mc;\nfilename ft15f001 temp;\nparmcards4;\n%macro sasjs_runner();\n%if %symexist(_webin_fileref) %then %do;\n%inc &_webin_fileref;\n%end;\n%mend sasjs_runner;\n%sasjs_runner()\n;;;;\n%mm_createwebservice(path=/User Folders/&_metauser/My Folder/sasjs,name=runner)\n";
var message = "The SASjs runner was not found in your user folder at /User Folders/&_metauser/My Folder/sasjs/runner.";
(0, displayResult_1.displayError)(message, 'An error occurred while executing the request.');
(_a = process.logger) === null || _a === void 0 ? void 0 : _a.info("Please deploy the SASjs runner by running the code below and try again:\n".concat(sasjsRunnerCode));
}
exports.displaySasjsRunnerError = displaySasjsRunnerError;
var loadEnvVariables = function (fileName) { return __awaiter(void 0, void 0, void 0, function () {
var envFileExistsInCurrentPath, envFileExistsInParentPath, envFilePath;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, (0, utils_1.fileExists)(path_1.default.join(process.cwd(), fileName))];
case 1:
envFileExistsInCurrentPath = _a.sent();
return [4 /*yield*/, (0, utils_1.fileExists)(path_1.default.join(process.cwd(), '..', fileName))];
case 2:
envFileExistsInParentPath = _a.sent();
envFilePath = envFileExistsInCurrentPath
? path_1.default.join(process.cwd(), fileName)
: envFileExistsInParentPath
? path_1.default.join(process.cwd(), '..', fileName)
: null;
if (envFilePath) {
dotenv_1.default.config({ path: envFilePath });
}
return [2 /*return*/];
}
});
}); };
exports.loadEnvVariables = loadEnvVariables;
function prefixAppLoc(appLoc, path) {
if (appLoc === void 0) { appLoc = ''; }
if (path === void 0) { path = ''; }
if (!path)
return null;
if (!/^\//.test(appLoc))
appLoc = '/' + appLoc;
if (Array.isArray(path))
path = path.join(' ');
return path
.split(' ')
.map(function (p) { return (/^\//.test(p) ? p : "".concat(appLoc, "/").concat(p)); })
.join(' ');
}
exports.prefixAppLoc = prefixAppLoc;
var terminateProcess = function (status) {
var _a;
(_a = process.logger) === null || _a === void 0 ? void 0 : _a.info("Process will be terminated with the status code ".concat(status, "."));
process.exit(status);
};
exports.terminateProcess = terminateProcess;
/**
* This function checks whether the current directory, or any of the parent
* directories, are part of a SASjs project. This is done by testing for
* the existence of a ./sasjs/sasjsconfig.json file.
*
* @returns boolean
*/
var isSASjsProject = function () { return __awaiter(void 0, void 0, void 0, function () {
var i, currentLocation, maxLevels, _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
i = 1;
currentLocation = process.projectDir;
maxLevels = currentLocation.split(path_1.default.sep).length;
_b.label = 1;
case 1:
if (!(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:
if (_a) {
return [2 /*return*/, true];
}
else {
currentLocation = path_1.default.join(currentLocation, '..');
i++;
}
return [3 /*break*/, 1];
case 5: return [2 /*return*/, false];
}
});
}); };
exports.isSASjsProject = isSASjsProject;
var getNodeModulePath = function (module) { return __awaiter(void 0, void 0, void 0, function () {
var projectPath, cliDepsPath, cliLocalPath, cliGlobalPath;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
projectPath = path_1.default.join(process.cwd(), 'node_modules', module);
return [4 /*yield*/, (0, utils_1.folderExists)(projectPath)];
case 1:
if (_a.sent())
return [2 /*return*/, projectPath
// Check if module is present in @sasjs/cli located in project's dependencies
];
cliDepsPath = path_1.default.join('@sasjs', 'cli', 'node_modules');
cliLocalPath = path_1.default.join(process.cwd(), 'node_modules', cliDepsPath, module);
return [4 /*yield*/, (0, utils_1.folderExists)(cliLocalPath)];
case 2:
if (_a.sent())
return [2 /*return*/, cliLocalPath
// Check if module is present in global @sasjs/cli
];
cliGlobalPath = path_1.default.join(shelljs_1.default.exec("npm root -g", { silent: true }).stdout.replace(/\n/, ''), cliDepsPath, module);
return [4 /*yield*/, (0, utils_1.folderExists)(cliGlobalPath)];
case 3:
if (_a.sent())
return [2 /*return*/, cliGlobalPath
// Return default value
];
// Return default value
return [2 /*return*/, ''];
}
});
}); };
exports.getNodeModulePath = getNodeModulePath;
var isSasJsServerInServerMode = function (target) { return __awaiter(void 0, void 0, void 0, function () {
var res, error_1, message;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4 /*yield*/, axios_1.default.get("".concat(target.serverUrl, "/SASjsApi/info"))];
case 1:
res = _a.sent();
return [2 /*return*/, res.data.mode === 'server'];
case 2:
error_1 = _a.sent();
message = "An error occurred while fetching server info from ".concat(target.serverUrl, "/SASjsApi/info");
(0, displayResult_1.displayError)(error_1, message);
throw new Error(message);
case 3: return [2 /*return*/];
}
});
}); };
exports.isSasJsServerInServerMode = isSasJsServerInServerMode;
var templateObject_1;