plugin-preloader
Version:
This library dynamically preloads and installs Babel and ESLint plugins and presets based on your configuration, streamlining the build process without the need to include them as dependencies in your project.
518 lines (501 loc) • 16.8 kB
JavaScript
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined")
return require.apply(this, arguments);
throw new Error('Dynamic require of "' + x + '" is not supported');
});
var __commonJS = (cb, mod) => function __require2() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __async = (__this, __arguments, generator) => {
return new Promise((resolve2, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve2(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// node_modules/color-support/index.js
var require_color_support = __commonJS({
"node_modules/color-support/index.js"(exports, module) {
module.exports = colorSupport({ alwaysReturn: true }, colorSupport);
function hasNone(obj, options) {
obj.level = 0;
obj.hasBasic = false;
obj.has256 = false;
obj.has16m = false;
if (!options.alwaysReturn) {
return false;
}
return obj;
}
function hasBasic(obj) {
obj.hasBasic = true;
obj.has256 = false;
obj.has16m = false;
obj.level = 1;
return obj;
}
function has256(obj) {
obj.hasBasic = true;
obj.has256 = true;
obj.has16m = false;
obj.level = 2;
return obj;
}
function has16m(obj) {
obj.hasBasic = true;
obj.has256 = true;
obj.has16m = true;
obj.level = 3;
return obj;
}
function colorSupport(options, obj) {
options = options || {};
obj = obj || {};
if (typeof options.level === "number") {
switch (options.level) {
case 0:
return hasNone(obj, options);
case 1:
return hasBasic(obj);
case 2:
return has256(obj);
case 3:
return has16m(obj);
}
}
obj.level = 0;
obj.hasBasic = false;
obj.has256 = false;
obj.has16m = false;
if (typeof process === "undefined" || !process || !process.stdout || !process.env || !process.platform) {
return hasNone(obj, options);
}
var env = options.env || process.env;
var stream = options.stream || process.stdout;
var term = options.term || env.TERM || "";
var platform = options.platform || process.platform;
if (!options.ignoreTTY && !stream.isTTY) {
return hasNone(obj, options);
}
if (!options.ignoreDumb && term === "dumb" && !env.COLORTERM) {
return hasNone(obj, options);
}
if (platform === "win32") {
return hasBasic(obj);
}
if (env.TMUX) {
return has256(obj);
}
if (!options.ignoreCI && (env.CI || env.TEAMCITY_VERSION)) {
if (env.TRAVIS) {
return has256(obj);
} else {
return hasNone(obj, options);
}
}
switch (env.TERM_PROGRAM) {
case "iTerm.app":
var ver = env.TERM_PROGRAM_VERSION || "0.";
if (/^[0-2]\./.test(ver)) {
return has256(obj);
} else {
return has16m(obj);
}
case "HyperTerm":
case "Hyper":
return has16m(obj);
case "MacTerm":
return has16m(obj);
case "Apple_Terminal":
return has256(obj);
}
if (/^xterm-256/.test(term)) {
return has256(obj);
}
if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(term)) {
return hasBasic(obj);
}
if (env.COLORTERM) {
return hasBasic(obj);
}
return hasNone(obj, options);
}
}
});
// node_modules/fancy-log/index.js
var require_fancy_log = __commonJS({
"node_modules/fancy-log/index.js"(exports, module) {
"use strict";
var util = __require("util");
var Console = __require("console").Console;
var supportsColor = require_color_support();
var console = new Console({
stdout: process.stdout,
stderr: process.stderr,
colorMode: false
});
function hasFlag(flag) {
return process.argv.indexOf("--" + flag) !== -1;
}
function hasColors() {
if (hasFlag("no-color")) {
return false;
}
if (hasFlag("color")) {
return true;
}
if (supportsColor()) {
return true;
}
return false;
}
function Timestamp() {
this.now = /* @__PURE__ */ new Date();
}
Timestamp.prototype[util.inspect.custom] = function(depth, opts) {
var timestamp = this.now.toLocaleTimeString("en", { hour12: false });
return "[" + opts.stylize(timestamp, "date") + "]";
};
function getTimestamp() {
return util.inspect(new Timestamp(), { colors: hasColors() });
}
function log4() {
var time = getTimestamp();
process.stdout.write(time + " ");
console.log.apply(console, arguments);
return this;
}
function info() {
var time = getTimestamp();
process.stdout.write(time + " ");
console.info.apply(console, arguments);
return this;
}
function dir() {
var time = getTimestamp();
process.stdout.write(time + " ");
console.dir.apply(console, arguments);
return this;
}
function warn() {
var time = getTimestamp();
process.stderr.write(time + " ");
console.warn.apply(console, arguments);
return this;
}
function error() {
var time = getTimestamp();
process.stderr.write(time + " ");
console.error.apply(console, arguments);
return this;
}
module.exports = log4;
module.exports.info = info;
module.exports.dir = dir;
module.exports.warn = warn;
module.exports.error = error;
}
});
// src/maps/babel/index.ts
var babel_exports = {};
__export(babel_exports, {
plugins: () => plugins_default,
presets: () => presets_default
});
// src/maps/babel/plugins.ts
var plugins = {
"@babel/plugin-transform-typescript": {
nameInRegistry: "@babel/plugin-transform-typescript"
},
"@babel/plugin-proposal-decorators": {
nameInRegistry: "@babel/plugin-proposal-decorators"
},
"@babel/plugin-proposal-private-methods": {
nameInRegistry: "@babel/plugin-proposal-private-methods"
},
"@babel/plugin-transform-runtime": {
nameInRegistry: "@babel/plugin-transform-runtime"
},
"@babel/plugin-proposal-class-properties": {
nameInRegistry: "@babel/plugin-proposal-class-properties"
},
"@babel/plugin-proposal-export-namespace-from": {
nameInRegistry: "@babel/plugin-proposal-export-namespace-from"
},
"styled-components": {
nameInRegistry: "babel-plugin-styled-components"
}
};
var plugins_default = plugins;
// src/maps/babel/presets.ts
var presets = {
"@babel/preset-env": {
nameInRegistry: "@babel/preset-env"
},
"@babel/preset-react": {
nameInRegistry: "@babel/preset-react"
},
"@babel/preset-flow": {
nameInRegistry: "@babel/preset-flow"
}
};
var presets_default = presets;
// src/maps/eslint/index.ts
var eslint_exports = {};
__export(eslint_exports, {
extendsMap: () => extends_default,
parser: () => parser_default,
plugins: () => plugins_default2
});
// src/maps/eslint/parser.ts
var parser = {
"@typescript-eslint/parser": {
nameInRegistry: "@typescript-eslint/parser"
},
"babel-eslint": {
nameInRegistry: "babel-eslint"
},
"@babel/eslint-parser": {
nameInRegistry: "@babel/eslint-parser"
}
};
var parser_default = parser;
// src/maps/eslint/extends.ts
var extendsMap = {
"plugin:security/recommended": {
nameInRegistry: "eslint-plugin-security"
},
"plugin:security-rules/recommended": {
nameInRegistry: "eslint-plugin-security-rules"
},
"plugin:abcsize/recommended": {
nameInRegistry: "eslint-plugin-abcsize"
},
"plugin:sonarjs/recommended": {
nameInRegistry: "eslint-plugin-sonarjs"
},
"plugin:n/recommended": {
nameInRegistry: "eslint-plugin-n"
},
"plugin:@typescript-eslint/recommended": {
nameInRegistry: "@typescript-eslint/eslint-plugin"
},
airbnb: {
nameInRegistry: "eslint-config-airbnb"
},
prettier: {
nameInRegistry: "eslint-config-prettier"
},
"prettier/react": {
nameInRegistry: "eslint-config-prettier"
},
"plugin:prettier/recommended": {
nameInRegistry: "eslint-plugin-prettier"
},
"plugin:flowtype/recommended": {
nameInRegistry: "eslint-plugin-flowtype"
}
};
var extends_default = extendsMap;
// src/maps/eslint/plugins.ts
var plugins2 = {
abcsize: {
nameInRegistry: "eslint-plugin-abcsize"
},
flowtype: {
nameInRegistry: "eslint-plugin-flowtype"
},
"@typescript-eslint": {
nameInRegistry: "@typescript-eslint/eslint-plugin"
},
sonarjs: {
nameInRegistry: "eslint-plugin-sonarjs"
}
};
var plugins_default2 = plugins2;
// src/getEntitiesMapWithVersions.ts
var import_fancy_log2 = __toESM(require_fancy_log());
import { resolve } from "path";
// src/utils/wrappers.ts
var wrappers_exports = {};
__export(wrappers_exports, {
asyncExec: () => asyncExec,
asyncExists: () => asyncExists,
syncExec: () => syncExec,
syncExists: () => syncExists
});
import { promisify } from "util";
import { exec, execSync as syncExec } from "child_process";
import { promises as fs, existsSync as syncExists } from "fs";
var asyncExec = promisify(exec);
var asyncExists = (path) => __async(void 0, null, function* () {
return !!(yield fs.stat(path).catch(() => false));
});
// src/utils/transform/index.ts
var transform_exports = {};
__export(transform_exports, {
babelConfig: () => babelConfig_default,
eslintConfig: () => eslintConfig_default
});
// src/utils/transform/babelConfig.ts
var import_fancy_log = __toESM(require_fancy_log());
function transformBabelConfig(config) {
const itemsToProcess = /* @__PURE__ */ new Map();
const { presets: presets2 = [], plugins: plugins3 = [], env = {} } = config;
const pluginsAndPresets = [
...Array.isArray(presets2) ? presets2 : [],
...Array.isArray(plugins3) ? plugins3 : []
];
Object.values(env).forEach((envConfig) => {
pluginsAndPresets.push(
...Array.isArray(envConfig.plugins) ? envConfig.plugins : [],
...Array.isArray(envConfig.presets) ? envConfig.presets : []
);
});
for (const pluginOrPreset of pluginsAndPresets) {
if (typeof pluginOrPreset === "string") {
if (!itemsToProcess.has(pluginOrPreset)) {
itemsToProcess.set(pluginOrPreset, pluginOrPreset);
}
} else if (Array.isArray(pluginOrPreset)) {
if (!itemsToProcess.has(pluginOrPreset[0])) {
itemsToProcess.set(
pluginOrPreset[0],
typeof pluginOrPreset[3] === "string" ? [pluginOrPreset[0], pluginOrPreset[3]] : pluginOrPreset[0]
);
}
} else {
import_fancy_log.default.error("This type of declaring the plugin is not supported yet");
}
}
return [...itemsToProcess.values()];
}
var babelConfig_default = transformBabelConfig;
// src/utils/transform/eslintConfig.ts
function transformEslintConfig(config) {
const { plugins: plugins3, parser: parser2, extends: extendsItems } = config;
const extendsArr = Array.isArray(extendsItems) ? extendsItems : typeof extendsItems === "string" ? [extendsItems] : [];
const pluginsArr = Array.isArray(plugins3) ? plugins3 : [];
const parserArr = parser2 ? [parser2] : [];
return [...extendsArr, ...pluginsArr, ...parserArr];
}
var eslintConfig_default = transformEslintConfig;
// src/getEntitiesMapWithVersions.ts
function getEntitiesMapWithVersions(entities, entitiesMap) {
const mapWithVersions = {};
for (const entity of entities) {
const name = Array.isArray(entity) ? entity[0] : entity;
try {
const { nameInRegistry } = entitiesMap[name];
mapWithVersions[name] = {
nameInRegistry,
desiredVersion: Array.isArray(entity) ? entity[1] : "latest"
};
const currentDir = process.cwd();
const packagePath = resolve(currentDir, "node_modules", nameInRegistry);
const packageIsInstalled = wrappers_exports.syncExists(packagePath);
if (packageIsInstalled) {
const { version } = __require(packagePath + "/package.json");
mapWithVersions[name].currentVersion = version;
if (mapWithVersions[name].desiredVersion === "latest") {
const command = `npm view ${nameInRegistry} version`;
const remoteVersion = wrappers_exports.syncExec(command, { encoding: "utf8" });
mapWithVersions[name].desiredVersion = remoteVersion.trim();
}
}
} catch (e) {
delete mapWithVersions[name];
import_fancy_log2.default.error(`Plugin ${name} is not handled yet.`);
}
}
return mapWithVersions;
}
var getEntitiesMapWithVersions_default = getEntitiesMapWithVersions;
// src/index.ts
var import_fancy_log3 = __toESM(require_fancy_log());
function preload({ babel, eslint }) {
const checkedEntities = [];
if (babel) {
const pluginsAndPresets = transform_exports.babelConfig(babel);
const pluginsAndPresetsMap = getEntitiesMapWithVersions_default(pluginsAndPresets, __spreadValues(__spreadValues({}, babel_exports.plugins), babel_exports.presets));
checkedEntities.push(...Object.values(pluginsAndPresetsMap));
}
if (eslint) {
const pluginsExtendsAndParser = transform_exports.eslintConfig(eslint);
const pluginsExtendsAndParserMap = getEntitiesMapWithVersions_default(pluginsExtendsAndParser, __spreadValues(__spreadValues(__spreadValues({}, eslint_exports.extendsMap), eslint_exports.parser), eslint_exports.plugins));
checkedEntities.push(...Object.values(pluginsExtendsAndParserMap));
}
if (checkedEntities.length) {
(0, import_fancy_log3.default)("Packages to install:");
} else {
(0, import_fancy_log3.default)("No packages need to be installed");
return;
}
const packagesToInstall = checkedEntities.reduce((acc, { nameInRegistry, desiredVersion }) => {
const packageWithVersion = `${nameInRegistry}@${desiredVersion}`;
(0, import_fancy_log3.default)(`- ${packageWithVersion}`);
return acc + `${packageWithVersion} `;
}, "");
const command = `npm install ${packagesToInstall.trim()} --no-save --no-audit`;
const output = wrappers_exports.syncExec(command, { encoding: "utf8" });
(0, import_fancy_log3.default)(output.trim());
}
var src_default = preload;
export {
src_default as default
};