UNPKG

@nuxt/cli

Version:
279 lines (278 loc) • 9.84 kB
import process from "node:process"; import { styleText } from "node:util"; import { supportsHyperlinks } from "clickable-path"; // src/utils/formatting.ts /** Render `label` as an OSC 8 link to `url`, where `clickable-path` reports support. */ function terminalLink(label, url, options = {}) { if (!supportsHyperlinks(options.stream ?? process.stdout)) return label; return `\u001B]8;;${url}\u0007${label}\u001B]8;;\u0007`; } const ANSI_RE = /\u001B\[[0-9;]*m|\u001B\]8;[^\u0007]*\u0007/g; const ANSI_AT_RE = new RegExp(ANSI_RE.source, "y"); const CONTROL_RE = /[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g; const NARROW_RE = /^[\u0000-\u02FF\u2010-\u2027\u2500-\u257F\u2800-\u28FF]*$/; let widthPatterns; function getWidthPatterns() { return widthPatterns ??= { zero: new RegExp(String.raw`[\p{Mn}\p{Me}\u200B-\u200F]`, "u"), wide: new RegExp(String.raw`[\p{Emoji_Presentation}\u1100-\u115F\u2E80-\u303E\u3041-\u33FF\u3400-\u4DBF\u4E00-\u9FFF\uA000-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6\u{20000}-\u{3FFFD}]`, "u") }; } /** Strip colour and hyperlink escapes. */ function stripAnsi(text) { return text.replace(ANSI_RE, ""); } /** Strip every control character but tab and newline, so no escape sequence survives in text from outside the CLI. */ function stripControlChars(text) { return text.replace(CONTROL_RE, ""); } function charWidth(char) { const { zero, wide } = getWidthPatterns(); if (zero.test(char)) return 0; return wide.test(char) ? 2 : 1; } /** Terminal columns `text` occupies. */ function visibleWidth(text) { const stripped = stripAnsi(text); if (NARROW_RE.test(stripped)) return stripped.length; let width = 0; for (const char of stripped) width += charWidth(char); return width; } const LINK_TERMINATOR = "\x1B]8;;\x07"; /** Cut `text` to `columns` with an ellipsis, closing any styling or link it cuts through. */ function truncate(text, columns) { if (columns <= 0) return ""; if (visibleWidth(text) <= columns) return text; const limit = columns - 1; let visible = 0; let index = 0; let styled = false; let linked = false; ANSI_RE.lastIndex = 0; while (index < text.length && visible < limit) { ANSI_RE.lastIndex = index; const match = ANSI_RE.exec(text); if (match?.index === index) { if (match[0].startsWith("\x1B]8;")) linked = match[0] !== LINK_TERMINATOR; else styled = true; index += match[0].length; continue; } const code = text.codePointAt(index); const char = code < 768 ? text[index] : String.fromCodePoint(code); const width = code < 768 ? 1 : charWidth(char); if (visible + width > limit) break; index += char.length; visible += width; } return `${text.slice(0, index)}\u2026${linked ? LINK_TERMINATOR : ""}${styled ? "\x1B[0m" : ""}`; } /** * Wrap each line of `text` to `columns`, breaking at spaces where possible. * Continuation rows keep the line's own indentation, and styling or a link * that spans a break is closed at the end of the row and reopened on the next. */ function wrapText(text, columns) { const width = Math.max(1, columns); return text.split("\n").flatMap((line) => wrapLine(line, width)); } function atomise(line) { const atoms = []; let index = 0; while (index < line.length) { ANSI_AT_RE.lastIndex = index; const match = ANSI_AT_RE.exec(line); if (match) { atoms.push({ text: match[0] }); index += match[0].length; continue; } const char = String.fromCodePoint(line.codePointAt(index)); atoms.push({ text: char, width: char.charCodeAt(0) < 768 ? 1 : charWidth(char) }); index += char.length; } return atoms; } const SGR_ON = { 1: "bold", 2: "dim", 3: "italic", 4: "underline", 5: "blink", 7: "inverse", 8: "hidden", 9: "strike" }; const SGR_OFF = { 22: ["bold", "dim"], 23: ["italic"], 24: ["underline"], 25: ["blink"], 27: ["inverse"], 28: ["hidden"], 29: ["strike"], 39: ["fg"], 49: ["bg"] }; /** The attributes still active after `sequence`, keyed by what each one sets. */ function applySgr(state, sequence) { const params = sequence.slice(2, -1).split(";").map((param) => Number(param || 0)); const next = new Map(state); for (let index = 0; index < params.length; index++) { const code = params[index]; if (code === 0) next.clear(); else if (SGR_ON[code]) next.set(SGR_ON[code], String(code)); else if (SGR_OFF[code]) SGR_OFF[code].forEach((slot) => next.delete(slot)); else if (code >= 30 && code <= 37 || code >= 90 && code <= 97) next.set("fg", String(code)); else if (code >= 40 && code <= 47 || code >= 100 && code <= 107) next.set("bg", String(code)); else if ((code === 38 || code === 48) && (params[index + 1] === 5 || params[index + 1] === 2)) { const length = params[index + 1] === 5 ? 3 : 5; next.set(code === 38 ? "fg" : "bg", params.slice(index, index + length).join(";")); index += length - 1; } else next.set(`other:${code}`, String(code)); } return next; } function wrapLine(line, columns) { if (visibleWidth(line) <= columns) return [line]; const leading = /^\s*/.exec(stripAnsi(line))[0].length; const hanging = " ".repeat(leading < columns / 2 ? leading : 0); const rows = []; let sgr = /* @__PURE__ */ new Map(); let link; let row = ""; let used = 0; /** The row holds something other than spaces, so breaking it makes progress. */ let worded = false; /** Where the row can be broken at its last space, and the state to resume with. */ let breakpoint; const atoms = atomise(line); const closing = (state) => `${state.link ? LINK_TERMINATOR : ""}${state.sgr.size ? "\x1B[0m" : ""}`; const reopen = (state) => `${hanging}${state.sgr.size ? `\u001B[${[...state.sgr.values()].join(";")}m` : ""}${state.link ?? ""}`; for (let index = 0; index < atoms.length; index++) { const atom = atoms[index]; if (atom.width === void 0) { if (atom.text.startsWith("\x1B]8;")) link = atom.text === LINK_TERMINATOR ? void 0 : atom.text; else sgr = applySgr(sgr, atom.text); row += atom.text; continue; } if (used + atom.width > columns && used > hanging.length) { if (atom.text !== " " && breakpoint && breakpoint.used > hanging.length) { const state = { sgr: breakpoint.sgr, link: breakpoint.link }; rows.push(row.slice(0, breakpoint.at).trimEnd() + closing(state)); row = reopen(state); used = hanging.length; worded = false; sgr = state.sgr; link = state.link; index = breakpoint.atom; breakpoint = void 0; continue; } rows.push(row.trimEnd() + closing({ sgr, link })); row = reopen({ sgr, link }); used = hanging.length; worded = false; breakpoint = void 0; if (atom.text === " ") continue; } row += atom.text; used += atom.width; if (atom.text !== " ") worded = true; else if (worded) breakpoint = { at: row.length, used, atom: index, sgr, link }; } rows.push(row); return rows; } /** Lower-case a leading capital, leaving acronyms alone. */ function decapitalise(text) { return /^[A-Z][a-z]/.test(text) ? text[0].toLowerCase() + text.slice(1) : text; } /** Format milliseconds with fixed precision per unit (`4.2ms`, `420ms`, `4.20s`, `42.0s`, `4m 02s`, `1h 04m 02s`). */ function formatDuration(ms) { ms = Math.max(0, ms); if (ms < 10) return `${ms.toFixed(1)}ms`; if (ms < 1e3) return `${Math.round(ms)}ms`; if (ms < 1e4) return `${(Math.floor(ms / 10) / 100).toFixed(2)}s`; if (ms < 6e4) return `${(Math.floor(ms / 100) / 10).toFixed(1)}s`; const total = Math.floor(ms / 1e3); const hours = Math.floor(total / 3600); const minutes = Math.floor(total % 3600 / 60); const seconds = String(total % 60).padStart(2, "0"); return hours ? `${hours}h ${String(minutes).padStart(2, "0")}m ${seconds}s` : `${minutes}m ${seconds}s`; } const BYTE_UNITS = [ "B", "kB", "MB", "GB" ]; /** Format a byte count in decimal units, as Vite and Nitro report sizes (`812 B`, `4.36 kB`, `2.45 MB`). */ function formatBytes(bytes) { let value = Math.max(0, bytes); let unit = 0; while (value >= 1e3 && unit < BYTE_UNITS.length - 1) { value /= 1e3; unit++; } return unit === 0 ? `${value} B` : `${value.toFixed(2)} ${BYTE_UNITS[unit]}`; } const AT_MENTION_RE = /\b@([^, ]+)/g; const BACKTICK_RE = /`([^`]*)`/g; function formatInfoBox(infoObj) { let firstColumnLength = 0; let ansiFirstColumnLength = 0; const entries = Object.entries(infoObj).map(([label, val]) => { if (label.length > firstColumnLength) { ansiFirstColumnLength = styleText(["bold", "whiteBright"], label).length + 6; firstColumnLength = label.length + 6; } return [label, val || "-"]; }); const terminalWidth = Math.max(process.stdout.columns || 80, firstColumnLength) - 8; let boxStr = ""; for (const [label, value] of entries) { const formattedValue = value.replace(AT_MENTION_RE, (_, r) => styleText("gray", ` ${r}`)).replace(BACKTICK_RE, (_, r) => r); boxStr += styleText(["bold", "whiteBright"], label).padEnd(ansiFirstColumnLength); let boxRowLength = firstColumnLength; const words = formattedValue.split(" "); let currentLine = ""; for (const word of words) { const wordLength = visibleWidth(word); const spaceLength = currentLine ? 1 : 0; if (boxRowLength + wordLength + spaceLength > terminalWidth) { if (currentLine) boxStr += styleText("cyan", currentLine); boxStr += `\n${" ".repeat(firstColumnLength)}`; currentLine = word; boxRowLength = firstColumnLength + wordLength; } else { currentLine += (currentLine ? " " : "") + word; boxRowLength += wordLength + spaceLength; } } if (currentLine) boxStr += styleText("cyan", currentLine); boxStr += "\n"; } return boxStr; } export { stripAnsi as a, truncate as c, formatInfoBox as i, visibleWidth as l, formatBytes as n, stripControlChars as o, formatDuration as r, terminalLink as s, decapitalise as t, wrapText as u };