Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

liferay-npm-bundler

Package Overview
Dependencies
Maintainers
1
Versions
131
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

liferay-npm-bundler - npm Package Compare versions

Comparing version 2.18.5 to 3.0.0-alpha.1

CHANGELOG.md

16

bin/liferay-npm-bundler.js
#!/usr/bin/env node
/**
* SPDX-FileCopyrightText: © 2017 Liferay, Inc. <https://liferay.com>
* SPDX-License-Identifier: LGPL-3.0-or-later
*/
const {argv} = require('yargs')
.option('config', {
alias: 'c',
type: 'string',
description:
'Specify path to config file to use (instead of .npmbundlerrc)',
type: 'string',
})
.option('create-jar', {
alias: 'j',
type: 'boolean',
description:
'Create a JAR file as output (as opposed to an exploded directory)',
type: 'boolean',
})
.option('dump-report', {
alias: 'r',
type: 'boolean',
description:
'Dump report HTML file with detailed information about the bundling process',
type: 'boolean',
})
.option('version', {
alias: 'v',
description: 'Show version number and exit',
type: 'boolean',
description: 'Show version number and exit',
})

@@ -30,4 +36,4 @@ .help();

// it may get an incorrect project object.
require('liferay-npm-build-tools-common/lib/project').default.argv = argv;
require('../lib/globals').project.argv = argv;
require('../lib/index').default(argv);
"use strict";
/**
* © 2017 Liferay, Inc. <https://liferay.com>
*
* SPDX-FileCopyrightText: © 2020 Liferay, Inc. <https://liferay.com>
* SPDX-License-Identifier: LGPL-3.0-or-later

@@ -19,21 +18,19 @@ */

const fs_extra_1 = __importDefault(require("fs-extra"));
const project_1 = __importDefault(require("liferay-npm-build-tools-common/lib/project"));
const path_1 = __importDefault(require("path"));
const liferay_js_toolkit_core_1 = require("liferay-js-toolkit-core");
const pretty_time_1 = __importDefault(require("pretty-time"));
const read_json_sync_1 = __importDefault(require("read-json-sync"));
const semver_1 = __importDefault(require("semver"));
const dependencies_1 = require("./dependencies");
const insight = __importStar(require("./insight"));
const globals_1 = require("./globals");
const jar_1 = __importDefault(require("./jar"));
const log = __importStar(require("./log"));
const manifest_1 = __importDefault(require("./manifest"));
const report_1 = __importDefault(require("./report"));
const copy_1 = __importDefault(require("./steps/copy"));
const angular_cli_1 = __importDefault(require("./steps/adapt/angular-cli"));
const create_react_app_1 = __importDefault(require("./steps/adapt/create-react-app"));
const bundle_1 = __importDefault(require("./steps/bundle"));
const rules_1 = __importDefault(require("./steps/rules"));
const transform_1 = __importDefault(require("./steps/transform"));
const util_1 = require("./util");
/** Default entry point for the liferay-npm-bundler */
function default_1(argv) {
const versionsInfo = project_1.default.versionsInfo;
async function default_1(argv) {
if (argv.version) {
const { versionsInfo } = globals_1.project;
versionsInfo.forEach((value, key) => {
// eslint-disable-next-line no-console
console.log(`"${key}":`, JSON.stringify(value, null, 2));

@@ -43,84 +40,63 @@ });

}
report_1.default.versionsInfo(versionsInfo);
if (project_1.default.misc.noTracking) {
run();
}
else {
log.debug('The tool is sending usage statistics to our remote servers.');
insight.init().then(run);
}
}
exports.default = default_1;
/** Real tool execution */
function run() {
try {
const { pkgJson, versionsInfo } = globals_1.project;
const rootPkg = new liferay_js_toolkit_core_1.PkgDesc(pkgJson.name, pkgJson.version);
const start = process.hrtime();
// Get root package
const rootPkg = dependencies_1.getRootPkg();
// Report configurations
report_1.default.rootPackage(rootPkg);
// Compute dependency packages
const depPkgsMap = dependencies_1.addPackageDependencies({}, project_1.default.dir.asNative, project_1.default.copy.includedDependencies);
const depPkgs = Object.values(depPkgsMap).filter(pkg => !pkg.isRoot);
report_1.default.dependencies(depPkgs);
reportLinkedDependencies(project_1.default.pkgJson);
// Report rules config
report_1.default.rulesConfig(project_1.default.rules.config);
// Warn about incremental builds
if (manifest_1.default.loadedFromFile) {
report_1.default.warn('This report is from an incremental build: some steps may be ' +
'missing (you may remove the output directory to force a ' +
'full build).');
report_1.default.rulesConfig(globals_1.project.rules.config);
report_1.default.versionsInfo(versionsInfo);
// Initialize package.json and manifest.json files
copyPackageJson();
addRootPackageToManifest(rootPkg);
// Run main process
switch (globals_1.project.probe.type) {
case liferay_js_toolkit_core_1.ProjectType.ANGULAR_CLI:
await angular_cli_1.default();
break;
case liferay_js_toolkit_core_1.ProjectType.BUNDLER:
await bundle_1.default();
await rules_1.default(rootPkg);
break;
case liferay_js_toolkit_core_1.ProjectType.CREATE_REACT_APP:
await create_react_app_1.default();
break;
default:
util_1.abort(`Unsupported project type '${globals_1.project.probe.type}': cannot run liferay-npm-bundler`);
}
// Do things
copy_1.default(rootPkg, depPkgs)
.then(() => rules_1.default(rootPkg, depPkgs))
.then(() => transform_1.default(rootPkg, depPkgs))
.then(() => manifest_1.default.save())
.then(() => (project_1.default.jar.supported ? jar_1.default() : undefined))
.then(() => {
// Report and show execution time
const hrtime = process.hrtime(start);
report_1.default.executionTime(hrtime);
log.info(`Bundling took ${pretty_time_1.default(hrtime)}`);
// Send report analytics data
report_1.default.sendAnalytics();
// Write report if requested
if (project_1.default.misc.reportFile) {
fs_extra_1.default.writeFileSync(project_1.default.misc.reportFile.asNative, report_1.default.toHtml());
log.info(`Report written to ${project_1.default.misc.reportFile.asNative}`);
}
else if (report_1.default.warningsPresent) {
log.debug('The build has emitted some warning messages.');
}
})
.catch(abort);
// Write manifest
saveManifest();
// Create final JAR
if (globals_1.project.jar.supported) {
await jar_1.default();
}
// Report and show execution time
const hrtime = process.hrtime(start);
report_1.default.executionTime(hrtime);
log.success(`Bundled {${pkgJson.name}} in`, pretty_time_1.default(hrtime));
// Write report if requested
if (globals_1.project.misc.reportFile) {
fs_extra_1.default.writeFileSync(globals_1.project.misc.reportFile.asNative, report_1.default.toHtml());
log.info(`Report written to ${globals_1.project.misc.reportFile.asNative}`);
}
else if (report_1.default.warningsPresent) {
log.debug('The build has emitted some warning messages.');
}
}
catch (err) {
abort(err);
log.error(`\n\n${err.stack}\n\n`);
process.exit(1);
}
}
/** Report linked dependencies of a given package.json */
function reportLinkedDependencies(pkgJson) {
['dependencies', 'devDependencies'].forEach(scope => {
if (pkgJson[scope] != null) {
Object.keys(pkgJson[scope]).forEach(depName => {
const depVersion = pkgJson[scope][depName];
if (semver_1.default.validRange(depVersion) == null) {
const depPkgJsonPath = path_1.default.join('node_modules', depName, 'package.json');
const depPkgJson = read_json_sync_1.default(depPkgJsonPath);
pkgJson[scope][depName] = depPkgJson.version;
report_1.default.linkedDependency(depName, depVersion, depPkgJson.version);
}
});
}
});
exports.default = default_1;
function addRootPackageToManifest(rootPkg) {
globals_1.manifest.addPackage(rootPkg, rootPkg.clone({ dir: globals_1.buildBundlerDir.asNative }));
}
/** Abort execution after showing error message */
function abort(err) {
log.error(`
${err.stack}
`);
process.exit(1);
function copyPackageJson() {
fs_extra_1.default.copyFileSync(globals_1.project.dir.join('package.json').asNative, globals_1.buildBundlerDir.join('package.json').asNative);
log.debug('Copied package.json to output directory');
}
function saveManifest() {
globals_1.manifest.save(globals_1.buildBundlerDir.join('manifest.json').asNative);
log.debug('Wrote manifest.json to output directory');
}

@@ -9,5 +9,5 @@ "use strict";

* Transform a preferences.json file into a DDM form JSON definition
* @param {Project} project the project descriptor
* @param {object} preferencesJson a preferences JSON object
* @return {object} a DDM form JSON object
* @param project the project descriptor
* @param preferencesJson a preferences JSON object
* @return a DDM form JSON object
*/

@@ -19,6 +19,6 @@ function transformPreferences(project, preferencesJson) {

const field = {
label: localized(project, props.name || name),
name,
label: localized(project, props.name || name),
...getTypeProps(props),
};
Object.assign(field, getTypeProps(props));
if (props.description) {

@@ -40,4 +40,4 @@ field.tip = localized(project, props.description);

field.options.push({
label: localized(project, value),
value: key,
label: localized(project, value),
});

@@ -53,5 +53,5 @@ });

* Get a predefinedValue DDM object for a given field
* @param {Project} project the project descriptor
* @param {object} props the field props (in preferences.json format)
* @return {*} the predefinedValue DDM object
* @param project the project descriptor
* @param props the field props (in preferences.json format)
* @return the predefinedValue DDM object
*/

@@ -81,4 +81,4 @@ function getPredefinedValue(project, props) {

* Get the dataType and type DDM properties of a given field
* @param {object} props the field props (in preferences.json format)
* @return {object} an object containing the dataType and type properties
* @param props the field props (in preferences.json format)
* @return an object containing the dataType and type properties
*/

@@ -100,4 +100,4 @@ function getTypeProps(props) {

return {
dataType: 'integer',
type: 'numeric',
dataType: 'number',
type: 'ddm-number',
};

@@ -107,3 +107,3 @@ case 'float':

dataType: 'double',
type: 'numeric',
type: 'ddm-decimal',
};

@@ -124,5 +124,5 @@ case 'boolean':

* default locale value)
* @param {Project} project the project descriptor
* @param {string} string the string to localize
* @return {object} the DDM localized value
* @param project the project descriptor
* @param string the string to localize
* @return the DDM localized value
*/

@@ -135,4 +135,4 @@ function localized(project, string) {

let labels = project.l10n.getLabels();
obj[''] = labels[string] || string;
project.l10n.availableLocales.forEach(locale => {
obj[''] = labels[string];
project.l10n.availableLocales.forEach((locale) => {
labels = project.l10n.getLabels(locale);

@@ -139,0 +139,0 @@ obj[locale] = labels[string];

@@ -20,11 +20,10 @@ "use strict";

const jszip_1 = __importDefault(require("jszip"));
const file_path_1 = __importDefault(require("liferay-npm-build-tools-common/lib/file-path"));
const project_1 = __importDefault(require("liferay-npm-build-tools-common/lib/project"));
const liferay_js_toolkit_core_1 = require("liferay-js-toolkit-core");
const path_1 = __importDefault(require("path"));
const globals_1 = require("../globals");
const ddm = __importStar(require("./ddm"));
const xml = __importStar(require("./xml"));
const pkgJson = project_1.default.pkgJson;
const pkgJson = globals_1.project.pkgJson;
/**
* Create an OSGi bundle with build's output
* @return {Promise}
*/

@@ -36,7 +35,7 @@ function createJar() {

addLocalizationFiles(zip);
addSystemConfigurationFiles(zip);
addPortletInstanceConfigurationFile(zip);
return zip.generateAsync({ type: 'nodebuffer' }).then(buffer => {
fs_extra_1.default.mkdirpSync(project_1.default.jar.outputDir.asNative);
fs_extra_1.default.writeFileSync(project_1.default.jar.outputDir.join(project_1.default.jar.outputFilename).asNative, buffer);
addConfigurationJsonSystemFiles(zip);
addConfigurationJsonPortletInstanceFile(zip);
return zip.generateAsync({ type: 'nodebuffer' }).then((buffer) => {
fs_extra_1.default.mkdirpSync(globals_1.project.jar.outputDir.asNative);
fs_extra_1.default.writeFileSync(globals_1.project.jar.outputDir.join(globals_1.project.jar.outputFilename).asNative, buffer);
});

@@ -47,13 +46,12 @@ }

* Add build's output files to ZIP archive
* @param {JSZip} zip the ZIP file
*/
function addBuildFiles(zip) {
addFiles(project_1.default.buildDir.asNative, ['**/*', `!${project_1.default.jar.outputFilename}`], zip.folder('META-INF').folder('resources'));
addFiles(globals_1.buildBundlerDir.asNative, ['**/*', `!${globals_1.project.jar.outputFilename}`], zip.folder('META-INF').folder('resources'));
}
/**
* Add several files to a ZIP folder.
* @param {string} srcDirPath source folder
* @param {array} srcGlobs array of globs describing files to include (in
* globby, i.e. POSIX, format)
* @param {JSZip} destFolder the destination folder in the ZIP file
* @param srcDirPath source folder
* @param srcGlobs
* array of globs describing files to include (in globby, i.e. POSIX, format)
* @param destFolder the destination folder in the ZIP file
*/

@@ -66,5 +64,5 @@ function addFiles(srcDirPath, srcGlobs, destFolder) {

})
.map(posixPath => new file_path_1.default(posixPath, { posix: true }))
.map(file => file.asNative);
filePaths.forEach(filePath => {
.map((posixPath) => new liferay_js_toolkit_core_1.FilePath(posixPath, { posix: true }))
.map((file) => file.asNative);
filePaths.forEach((filePath) => {
const parts = filePath.split(path_1.default.sep);

@@ -79,6 +77,5 @@ const dirs = parts.slice(0, parts.length - 1);

* Add the localization bundle files if configured.
* @param {JSZip} zip the ZIP file
*/
function addLocalizationFiles(zip) {
const languageFileBaseName = project_1.default.l10n.languageFileBaseName;
const languageFileBaseName = globals_1.project.l10n.languageFileBaseName;
if (languageFileBaseName) {

@@ -91,7 +88,6 @@ const localizationDirPath = path_1.default.dirname(languageFileBaseName.asNative);

* Add the manifest file to the ZIP archive
* @param {JSZip} zip the ZIP file
*/
function addManifest(zip) {
let contents = '';
const bundlerVersion = project_1.default.versionsInfo.get('liferay-npm-bundler')
const bundlerVersion = globals_1.project.versionsInfo.get('liferay-npm-bundler')
.version;

@@ -106,3 +102,3 @@ contents += `Manifest-Version: 1.0\n`;

}
contents += `Web-ContextPath: ${project_1.default.jar.webContextPath}\n`;
contents += `Web-ContextPath: ${globals_1.project.jar.webContextPath}\n`;
contents +=

@@ -112,8 +108,8 @@ `Provide-Capability: osgi.webresource;` +

`version:Version="${pkgJson.version}"\n`;
if (project_1.default.l10n.supported) {
const bundleName = path_1.default.basename(project_1.default.l10n.languageFileBaseName.asNative);
if (globals_1.project.l10n.supported) {
const bundleName = path_1.default.basename(globals_1.project.l10n.languageFileBaseName.asNative);
contents += `Provide-Capability: liferay.resource.bundle;`;
contents += `resource.bundle.base.name="content.${bundleName}"\n`;
}
if (project_1.default.jar.requireJsExtender) {
if (globals_1.project.jar.requireJsExtender) {
let filter;

@@ -133,3 +129,3 @@ const minimumExtenderVersion = getMinimumExtenderVersion();

}
Object.entries(project_1.default.jar.customManifestHeaders).forEach(([key, value]) => {
Object.entries(globals_1.project.jar.customManifestHeaders).forEach(([key, value]) => {
contents += `${key}: ${value}\n`;

@@ -141,6 +137,5 @@ });

* Add the settings files if configured.
* @param {JSZip} zip the ZIP file
*/
function addSystemConfigurationFiles(zip) {
const systemConfigJson = getSystemConfigurationJson();
function addConfigurationJsonSystemFiles(zip) {
const systemConfigJson = getConfigurationJsonSystemJson();
if (!systemConfigJson) {

@@ -150,4 +145,4 @@ return;

// Add OSGI-INF/metatype/metatype.xml file
const localization = project_1.default.l10n.supported
? `content/${path_1.default.basename(project_1.default.l10n.languageFileBaseName.asNative)}`
const localization = globals_1.project.l10n.supported
? `content/${path_1.default.basename(globals_1.project.l10n.languageFileBaseName.asNative)}`
: undefined;

@@ -170,3 +165,3 @@ const name = systemConfigJson.name ||

if (systemConfigJson.category) {
metatypeJson.category = systemConfigJson.category;
metatypeJson['category'] = systemConfigJson.category;
}

@@ -177,10 +172,9 @@ zip.folder('features').file('metatype.json', JSON.stringify(metatypeJson, null, 2));

* Add the portlet preferences file if configured.
* @param {JSZip} zip the ZIP file
*/
function addPortletInstanceConfigurationFile(zip) {
const portletInstanceConfigJson = getPortletInstanceConfigurationJson();
function addConfigurationJsonPortletInstanceFile(zip) {
const portletInstanceConfigJson = getConfigurationJsonPortletInstanceJson();
if (!portletInstanceConfigJson) {
return;
}
const ddmJson = ddm.transformPreferences(project_1.default, portletInstanceConfigJson);
const ddmJson = ddm.transformPreferences(globals_1.project, portletInstanceConfigJson);
zip.folder('features').file('portlet_preferences.json', JSON.stringify(ddmJson, null, 2));

@@ -191,6 +185,7 @@ }

* to work
* @return {string|undefined} a version number or undefined if none is required
*
* @return a version number or undefined if none is required
*/
function getMinimumExtenderVersion() {
const requireJsExtender = project_1.default.jar.requireJsExtender;
const requireJsExtender = globals_1.project.jar.requireJsExtender;
if (typeof requireJsExtender === 'string') {

@@ -203,6 +198,6 @@ if (requireJsExtender === 'any') {

let minExtenderMinorVersion = 0;
if (getSystemConfigurationJson()) {
if (getConfigurationJsonSystemJson()) {
minExtenderMinorVersion = Math.max(minExtenderMinorVersion, 1);
}
if (getPortletInstanceConfigurationJson()) {
if (getConfigurationJsonPortletInstanceJson()) {
minExtenderMinorVersion = Math.max(minExtenderMinorVersion, 1);

@@ -215,13 +210,12 @@ }

* file.
* @return {object}
*/
function getPortletInstanceConfigurationJson() {
if (!project_1.default.jar.configurationFile) {
function getConfigurationJsonPortletInstanceJson() {
if (!globals_1.project.jar.configurationFile) {
return undefined;
}
const filePath = project_1.default.jar.configurationFile.asNative;
const filePath = globals_1.project.jar.configurationFile.asNative;
const configurationJson = fs_extra_1.default.readJSONSync(filePath);
if (!configurationJson.portletInstance ||
!configurationJson.portletInstance.fields ||
Object.keys(configurationJson.portletInstance.fields).length == 0) {
Object.keys(configurationJson.portletInstance.fields).length === 0) {
return undefined;

@@ -235,11 +229,11 @@ }

*/
function getSystemConfigurationJson() {
if (!project_1.default.jar.configurationFile) {
function getConfigurationJsonSystemJson() {
if (!globals_1.project.jar.configurationFile) {
return undefined;
}
const filePath = project_1.default.jar.configurationFile.asNative;
const filePath = globals_1.project.jar.configurationFile.asNative;
const configurationJson = fs_extra_1.default.readJSONSync(filePath);
if (!configurationJson.system ||
!configurationJson.system.fields ||
Object.keys(configurationJson.system.fields).length == 0) {
Object.keys(configurationJson.system.fields).length === 0) {
return undefined;

@@ -246,0 +240,0 @@ }

@@ -17,6 +17,2 @@ "use strict";

* Add a metatype AD node to the XML
* @param {object} metatype
* @param {string} id id of field
* @param {object} desc an object with type, name, description, required,
* default, min, max and options fields
*/

@@ -49,7 +45,2 @@ function addMetatypeAttr(metatype, id, desc) {

exports.addMetatypeAttr = addMetatypeAttr;
/**
*
* @param {object} xml
* @param {string} localization
*/
function addMetatypeLocalization(xml, localization) {

@@ -61,5 +52,4 @@ const metadata = findChild(xml, 'metatype:MetaData');

/**
* @param {string} id id of configuration
* @param {string} name human readable name of configuration
* @return {object}
* @param id id of configuration
* @param name human readable name of configuration
*/

@@ -78,4 +68,2 @@ function createMetatype(id, name) {

* Format an XML object and return it as a string.
* @param {object} xml
* @return {string}
*/

@@ -88,5 +76,2 @@ function format(xml) {

* Add an attribute to an XML node.
* @param {object} node
* @param {string} name
* @param {string} value
*/

@@ -99,12 +84,9 @@ function addAttr(node, name, value) {

* Add a child node to an existing node.
* @param {object} parentNode
* @param {string} childName
* @return {object} the child node
*/
function addChild(parentNode, childName) {
const childNode = {
type: 'element',
name: childName,
attributes: {},
elements: [],
name: childName,
type: 'element',
};

@@ -117,16 +99,12 @@ parentNode.elements = parentNode.elements || [];

* Find an XML child node creating it if necessary.
* @param {object} parentNode
* @param {string} childName
* @param {boolean} create
* @return {object} the child node
*/
function findChild(parentNode, childName, create = false) {
const elements = parentNode.elements || [];
let childNode = elements.find(node => node.name == childName);
let childNode = elements.find((node) => node.name === childName);
if (childNode === undefined && create) {
childNode = {
type: 'element',
name: childName,
attributes: {},
elements: [],
name: childName,
type: 'element',
};

@@ -133,0 +111,0 @@ parentNode.elements = elements;

@@ -6,32 +6,40 @@ "use strict";

*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const project_1 = __importDefault(require("liferay-npm-build-tools-common/lib/project"));
/**
* Log errors
* @return {void}
*/
const liferay_js_toolkit_core_1 = require("liferay-js-toolkit-core");
const globals_1 = require("./globals");
const { logLevel } = globals_1.project.misc;
function error(...args) {
console.log(...args);
if (logLevel < liferay_js_toolkit_core_1.LogLevel.error) {
return;
}
liferay_js_toolkit_core_1.format.print(liferay_js_toolkit_core_1.format.error `${args.join(' ')}`);
}
exports.error = error;
/**
* Log message as console.log does
* @return {void}
*/
function warn(...args) {
if (logLevel < liferay_js_toolkit_core_1.LogLevel.warn) {
return;
}
liferay_js_toolkit_core_1.format.print(liferay_js_toolkit_core_1.format.warn `${args.join(' ')}`);
}
exports.warn = warn;
function success(...args) {
if (logLevel < liferay_js_toolkit_core_1.LogLevel.error) {
return;
}
liferay_js_toolkit_core_1.format.print(liferay_js_toolkit_core_1.format.success `${args.join(' ')}`);
}
exports.success = success;
function info(...args) {
console.log(...args);
if (logLevel < liferay_js_toolkit_core_1.LogLevel.info) {
return;
}
liferay_js_toolkit_core_1.format.print(liferay_js_toolkit_core_1.format.info `${args.join(' ')}`);
}
exports.info = info;
/**
* Log message as console.log does but only if verbose is on
* @return {void}
*/
function debug(...args) {
if (project_1.default.misc.verbose) {
console.log(...args);
if (logLevel < liferay_js_toolkit_core_1.LogLevel.debug) {
return;
}
liferay_js_toolkit_core_1.format.print(liferay_js_toolkit_core_1.format.debug `${args.join(' ')}`);
}
exports.debug = debug;

@@ -10,4 +10,5 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
/* eslint require-jsdoc: off */
const liferay_js_toolkit_core_1 = require("liferay-js-toolkit-core");
const pretty_time_1 = __importDefault(require("pretty-time"));
/* eslint-disable sort-keys */
const LOG_LEVEL_SORT = {

@@ -18,155 +19,43 @@ error: 0,

};
/* eslint-enable sort-keys */
function htmlDump(report) {
const { _executionDate, _executionTime, _packages, _rules, _versionsInfo, _warnings, } = report;
const { _executionDate, _executionTime, _rootPkg, _rules, _versionsInfo, _warnings, _webpack, } = report;
const title = 'Report of liferay-npm-bundler execution';
const summary = htmlTable([
htmlRow(`<td>Executed at:</td><td>${_executionDate.toUTCString()}</td>`),
htmlIf(_executionTime, () => htmlRow(`<td>Execution took:</td><td>${pretty_time_1.default(_executionTime)}</td>`)),
htmlIf(_executionTime !== undefined, () => htmlRow(`<td>Execution took:</td><td>${pretty_time_1.default(_executionTime)}</td>`)),
]);
const warnings = htmlIf(_warnings.length > 0, () => htmlSection('Warnings', htmlList(..._warnings)));
const versionsInfo = htmlSection('Bundler environment versions', htmlTable('Package', 'Version', Object.keys(_versionsInfo).map(pkgName => htmlRow(`
const projectInfo = htmlSection('Project information', htmlTable('Name', 'Version', htmlRow(`
<td>${_rootPkg.name}</td>
<td>${_rootPkg.version}</td>
`)));
const versionsInfo = htmlSection('Bundler environment versions', htmlTable('Package', 'Version', Object.keys(_versionsInfo).map((pkgName) => htmlRow(`
<td>${pkgName}</td>
<td>${_versionsInfo[pkgName].version}</td>
`))));
const dependencies = htmlSection('Bundled packages', htmlTable('Package', 'Version', 'Copied files', 'Excluded files', 'Linked to', Object.keys(_packages)
const webpack = htmlSection('Details of webpack execution', htmlTable('File', '', 'Source', 'Messages', Object.entries(_webpack.logs)
.sort((a, b) => a[0].localeCompare(b[0]))
.map(([prjRelPath, sources]) => Object.entries(sources).map(([source, logger]) => logger.messages
.map(({ logLevel, things }, index) => htmlRow(`
<td>${index === 0 ? prjRelPath : ''}</td>
<td class="${logLevel}">
${liferay_js_toolkit_core_1.LogLevel[logLevel].toUpperCase()}
</td>
<td class="source">[${source}]</td>
<td>
${things.map((thing) => `${thing}`).join(' ')}
</td>
`, liferay_js_toolkit_core_1.LogLevel[logLevel]))
.join('')))));
const rulesExecution = htmlIf(Object.keys(_rules.files).length > 0, () => htmlSection('Details of rule executions', `
<div class="configuration">
<div>Configuration</div>
<pre>${JSON.stringify(_rules.config, null, 2)}</pre>
</div>
`, htmlLogOutput(['File'], Object.keys(_rules.files)
.sort()
.map(pkgId => {
const { allFiles, copiedFiles, link, name, version, } = _packages[pkgId];
return htmlRow(`
<td>${name}</td>
<td>${version}</td>
<td>${htmlIf(copiedFiles, () => `<div title="${copiedFiles.sort().join(',')}">
${copiedFiles.length}
</div>`)}</td>
<td>
${htmlIf(allFiles && copiedFiles, () => `<div title="${allFiles
.filter(file => copiedFiles.indexOf(file) == -1)
.sort()
.join(',')}">
${allFiles.length - copiedFiles.length}
</div>`)}
</td>
<td>${htmlIf(link, () => link)}</td>
`);
})));
const rulesExecution = htmlSection('Details of rule executions', `
<div class="configuration">
<div>Configuration</div>
<pre>${JSON.stringify(_rules.config, null, 2)}</pre>
</div>
`, htmlLogOutput(['File'], Object.keys(_rules.files)
.map((filePath) => [filePath]), Object.keys(_rules.files)
.sort()
.map(filePath => [filePath]), Object.keys(_rules.files)
.sort()
.map(filePath => _rules.files[filePath].logger)));
const packageProcessesPresent = Object.keys(_packages).reduce((found, pkgId) => {
const pkg = _packages[pkgId];
const { babel, copy, post, pre } = pkg.process;
const copyKeys = Object.keys(copy);
const preKeys = Object.keys(pre);
const postKeys = Object.keys(post);
const babelKeys = Object.keys(babel.files);
found |= copyKeys.length > 0;
found |= preKeys.length > 0;
found |= postKeys.length > 0;
found |= babelKeys.length > 0;
return found;
}, false);
const packageProcesses = htmlSection('Summary of package transformations', htmlTable('Package', 'Version', 'Copy phase', 'Pre-babel phase', 'Babel phase', 'Post-babel phase', Object.keys(_packages)
.sort()
.map(pkgId => {
const pkg = _packages[pkgId];
const { babel, copy, post, pre } = pkg.process;
const copyKeys = Object.keys(copy);
const preKeys = Object.keys(pre);
const postKeys = Object.keys(post);
const babelKeys = Object.keys(babel.files);
const copyNotice = htmlIf(copyKeys.length > 0, () => `${copyKeys.length} plugins applied`);
const preNotice = htmlIf(preKeys.length > 0, () => `${preKeys.length} plugins applied`);
const babelNotice = htmlIf(babelKeys.length > 0, () => `${babelKeys.length} files processed`);
const postNotice = htmlIf(postKeys.length > 0, () => `${postKeys.length} plugins applied`);
return htmlRow(`
<td>${pkg.name}</td>
<td>${pkg.version}</td>
<td>
<a href="#${pkgId}-bundler">
${copyNotice}
</a>
</td>
<td>
<a href="#${pkgId}-bundler">
${preNotice}
</a>
</td>
<td>
<a href="#${pkgId}-babel">
${babelNotice}
</a>
</td>
<td>
<a href="#${pkgId}-bundler">
${postNotice}
</a>
</td>
`);
})));
const packageProcessesBundlerDetails = htmlSection('Details of bundler transformations', ...Object.keys(_packages)
.sort()
.map(pkgId => {
const pkg = _packages[pkgId];
const { copy, post, pre } = pkg.process;
const copyKeys = Object.keys(copy);
const preKeys = Object.keys(pre);
const postKeys = Object.keys(post);
return htmlIf(copyKeys.length > 0 ||
preKeys.length > 0 ||
postKeys.length > 0, () => htmlSubsection(`
<a name="${pkgId}-bundler">
${pkg.name}@${pkg.version}
</a>
`, ...htmlIf(copyKeys.length > 0, () => copyKeys
.sort()
.map(pluginName => htmlLogOutput(['Copy phase plugin', 'Config'], [
[
pluginName,
JSON.stringify(copy[pluginName].plugin
.config),
],
], [copy[pluginName].logger], { source: false }))), ...htmlIf(preKeys.length > 0, () => preKeys
.sort()
.map(pluginName => htmlLogOutput(['Pre-phase plugin', 'Config'], [
[
pluginName,
JSON.stringify(pre[pluginName].plugin
.config),
],
], [pre[pluginName].logger], { source: false }))), ...htmlIf(postKeys.length > 0, () => postKeys
.sort()
.map(pluginName => htmlLogOutput(['Post-phase plugin', 'Config'], [
[
pluginName,
JSON.stringify(post[pluginName].plugin
.config),
],
], [post[pluginName].logger], { source: false })))));
}));
const packageProcessesBabelDetails = htmlSection('Details of Babel transformations', ...Object.keys(_packages)
.sort()
.map(pkgId => {
const pkg = _packages[pkgId];
const { babel } = pkg.process;
const babelKeys = Object.keys(babel.files);
return htmlIf(babelKeys.length > 0, () => htmlSubsection(`
<a name="${pkgId}-babel">
${pkg.name}@${pkg.version}
</a>
`, `
<div class="configuration">
<div>Configuration</div>
<pre>${JSON.stringify(babel.config, null, 2)}</pre>
</div>
`, htmlLogOutput(['File'], babelKeys.sort().map(filePath => [filePath]), babelKeys
.sort()
.map(filePath => babel.files[filePath].logger))));
}));
.map((filePath) => _rules.files[filePath].logger))));
return `

@@ -216,10 +105,10 @@ <!DOCTYPE html>

th, td {
padding: .1em 0;
padding: .1em;
vertical-align: top;
}
td.info, td.warn, td.error {
background: green;
td.debug, td.info, td.warn, td.error {
border-radius: 4px;
color: white;
padding: 0 2px;
text-align: center;

@@ -231,2 +120,10 @@ vertical-align: middle;

td.debug {
background: gray;
}
td.info {
background: green;
}
td.warn {

@@ -241,2 +138,3 @@ background: orange;

td.source {
color: grey;
white-space: nowrap;

@@ -319,12 +217,18 @@ }

select.value = 'info';
select.value = 'debug';
select.onchange = function() {
switch(select.value) {
case 'info':
case 'debug':
style.innerHTML = '';
break;
case 'info':
style.innerHTML =
'tr.debug {display: none;}';
break;
case 'warn':
style.innerHTML =
'tr.debug {display: none;}' +
'tr.info {display: none;}';

@@ -335,2 +239,3 @@ break;

style.innerHTML =
'tr.debug {display: none;}' +
'tr.info {display: none;} ' +

@@ -348,2 +253,3 @@ 'tr.warn {display: none;}';

<select id='log-level-select'>
<option>debug</option>
<option>info</option>

@@ -358,10 +264,6 @@ <option>warn</option>

${warnings}
${projectInfo}
${versionsInfo}
${dependencies}
${webpack}
${rulesExecution}
${htmlIf(packageProcessesPresent, () => `
${packageProcesses}
${packageProcessesBundlerDetails}
${packageProcessesBabelDetails}
`)}
</body>

@@ -381,2 +283,3 @@ </html>

}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function htmlSubsection(title, ...contents) {

@@ -391,3 +294,3 @@ return `

<ul>
${args.map(arg => `<li>${arg}</li>`).join(' ')}
${args.map((arg) => `<li>${arg}</li>`).join(' ')}
</ul>

@@ -402,3 +305,3 @@ `;

}
if (columns.length == 0) {
if (columns.length === 0) {
return `

@@ -413,3 +316,3 @@ <table>

<table>
${htmlRow(columns.map(column => `<th>${column}</th>`))}
${htmlRow(columns.map((column) => `<th>${column}</th>`))}
${content}

@@ -428,7 +331,7 @@ </table>

* Dump a table with the output of a PluginLogger
* @param {Array} prefixColumns [description]
* @param {Array<Array>} prefixCells an array with one array per row containing the prefix cell content
* @param {Array} rowLoggers an array with one logger per row in prefixCells
* @param {boolean} source whether or not to show 'Log source' column
* @return {String} an HTML table
* @param prefixCells
* an array with one array per row containing the prefix cell content
* @param rowLoggers an array with one logger per row in prefixCells
* @param source whether or not to show 'Log source' column
* @return an HTML table
*/

@@ -450,5 +353,5 @@ function htmlLogOutput(prefixColumns, prefixCells, rowLoggers, { source } = { source: true }) {

const msgs = rowLoggers[i].messages;
if (msgs.length == 0) {
if (msgs.length === 0) {
rows.push(htmlRow(`
${cells.map(cell => `<td>${cell}</td>`).join(' ')}
${cells.map((cell) => `<td>${cell}</td>`).join(' ')}
${htmlIf(source, () => `<td></td>`)}

@@ -466,5 +369,5 @@ ${logColums

let sourceCell = htmlIf(source, () => `<td class="source">${msg0.source}</td>`);
let infoLink = htmlIf(msg0['link'], () => `<a href='${msg0['link']}'>🛈</a>`);
let infoLink = htmlIf(msg0['link'] !== undefined, () => `<a href='${msg0['link']}'>🛈</a>`);
rows.push(htmlRow(`
${cells.map(cell => `<td>${cell}</td>`).join(' ')}
${cells.map((cell) => `<td>${cell}</td>`).join(' ')}
${sourceCell}

@@ -477,3 +380,3 @@ <td class="${msg0.level}">${msg0.level.toUpperCase()}</td>

sourceCell = htmlIf(source, () => `<td class="source">${msgs[i].source}</td>`);
infoLink = htmlIf(msgs[i]['link'], () => `<a href='${msgs[i]['link']}'>🛈</a>`);
infoLink = htmlIf(msgs[i]['link'] !== undefined, () => `<a href='${msgs[i]['link']}'>🛈</a>`);
rows.push(htmlRow(`

@@ -480,0 +383,0 @@ ${cells.map(() => `<td></td>`).join(' ')}

@@ -6,18 +6,18 @@ "use strict";

*/
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const analytics_1 = require("./analytics");
const html_1 = require("./html");
const logger_1 = __importDefault(require("./logger"));
/**
* A Report holds data describing a execution of the liferay-npm-bundler so that
* it can be dump as an HTML report.
* @type {Report}
*/
class Report {
/**
* Constructor
*/
constructor() {
this._executionDate = new Date();
this._executionTime = undefined;
this._versionsInfo = {};
this._packages = {};
this._rootPkg = undefined;
this._rules = {

@@ -28,6 +28,8 @@ config: {},

this._warnings = [];
this._webpack = {
logs: {},
};
}
/**
* Return an HTML string with the information contained in this report.
* @return {String} an HTML string
*/

@@ -38,11 +40,4 @@ toHtml() {

/**
* Dump report information to insight package so that it gets exported to
* our Google Analytics account.
* @return {void}
*/
sendAnalytics() {
return analytics_1.analyticsDump(this);
}
/**
* Register execution time.
*
* @param {Array} hrtime the time it took to execute

@@ -56,3 +51,4 @@ * @return {void}

* Test if there are global warning messages present.
* @return {boolean} true if warnings exist
*
* @return true if warnings exist
*/

@@ -64,8 +60,8 @@ get warningsPresent() {

* Register a warning.
* @param {String} message the warning message
* @param {boolean} unique set to true if you want this warning to be deduped
* @return {void}
*
* @param message the warning message
* @param unique set to true if you want this warning to be deduped
*/
warn(message, { unique } = { unique: false }) {
if (unique && this._warnings.find(item => item === message)) {
if (unique && this._warnings.find((item) => item === message)) {
return;

@@ -78,2 +74,3 @@ }

* build process.
*
* @param {Object} info a hash or (package,version) pairs

@@ -94,85 +91,8 @@ * @return {void}

rootPackage(rootPkg) {
const pkg = this._getPackage(rootPkg.id);
pkg.name = rootPkg.name;
pkg.version = rootPkg.version;
}
/**
* Register the list of dependencies detected in this build.
* @param {Array} deps an array of PkgDesc objects
* @return {void}
*/
dependencies(deps) {
deps.forEach(dep => {
const pkg = this._getPackage(dep.id);
pkg.name = dep.name;
pkg.version = dep.version;
});
}
/**
* Register a linked dependency found in the root package.json. This method
* must be called after registering all dependencies with the dependencies()
* method. Unknown dependencies will be ignored.
* @param {String} packageName package name
* @param {String} packageLink the link to the package
* @param {String} packageVersion package version
* @return {void}
*/
linkedDependency(packageName, packageLink, packageVersion) {
const pkgId = `${packageName}@${packageVersion}`;
const pkg = this._getPackage(pkgId, false);
if (pkg) {
pkg.link = packageLink;
pkg.version = packageVersion;
}
}
/**
* Register a package copy action.
* @param {Object} pkg a package descriptor
* @param {Array} allFiles the list of all files in the package
* @param {Array} copiedFiles the list of files copied to the target
* @return {void}
*/
packageCopy(pkg, allFiles, copiedFiles) {
const rpkg = this._getPackage(pkg.id);
Object.assign(rpkg, {
allFiles,
copiedFiles,
});
}
/**
* Register a liferay-npm-bundler plugin execution.
* @param {String} phase run phase (pre or post)
* @param {Object} pkg package descriptor
* @param {Object} plugin plugin descriptor (with config and run fields)
* @param {PluginLogger} logger the logger cotaining the process messages
* @return {void}
*/
packageProcessBundlerPlugin(phase, pkg, plugin, logger) {
const pkgProcess = this._getPackageProcess(pkg.id);
pkgProcess[phase][plugin.name] = {
plugin,
logger,
this._rootPkg = {
id: rootPkg.id,
name: rootPkg.name,
version: rootPkg.version,
};
}
/**
* Register a Babel execution config.
* @param {Object} pkg package descriptor
* @param {Object} babelConfig the Babel config object
* @return {void}
*/
packageProcessBabelConfig(pkg, babelConfig) {
const { babel } = this._getPackageProcess(pkg.id);
babel.config = babelConfig;
}
/**
* Register a Babel file process.
* @param {Object} pkg package descriptor
* @param {String} filePath the file path
* @param {PluginLogger} logger the logger cotaining the process messages
* @return {void}
*/
packageProcessBabelRun(pkg, filePath, logger) {
const { babel } = this._getPackageProcess(pkg.id);
babel.files[filePath] = { logger };
}
rulesConfig(config) {

@@ -184,36 +104,11 @@ this._rules.config = config;

}
/**
* Get a package slot and create it if missing.
* @param {String} pkgId the package id
* @param {Boolean} create whether to create the entry if it doesn't exist
* @return {Object} a package slot
*/
_getPackage(pkgId, create = true) {
let pkg = this._packages[pkgId];
if (!pkg && create) {
pkg = this._packages[pkgId] = {
id: pkgId,
};
this._getPackageProcess(pkgId);
getWebpackLogger(source, prjRelPath) {
if (this._webpack.logs[prjRelPath] === undefined) {
this._webpack.logs[prjRelPath] = {};
}
return pkg;
if (this._webpack.logs[prjRelPath][source] === undefined) {
this._webpack.logs[prjRelPath][source] = new logger_1.default();
}
return this._webpack.logs[prjRelPath][source];
}
/**
* Get a package process slot and create it if missing.
* @param {String} pkgId the package id
* @return {Object} a package process slot
*/
_getPackageProcess(pkgId) {
const rpkg = this._getPackage(pkgId);
rpkg.process = rpkg.process || {
copy: {},
pre: {},
babel: {
config: {},
files: {},
},
post: {},
};
return rpkg.process;
}
}

@@ -220,0 +115,0 @@ exports.Report = Report;

@@ -18,30 +18,19 @@ "use strict";

const fs_extra_1 = __importDefault(require("fs-extra"));
const gl = __importStar(require("liferay-npm-build-tools-common/lib/globs"));
const plugin_logger_1 = __importDefault(require("liferay-npm-build-tools-common/lib/plugin-logger"));
const project_1 = __importDefault(require("liferay-npm-build-tools-common/lib/project"));
const liferay_js_toolkit_core_1 = require("liferay-js-toolkit-core");
const path_1 = __importDefault(require("path"));
const globals_1 = require("../globals");
const log = __importStar(require("../log"));
const report_1 = __importDefault(require("../report"));
const util_1 = require("./util");
const util_1 = require("../util");
const files_1 = require("../util/files");
/**
* Run configured rules.
* @param {PkgDesc} rootPkg the root package descriptor
* @param {Array<PkgDesc>} depPkgs dependency package descriptors
* @return {Promise}
*/
function runRules(rootPkg, depPkgs) {
const dirtyPkgs = [rootPkg, ...depPkgs].filter(srcPkg => !srcPkg.clean);
return Promise.all(dirtyPkgs.map(srcPkg => processPackage(srcPkg))).then(() => log.debug(`Applied rules to ${dirtyPkgs.length} packages`));
function runRules(rootPkg) {
return processPackage(rootPkg);
}
exports.default = runRules;
/**
*
* @param {PkgDesc} srcPkg
* @param {number} chunkIndex
* @return {Promise}
*/
function processPackage(srcPkg) {
log.debug(`Applying rules to package '${srcPkg.id}'...`);
const sourceGlobs = srcPkg.isRoot
? project_1.default.sources.map(source => fs_extra_1.default.statSync(project_1.default.dir.join(source).asNative).isDirectory()
? globals_1.project.sources.map((source) => fs_extra_1.default.statSync(globals_1.project.dir.join(source).asNative).isDirectory()
? `${source.asPosix}/**/*`

@@ -51,26 +40,23 @@ : source.asPosix)

const globs = [...sourceGlobs, '!node_modules/**/*'];
const sourcePrjRelPaths = util_1.findFiles(project_1.default.dir.asNative, gl.prefix(`${project_1.default.dir.asPosix}/${srcPkg.dir.asPosix}/`, globs));
const sourcePrjRelPaths = files_1.findFiles(globals_1.project.dir.asNative, liferay_js_toolkit_core_1.prefixGlobs(`${globals_1.project.dir.asPosix}/${srcPkg.dir.asPosix}/`, globs)).map((file) => file.asNative);
if (sourcePrjRelPaths.length === 0) {
return Promise.resolve();
}
log.debug(`Applying rules to package '${srcPkg.id}'...`);
const destPkg = srcPkg.clone({
dir: util_1.getDestDir(srcPkg),
});
return util_1.runInChunks(sourcePrjRelPaths, project_1.default.misc.maxParallelFiles, 0, prjRelPath => processFile(srcPkg, destPkg, prjRelPath));
return util_1.runInChunks(sourcePrjRelPaths, globals_1.project.misc.maxParallelFiles, 0, (prjRelPath) => processFile(srcPkg, destPkg, prjRelPath));
}
/**
*
* @param {PkgDesc} srcPkg
* @param {PkgDesc} destPkg
* @param {string} prjRelPath
* @return {Promise}
*/
function processFile(srcPkg, destPkg, prjRelPath) {
const loaders = project_1.default.rules.loadersForFile(prjRelPath);
if (loaders.length == 0) {
const loaders = globals_1.project.rules.loadersForFile(prjRelPath);
if (loaders.length === 0) {
return Promise.resolve();
}
const fileAbsPath = project_1.default.dir.join(prjRelPath).asNative;
const fileAbsPath = globals_1.project.dir.join(prjRelPath).asNative;
const context = {
content: fs_extra_1.default.readFileSync(fileAbsPath),
extraArtifacts: {},
filePath: prjRelPath,
extraArtifacts: {},
log: new plugin_logger_1.default(),
log: new liferay_js_toolkit_core_1.PluginLogger(),
};

@@ -83,6 +69,4 @@ return runLoaders(loaders, 0, context)

* Run rule loaders contained in an array starting at given index.
* @param {Array<object>} loaders
* @param {number} firstLoaderIndex
* @param {object} context the context object to pass to loaders
* @return {Promise}
* @param context the context object to pass to loaders
* @return the processed context content
*/

@@ -101,6 +85,6 @@ function runLoaders(loaders, firstLoaderIndex, context) {

catch (err) {
err.message = `Loader '${loader.use}' failed: ${err.message}`;
err.message = `Loader '${loader.loader}' failed: ${err.message}`;
throw err;
}
return Promise.resolve(result).then(content => {
return Promise.resolve(result).then((content) => {
if (content !== undefined) {

@@ -116,5 +100,4 @@ context = Object.assign(context, { content });

* Buffer to string with given `encoding` or the opposite way.
* @param {boolean} beforeInvocation true if called before invoking the loader
* @param {object} context
* @param {string} encoding
* @param beforeInvocation true if called before invoking the loader
*/

@@ -125,3 +108,3 @@ function transformContents(beforeInvocation, context, encoding) {

assertBuffer(context, 'content', filePath);
Object.keys(extraArtifacts).forEach(key => {
Object.keys(extraArtifacts).forEach((key) => {
assertBuffer(extraArtifacts, key, `extra artifact ${key}`);

@@ -135,3 +118,3 @@ });

}
Object.keys(extraArtifacts).forEach(key => {
Object.keys(extraArtifacts).forEach((key) => {
if (extraArtifacts[key] !== undefined) {

@@ -144,3 +127,3 @@ extraArtifacts[key] = extraArtifacts[key].toString(encoding);

assertBuffer(context, 'content', filePath);
Object.keys(extraArtifacts).forEach(key => {
Object.keys(extraArtifacts).forEach((key) => {
assertBuffer(extraArtifacts, key, `extra artifact ${key}`);

@@ -151,3 +134,3 @@ });

assertString(context, 'content', filePath);
Object.keys(extraArtifacts).forEach(key => {
Object.keys(extraArtifacts).forEach((key) => {
assertString(extraArtifacts, key, `extra artifact ${key}`);

@@ -158,3 +141,3 @@ });

}
Object.keys(extraArtifacts).forEach(key => {
Object.keys(extraArtifacts).forEach((key) => {
if (extraArtifacts[key] !== undefined) {

@@ -169,5 +152,2 @@ extraArtifacts[key] = Buffer.from(extraArtifacts[key], encoding);

* Assert that a given artifact content is of type `Buffer` and throw otherwise.
* @param {object} object
* @param {string} field
* @param {string} what
*/

@@ -185,5 +165,2 @@ function assertBuffer(object, field, what) {

* Assert that a given artifact content is of type `string` and throw otherwise.
* @param {object} object
* @param {string} field
* @param {string} what
*/

@@ -199,17 +176,11 @@ function assertString(object, field, what) {

}
/**
*
* @param {PkgDesc} srcPkg
* @param {PkgDesc} destPkg
* @param {object} context
*/
function writeLoadersResult(srcPkg, destPkg, context) {
if (context.content != undefined) {
writeRuleFile(destPkg, srcPkg.dir.relative(project_1.default.dir.join(context.filePath)).asNative, context.content);
writeRuleFile(destPkg, srcPkg.dir.relative(globals_1.project.dir.join(context.filePath)).asNative, context.content);
}
Object.entries(context.extraArtifacts).forEach(([extraPrjRelPath, content]) => {
if (content == undefined) {
if (content === undefined) {
return;
}
writeRuleFile(destPkg, srcPkg.dir.relative(project_1.default.dir.join(extraPrjRelPath)).asNative, content);
writeRuleFile(destPkg, srcPkg.dir.relative(globals_1.project.dir.join(extraPrjRelPath)).asNative, content);
context.log.info('liferay-npm-bundler', `Rules generated extra artifact: ${extraPrjRelPath}`);

@@ -220,5 +191,2 @@ });

* Write a file generated by a rule for a given destination package.
* @param {PkgDesc} destPkg
* @param {string} pkgRelPath
* @param {string} content
*/

@@ -229,3 +197,3 @@ function writeRuleFile(destPkg, pkgRelPath, content) {

}
const fileAbsPath = project_1.default.dir.join(destPkg.dir, pkgRelPath).asNative;
const fileAbsPath = globals_1.project.dir.join(destPkg.dir, pkgRelPath).asNative;
fs_extra_1.default.ensureDirSync(path_1.default.dirname(fileAbsPath));

@@ -236,7 +204,6 @@ fs_extra_1.default.writeFileSync(fileAbsPath, content);

* String configured source prefixes from package file path.
* @param {string} pkgRelPath
*/
function stripSourceDir(pkgRelPath) {
pkgRelPath = `.${path_1.default.sep}${pkgRelPath}`;
for (const sourcePath of project_1.default.sources.map(source => source.asNative)) {
for (const sourcePath of globals_1.project.sources.map((source) => source.asNative)) {
const prefixPath = `${sourcePath}${path_1.default.sep}`;

@@ -243,0 +210,0 @@ if (pkgRelPath.startsWith(prefixPath)) {

{
"name": "liferay-npm-bundler",
"version": "2.18.5",
"version": "3.0.0-alpha.1",
"description": "A CLI utility to bundle NPM dependencies of a Liferay OSGi bundle.",
"license": "LGPL-3.0",
"main": "lib/index.js",

@@ -10,30 +11,34 @@ "bin": {

"scripts": {
"build": "tsc && yarn copyfiles",
"ci": "cd ../.. && yarn ci",
"clean": "node ../../scripts/clean.js",
"copyfiles": "node ../../scripts/copyfiles.js",
"build": "tsc && yarn copyfiles",
"prepublish": "yarn build"
"postversion": "npx liferay-js-publish",
"preversion": "yarn ci"
},
"devDependencies": {
"liferay-npm-bundler-preset-liferay-dev": "1.12.0"
"@types/ejs": "^3.0.1",
"@types/escodegen": "^0.0.6",
"@types/estraverse": "^0.0.6",
"@types/estree": "^0.0.42",
"@types/fs-extra": "^8.1.0",
"@types/webpack": "^4.41.6"
},
"dependencies": {
"babel-core": "^6.26.3",
"clone": "^2.1.2",
"data-urls": "^1.1.0",
"dot-prop": "^5.0.1",
"acorn": "^6.2.1",
"cross-spawn": "^7.0.0",
"ejs": "^2.6.1",
"escodegen": "^1.14.1",
"estraverse": "^4.3.0",
"fs-extra": "^8.1.0",
"globby": "^10.0.1",
"insight": "0.10.3",
"jszip": "^3.1.5",
"liferay-npm-build-tools-common": "2.18.5",
"liferay-npm-bundler-preset-standard": "2.18.5",
"merge": "^1.2.1",
"liferay-js-toolkit-core": "3.0.0-alpha.1",
"pretty-time": "^1.1.0",
"read-json-sync": "^2.0.1",
"resolve": "^1.8.1",
"rimraf": "^3.0.0",
"semver": "^6.3.0",
"source-map": "^0.7.3",
"webpack": "^4.41.6",
"xml-js": "^1.6.8",
"yargs": "^14.0.0"
},
"gitHead": "42b661cdef42808ef63cb684b4b59185bfa0325c"
}
}
/**
* © 2017 Liferay, Inc. <https://liferay.com>
*
* SPDX-FileCopyrightText: © 2020 Liferay, Inc. <https://liferay.com>
* SPDX-License-Identifier: LGPL-3.0-or-later

@@ -8,149 +7,112 @@ */

import fs from 'fs-extra';
import project from 'liferay-npm-build-tools-common/lib/project';
import path from 'path';
import {PkgDesc, ProjectType} from 'liferay-js-toolkit-core';
import pretty from 'pretty-time';
import readJsonSync from 'read-json-sync';
import semver from 'semver';
import {addPackageDependencies, getRootPkg} from './dependencies';
import * as insight from './insight';
import {buildBundlerDir, manifest, project} from './globals';
import createJar from './jar';
import * as log from './log';
import manifest from './manifest';
import report from './report';
import copyPackages from './steps/copy';
import adaptAngularCli from './steps/adapt/angular-cli';
import adaptCreateReactApp from './steps/adapt/create-react-app';
import bundle from './steps/bundle';
import runRules from './steps/rules';
import transformPackages from './steps/transform';
import {abort} from './util';
/** Default entry point for the liferay-npm-bundler */
export default function(argv: {version: boolean}): void {
const versionsInfo = project.versionsInfo;
export default async function (argv: {version: boolean}): Promise<void> {
if (argv.version) {
const {versionsInfo} = project;
if (argv.version) {
versionsInfo.forEach((value, key) => {
// eslint-disable-next-line no-console
console.log(`"${key}":`, JSON.stringify(value, null, 2));
});
return;
}
report.versionsInfo(versionsInfo);
try {
const {pkgJson, versionsInfo} = project;
const rootPkg = new PkgDesc(pkgJson.name, pkgJson.version);
if (project.misc.noTracking) {
run();
} else {
log.debug(
'The tool is sending usage statistics to our remote servers.'
);
insight.init().then(run);
}
}
/** Real tool execution */
function run(): void {
try {
const start = process.hrtime();
// Get root package
const rootPkg = getRootPkg();
// Report configurations
report.rootPackage(rootPkg);
report.rulesConfig(project.rules.config);
report.versionsInfo(versionsInfo);
// Compute dependency packages
const depPkgsMap = addPackageDependencies(
{},
project.dir.asNative,
project.copy.includedDependencies
);
// Initialize package.json and manifest.json files
copyPackageJson();
addRootPackageToManifest(rootPkg);
const depPkgs = Object.values(depPkgsMap).filter(pkg => !pkg.isRoot);
// Run main process
switch (project.probe.type) {
case ProjectType.ANGULAR_CLI:
await adaptAngularCli();
break;
report.dependencies(depPkgs);
reportLinkedDependencies(project.pkgJson);
case ProjectType.BUNDLER:
await bundle();
await runRules(rootPkg);
break;
// Report rules config
report.rulesConfig(project.rules.config);
case ProjectType.CREATE_REACT_APP:
await adaptCreateReactApp();
break;
// Warn about incremental builds
if (manifest.loadedFromFile) {
report.warn(
'This report is from an incremental build: some steps may be ' +
'missing (you may remove the output directory to force a ' +
'full build).'
);
default:
abort(
`Unsupported project type '${project.probe.type}': cannot run liferay-npm-bundler`
);
}
// Do things
copyPackages(rootPkg, depPkgs)
.then(() => runRules(rootPkg, depPkgs))
.then(() => transformPackages(rootPkg, depPkgs))
.then(() => manifest.save())
.then(() => (project.jar.supported ? createJar() : undefined))
.then(() => {
// Report and show execution time
const hrtime = process.hrtime(start);
report.executionTime(hrtime);
log.info(`Bundling took ${pretty(hrtime)}`);
// Write manifest
saveManifest();
// Send report analytics data
report.sendAnalytics();
// Create final JAR
if (project.jar.supported) {
await createJar();
}
// Write report if requested
if (project.misc.reportFile) {
fs.writeFileSync(
project.misc.reportFile.asNative,
report.toHtml()
);
// Report and show execution time
const hrtime = process.hrtime(start);
report.executionTime(hrtime);
log.success(`Bundled {${pkgJson.name}} in`, pretty(hrtime));
log.info(
`Report written to ${project.misc.reportFile.asNative}`
);
} else if (report.warningsPresent) {
log.debug('The build has emitted some warning messages.');
}
})
.catch(abort);
// Write report if requested
if (project.misc.reportFile) {
fs.writeFileSync(project.misc.reportFile.asNative, report.toHtml());
log.info(`Report written to ${project.misc.reportFile.asNative}`);
} else if (report.warningsPresent) {
log.debug('The build has emitted some warning messages.');
}
} catch (err) {
abort(err);
log.error(`\n\n${err.stack}\n\n`);
process.exit(1);
}
}
/** Report linked dependencies of a given package.json */
function reportLinkedDependencies(pkgJson: object): void {
['dependencies', 'devDependencies'].forEach(scope => {
if (pkgJson[scope] != null) {
Object.keys(pkgJson[scope]).forEach(depName => {
const depVersion = pkgJson[scope][depName];
function addRootPackageToManifest(rootPkg: PkgDesc): void {
manifest.addPackage(
rootPkg,
rootPkg.clone({dir: buildBundlerDir.asNative})
);
}
if (semver.validRange(depVersion) == null) {
const depPkgJsonPath = path.join(
'node_modules',
depName,
'package.json'
);
function copyPackageJson(): void {
fs.copyFileSync(
project.dir.join('package.json').asNative,
buildBundlerDir.join('package.json').asNative
);
const depPkgJson = readJsonSync(depPkgJsonPath);
pkgJson[scope][depName] = depPkgJson.version;
report.linkedDependency(
depName,
depVersion,
depPkgJson.version
);
}
});
}
});
log.debug('Copied package.json to output directory');
}
/** Abort execution after showing error message */
function abort(err: any): void {
log.error(`
function saveManifest(): void {
manifest.save(buildBundlerDir.join('manifest.json').asNative);
${err.stack}
`);
process.exit(1);
log.debug('Wrote manifest.json to output directory');
}

@@ -5,4 +5,4 @@ {

{
"dataType": "integer",
"type": "numeric",
"dataType": "number",
"type": "ddm-number",
"name": "a-number",

@@ -21,3 +21,3 @@ "label": {

"dataType": "double",
"type": "numeric",
"type": "ddm-decimal",
"name": "a-float",

@@ -24,0 +24,0 @@ "label": {

@@ -5,4 +5,4 @@ {

{
"dataType": "integer",
"type": "numeric",
"dataType": "number",
"type": "ddm-number",
"name": "a-number",

@@ -9,0 +9,0 @@ "label": {

{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "./lib"
"outDir": "./lib",
"rootDir": "./src"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/__tests__/**"]
"include": ["**/*"],
"references": [{"path": "../liferay-js-toolkit-core"}]
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc