UNPKG

cmrd

Version:

A tiny utility for building command-line strings with clean and simple syntax.

76 lines (73 loc) 2.35 kB
var import_node_module = require("node:module"); var __defProp = Object.defineProperty; var __getOwnPropNames = Object.getOwnPropertyNames; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __hasOwnProp = Object.prototype.hasOwnProperty; var __moduleCache = /* @__PURE__ */ new WeakMap; var __toCommonJS = (from) => { var entry = __moduleCache.get(from), desc; if (entry) return entry; entry = __defProp({}, "__esModule", { value: true }); if (from && typeof from === "object" || typeof from === "function") __getOwnPropNames(from).map((key) => !__hasOwnProp.call(entry, key) && __defProp(entry, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable })); __moduleCache.set(from, entry); return entry; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true, configurable: true, set: (newValue) => all[name] = () => newValue }); }; // src/index.ts var exports_src = {}; __export(exports_src, { default: () => cmrd_default, cmrd: () => cmrd }); module.exports = __toCommonJS(exports_src); // src/cmrd.ts function getMaxArgPlaceholder(expressions) { return Math.max(...expressions.filter((exp) => typeof exp === "number")); } function isNil(value) { return value == null; } function isCmdArgIndex(exp) { return typeof exp === "number"; } function isCmdIf(exp) { return Array.isArray(exp) && exp.length === 2 && isCmdArgIndex(exp[0]) && typeof exp[1] === "string"; } function cmrd(strings, ...exprs) { const highestArgKey = getMaxArgPlaceholder(exprs); return (...args) => { const getExprValue = (expr) => { if (isNil(expr)) return ""; if (isCmdArgIndex(expr)) return args[expr] || ""; if (isCmdIf(expr)) return args[expr[0]] == null ? "" : expr[1]; return expr; }; const parsedCmd = strings.reduce((acc, str, i) => { const arg = getExprValue(exprs[i])?.trim(); const part = `${str}${arg}`; if (acc.endsWith(" ") && part.startsWith(" ")) { return `${acc}${part.trimStart()}`; } return `${acc}${part}`; }, ""); const extraArgs = args.slice(highestArgKey + 1).join(" "); return `${parsedCmd} ${extraArgs}`.trim(); }; } var cmrd_default = cmrd;