All files / lib helper.js

98.47% Statements 129/131
84% Branches 42/50
95.23% Functions 20/21
98.46% Lines 128/130

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 3337x 7x 7x 7x 7x 7x 7x   7x           7x 9x 9x   1x         1x                 7x 13x 13x     13x         13x       13x 13x             7x 4x     4x           7x 42x 42x               7x 36x 36x 2x     2x   34x     34x                 7x         4x 4x   12x   2x 2x 2x 1x       3x                         7x   38x     38x   106x   83x       38x           7x 13x                       7x 5x 5x 5x 5x 2x 2x         181x       2x 2x   1x 1x       4x     7x 2x 2x 2x 2x 1x 2x 2x 2x 2x     2x     7x 1x 1x 2x 2x           1x               1x     7x 46x 26x   20x                 20x 2x 2x 2x 1x 1x 1x     1x           19x 19x 19x       5x 3x 1x     16x         18x     7x 46x 26x   20x                 20x 2x 2x 2x 1x   1x 1x     1x             19x             7x 6x 6x 6x 5x     5x 5x       5x     5x 5x 5x   1x     1x           6x    
const path = require('path');
const https = require('https');
const chalk = require('chalk');
const fs = require('fs');
const arg = require('arg');
const semver = require('semver');
const archive = require('archiver');
 
const CONSTANTS = require('./constant');
 
/*
  wrapper for importing which might have a chance of error
  catch error incase of modulepath not found.
*/
exports.getRequiredFunction = (modulePath) => {
  try {
    return require(modulePath);
  } catch (err) {
    console.log(
      chalk.red(
        `getRequiredFunction(): The file: ${modulePath} could not be loaded`
      )
    );
    return false;
  }
};
 
/*
  returns the build foldername which should be libname/libversion
  the same folder structure is supported by component publish in v2
  uses package.json to get the packagename and version and appends
*/
exports.getBuildFolderName = (libraryName, libraryVersion) => {
  let packageDetails = {};
  Iif(libraryName && libraryVersion){
    packageDetails = {"name" : libraryName, "version" : libraryVersion };
  } else{
    packageDetails = this.getRequiredFunction(
      path.join(CONSTANTS.CURRENT_WORKING_DIR, 'package.json')
    );
 
  }
  const buildFolderFullPath = path.join(
    packageDetails.name,
    packageDetails.version
  );
  const buildFolderName = packageDetails.name;
  return {
    buildFolderFullPath,
    buildFolderName,
    packageVersion: packageDetails.version,
  };
};
 
exports.getAppstaticEnd = (appStaticSVCUrl) => {
  const appStaticURL = this.getAppStaticServerUrl(appStaticSVCUrl)
    ? this.getAppStaticServerUrl(appStaticSVCUrl)
    : '{APP_URL}';
  return appStaticURL && appStaticURL.endsWith('/')
    ? appStaticURL + CONSTANTS.ENDPOINTURL
    : appStaticURL + '/' + CONSTANTS.ENDPOINTURL;
};
 
/**/
exports.getHttpsAgent = () => {
  const agentOptions = { rejectUnauthorized: false };
  return new https.Agent(agentOptions);
};
 
/**
 *
 * @param {none}
 * @returns headers
 */
exports.getHeaders = (tokenParams) => {
  const bs2Token = this.getB2SToken(tokenParams);
  if (bs2Token === '') {
    console.log(
      chalk.red('B2STOKEN, Auth token is empty.. please fix and try again')
    );
    return false;
  }
  const token = bs2Token.startsWith('Bearer ')
    ? bs2Token.substring(7)
    : bs2Token;
  return {
    Authorization: `Bearer ${token}`,
    'Content-Type': 'application/json',
  };
};
 
/*
  Before zipping remove any previous versions of library i.e package.version should be the only folder
*/
exports.cleanUpBuildFolder = (
  parentFolder,
  buildFolderName,
  packageVersion
) => {
  try {
    const removedVersions = fs
      .readdirSync(path.join(parentFolder, buildFolderName))
      .filter((version) => version === packageVersion)
      .map((version) => {
        const versionPath = path.join(parentFolder, buildFolderName, version);
        Eif (fs.statSync(versionPath).isDirectory()) {
          fs.rmSync(versionPath, { recursive: true });
          return buildFolderName + '/' + version;
        }
      })
      .filter(Boolean); // Filter out undefined values
    console.log(
      chalk.yellow(
        `Removed following output version : ${removedVersions.join(', ')}`
      )
    );
  } catch (ex) {
    // console.log(ex);
  }
};
 
/*
  String Utils
*/
exports.formatEndPointURL = (...params) => {
  // Remove any trailing slashes from the first parameter
  let result = params[0] && params[0].replace(/\/+$/, '');
 
  // Loop through the remaining parameters starting from the second one
  for (let i = 1; i < params.length; i++) {
    // Check if the parameter is empty before appending
    if (params[i]) {
      // Append a slash and the current parameter
      result += '/' + params[i].replace(/^\/+/, ''); // Remove any leading slashes
    }
  }
 
  return result;
};
 
/*
  Questions utils for inquirer prompts
*/
exports.getQuestionsListDynamically = (name, message, list) => {
  return [
    {
      name,
      message,
      type: 'list',
      choices: list,
    },
  ];
};
/*
  Return Org ID for source map
*/
exports.getPayloadFromTkn = (tkn, keyToPayload) => {
  let valueToPayload = '';
  Eif (tkn && keyToPayload) {
    const base64Url = tkn.split('.')[1];
    if (base64Url) {
      const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
      const jsonPayload = decodeURIComponent(
        Buffer.from(base64, 'base64')
          .toString()
          .split('')
          .map(function (c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
          })
          .join('')
      );
      try {
        valueToPayload = JSON.parse(jsonPayload)[keyToPayload];
      } catch (ex) {
        console.error(`tkn parse failed : ${jsonPayload}`);
        return '';
      }
    }
  }
  return valueToPayload;
};
 
exports.getVersionFromListOutput = (listOutput, packageNamePattern) => {
  const regex = new RegExp(`${packageNamePattern}[^\\s]+@[^\\s]+`, 'g');
  const matches = listOutput.match(regex);
  const versions = {};
  if (matches) {
    matches.forEach((match) => {
      const lastIndex = match.lastIndexOf('@');
      const packageName = match.substring(0, lastIndex);
      const version = match.substring(lastIndex + 1);
      versions[packageName] = version;
    });
  }
  return versions;
};
 
exports.compareObjects = (smallObj, bigObj) => {
  const mismatches = {};
  for (const key in smallObj) {
    Eif (bigObj.hasOwnProperty(key)) {
      if (
        !(
          semver.major(smallObj[key]) === semver.major(bigObj[key]) &&
          semver.minor(smallObj[key]) === semver.minor(bigObj[key])
        )
      ) {
        mismatches[key] = {
          'Your library Package.json version': smallObj[key],
          'Package version used in targeted Constellation runtime portal':
            bigObj[key],
        };
      }
    }
  }
  return mismatches;
};
 
exports.getB2SToken = (tokenParams) => {
  if(tokenParams){
    return tokenParams;
  }
  const args = arg(
    {
      '--token-path': String,
    },
    {
      argv: process.argv.slice(2),
    }
  );
 
  if (args['--token-path']) {
    try {
      const tokenPath = path.join(path.resolve(), args['--token-path']);
      const OauthData = fs.readFileSync(tokenPath, 'utf8');
      Eif (OauthData) {
        const { C11NB2S: C11NB2S } = JSON.parse(OauthData);
        return C11NB2S;
      }
    } catch (ex) {
      console.log(
        'Fallback to predefined token path; unable to read from specified --token-path argument : ',
        args['--token-path']
      );
    }
  }
  Eif (CONSTANTS.TOKEN_PATH) {
    try {
      const OauthData = fs.readFileSync(
        path.join(CONSTANTS.CURRENT_WORKING_DIR, CONSTANTS.TOKEN_PATH),
        'utf8'
      );
      if (OauthData) {
        const { C11NB2S: C11NB2S } = JSON.parse(OauthData);
        return C11NB2S;
      }
    } catch (ex) {
      console.log(
        'Fallback to constant value B2STOKEN; unable to read token from default path.'
      );
    }
  }
  return CONSTANTS.B2STOKEN;
};
 
exports.getAppStaticServerUrl = (appStaticSVCUrl) => {
  if(appStaticSVCUrl){
    return appStaticSVCUrl;
  }
  const args = arg(
    {
      '--token-path': String,
    },
    {
      argv: process.argv.slice(2),
    }
  );
 
  if (args['--token-path']) {
    try {
      const tokenPath = path.join(path.resolve(), args['--token-path']);
      const OauthData = fs.readFileSync(tokenPath, 'utf8');
      Eif (OauthData) {
        const { appStaticContentServer: appStaticContentServer } =
          JSON.parse(OauthData);
        return appStaticContentServer;
      }
    } catch (ex) {
      console.log(
        'Fallback to constant value APPSTATICURL; unable to read from specified --token-path argument : ',
        args['--token-path']
      );
    }
  }
 
  return CONSTANTS.APPSTATICURL;
};
 
/*
  zip content after building from build-library
  @param: folderName
*/
exports.zipContent = async (folderName, srcToZip) => {
  const promise = new Promise((resolve, reject) => {
    try {
      const op = fs.createWriteStream(`${folderName}.zip`);
      const arch = archive('zip', {
        zlib: { level: 9 },
      });
      op.on('close', () => {
        resolve({
          status: 'success',
        });
      });
      arch.on('error', (err) => {
        throw err;
      });
      arch.pipe(op);
      arch.directory(srcToZip);
      arch.finalize();
    } catch (error) {
      console.log(
        chalk.red(`helper(): error while zipping content:: ${error}`)
      );
      reject({
        status: 'failure',
        error,
      });
    }
  });
  return promise;
};