UNPKG

@pega/custom-dx-components

Version:

Utility for building custom UI components

172 lines (147 loc) 5.05 kB
import fs from 'fs'; import path from 'path'; import fetch from 'node-fetch'; import archiver from 'archiver'; import chalk from 'chalk'; import { constructCompleteUrl, getComponentDirectoryPath, getComponents, getPegaServerConfig, getHttpsAgent, getLibraryBased } from '../../util.js'; import { PUBLISH_COMPONENT_SERVICE_REST_ENDPOINT, TOKEN_PATH } from '../../constants.js'; export const getPublishComponentQuestions = async componentKey => { const isLibraryBased = getLibraryBased(); // validate and validateAll will be called when libraryBased, but using same code // so need different label const buildLabel = isLibraryBased ? "validate" : "build"; const components = await getComponents(); if (components.length === 0) { console.log(chalk.redBright(`No components to ${buildLabel}`)); process.exit(); } const defaultPegaConfig = await getPegaServerConfig(); return [ { name: 'componentKey', type: 'rawlist', message: `Select component to ${buildLabel}`, choices: components, default: componentKey, when: () => !componentKey }, { name: 'sourceMap', message: 'Generate source map ?', default: defaultPegaConfig.sourceMap, // eslint-disable-next-line sonarjs/no-redundant-boolean when: () => false && !process.env.SOURCE_MAP }, { name: 'devBuild', type: 'confirm', message: 'Generate development build ?', default: defaultPegaConfig.devBuild, when: () => !isLibraryBased } ]; }; export const zipComponent = async componentKey => { const srcDirectory = await getComponentDirectoryPath(componentKey); const buildDirectory = await path.join(path.resolve(), 'dist/components', componentKey); const configJson = `${srcDirectory}/config.json`; const localizationJson = `${srcDirectory}/localizations.json`; const archive = archiver('zip', { zlib: { level: 9 } }); const zipChunks = []; archive.on('data', chunk => zipChunks.push(chunk)); // Add src directory archive.directory(srcDirectory, 'src'); // Add config.json file if (fs.existsSync(configJson)) { archive.file(configJson, { name: path.basename(configJson) }); } // Add localizations.json file if it exists if (fs.existsSync(localizationJson)) { archive.file(localizationJson, { name: path.basename(localizationJson) }); } // Add build directory archive.directory(buildDirectory, false); await archive.finalize(); const zipBuffer = Buffer.concat(zipChunks); console.log(chalk.green(`component zipped with size: ${Math.ceil(zipBuffer.length / 1024)} KB`)); const zipContent = zipBuffer.toString('base64'); const configContent = Buffer.from(fs.readFileSync(configJson)).toString(); if (fs.existsSync('dist/components')) { fs.rm('dist/components', { recursive: true }, err => { if (err) { throw err; } }); } if (fs.existsSync('lib')) { fs.rm('lib', { recursive: true }, err => { if (err) { throw err; } }); } return { zipContent, configContent }; }; export const publishComponentToServer = async data => { const { configContent, zipContent, rulesetName, rulesetVersion } = data; const apiBody = { configContent, zipContent, componentKey: JSON.parse(configContent).componentKey, publishFor: 'constellation', rulesetName, rulesetVersion, category: '' }; const defaultPegaConfig = await getPegaServerConfig(); const url = constructCompleteUrl( defaultPegaConfig.server, PUBLISH_COMPONENT_SERVICE_REST_ENDPOINT ); try { const OauthData = fs.readFileSync(TOKEN_PATH, 'utf8'); if (OauthData) { const { access_token: accessToken, token_type: tokenType } = JSON.parse(OauthData); let status = 500; fetch(url, { method: 'POST', agent: getHttpsAgent(defaultPegaConfig), headers: { Authorization: `${tokenType} ${accessToken}` }, body: JSON.stringify(apiBody) }) .then(response => { status = response.status; return response.text(); }) .then(resp => { const respData = JSON.parse(resp); if (status === 401) { throw new Error( 'Error occurred in authentication. Please regenerate using authenticate' ); // console.log(accessTokenUri, refreshToken); /* TODO - Handle refresh_token */ } else if (status === 200) { console.log(chalk.bold.green(`Success : ${respData.message}`)); } else { throw new Error(`${respData.message}`); } }) // eslint-disable-next-line prefer-promise-reject-errors .catch(e => Promise.reject(`${chalk.bold.red(e)}`)); } else { throw new Error(`Error occurred in authentication. Please regenerate using authenticate`); } } catch (err) { throw new Error(`Error occurred in authentication. Please regenerate using authenticate`); } };