UNPKG

rantail

Version:

The ultimate companion for Tailwind CSS. Write clean and secure code effortlessly. Protect your work from theft with Rantail. Encode your Tailwind classes with unique and customizable cuid's. Enjoy smooth, encoded, and theft-proof coding.

250 lines (241 loc) 8.06 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; 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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __async = (__this, __arguments, generator) => { return new Promise((resolve, 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 ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); step((generator = generator.apply(__this, __arguments)).next()); }); }; // src/cli.ts var cli_exports = {}; __export(cli_exports, { CLI: () => CLI }); module.exports = __toCommonJS(cli_exports); // src/logger.ts var Logger = class _Logger { /** * Generic error logger * @param text * @returns */ static error(...text) { return console.error(`\u274C`, `[rantail]`, ...text); } /** * Generic log * @param emoji * @param text */ static log(emoji, ...text) { return console.log(emoji, `[rantail]:`, ...text); } /** * Generic success logger * @param * @returns */ static generationCompleted() { _Logger.log(`\u2705`, "Generation completed"); } /** * Generic file process logger * @param * @returns */ static logFile(fileName) { _Logger.log(`\u2757`, `Processing File`, fileName); } /** * Generic config loader logger * @param * @returns */ static loadingConfig(path2) { _Logger.log(`\u2728`, `Loading Rantail config from `, path2); } static loadingCSS(path2) { _Logger.log(`\u2728`, `Loading main CSS file from `, path2); } }; // src/utils/merge.ts var import_lodash = __toESM(require("lodash")); var overwriteMerge = (...configs) => { return import_lodash.default.merge({}, ...configs); }; // src/utils/defaults.ts var defaultConfig = { content: [ "./pages/**/*.{js,jsx,ts,tsx}", "./components/**/*.{js,jsx,ts,tsx}", "./app/**/*.{js,jsx,ts,tsx}", "./src/**/*.{js,jsx,ts,tsx}" ], cuidLength: 12 }; var withDefaultConfig = (config) => { return overwriteMerge(defaultConfig, config); }; // src/utils/path.ts var import_node_path = __toESM(require("path")); var import_promises = __toESM(require("fs/promises")); var import_url = require("url"); var minimist = require("minimist"); var getPath = (...pathSegment) => { return import_node_path.default.resolve(process.cwd(), ...pathSegment); }; var getConfigFilePath = () => __async(void 0, null, function* () { const args = minimist(process.argv.slice(2)); const configPath = getPath(args.config || "rantail.config.js"); return import_promises.default.stat(configPath).then(() => (0, import_url.pathToFileURL)(configPath).toString()); }); var getCSSFilePath = (cssFilePath) => __async(void 0, null, function* () { if (!cssFilePath) { throw new Error("CSS File Path is not declared in the config File, continuing with unencoded code build."); } const fullCssFilePath = getPath(cssFilePath); Logger.loadingCSS(fullCssFilePath); return fullCssFilePath; }); // src/parsers/config-parser.ts var ConfigParser = class { /** * Load rantail.config.js as module * @returns */ loadBaseConfig() { return __async(this, null, function* () { const path2 = yield getConfigFilePath(); Logger.loadingConfig(path2); const baseConfig = yield import(path2); if (!(baseConfig == null ? void 0 : baseConfig.default)) { throw new Error("Unable to import rantail config file"); } return withDefaultConfig(baseConfig.default); }); } loadConfig() { return __async(this, null, function* () { const config = yield this.loadBaseConfig(); return { config }; }); } }; // src/cli.ts var import_node_fs = __toESM(require("fs")); var fg = __toESM(require("fast-glob")); // src/utils/cuid.ts var import_cuid2 = require("@paralleldrive/cuid2"); var generateCUID = (cuidLength, prefix, suffix) => { const cuid = (0, import_cuid2.init)({ length: cuidLength }); let generatedCuid = cuid(); if (prefix) { generatedCuid = prefix + generatedCuid; } if (suffix) { generatedCuid = generatedCuid + suffix; } return generatedCuid; }; // src/cli.ts var CLI = class { main() { return __async(this, null, function* () { var _a; const configParser = new ConfigParser(); const { config } = yield configParser.loadConfig(); let cssFilePath = yield getCSSFilePath(config.cssFilePath); import_node_fs.default.appendFileSync(cssFilePath, "\n"); const classNameRegex = /className=(['"])(.*?)\1|className={`([^`]*?)`}/g; let match; let replacements = {}; for (const pattern of config.content) { const files = fg.globSync(pattern); for (const file of files) { Logger.logFile(file); let jsxFileContent = import_node_fs.default.readFileSync(file, "utf8"); while ((match = classNameRegex.exec(jsxFileContent)) !== null) { const originalClassNames = (_a = match[2] || match[3]) == null ? void 0 : _a.replace(/`|'|"|{|}/g, "").split(" "); if (Array.isArray(originalClassNames)) { for (const originalClassName of originalClassNames) { if (!/^[a-z0-9-:\\[\]\\]+$/.test(originalClassName) || originalClassName.length < 3 || config.ignore && originalClassName.startsWith(config.ignore)) { continue; } if (!replacements[originalClassName]) { const randomClassName = generateCUID(config.cuidLength, config.prefix, config.suffix); replacements[originalClassName] = randomClassName; let cssContent = `.${randomClassName} { @apply ${originalClassName}; } `; import_node_fs.default.appendFileSync(cssFilePath, cssContent); } } } } for (let key in replacements) { let value = replacements[key]; let escapedKey = key.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); let regex = new RegExp(`(?<![a-z0-9-_])${escapedKey}(?![a-z0-9-_])`, "g"); jsxFileContent = jsxFileContent.replace(regex, value); } import_node_fs.default.writeFileSync(file, jsxFileContent); } } }); } /** * Execute and log result * @returns */ execute() { return __async(this, null, function* () { return this.main().then(Logger.generationCompleted).catch(Logger.error); }); } }; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { CLI }); //# sourceMappingURL=cli.js.map