@visulima/string
Version:
Functions for manipulating strings.
72 lines (69 loc) • 2.97 kB
JavaScript
import { format, stripVTControlCharacters } from 'node:util';
import { getStringWidth } from '../get-string-width.mjs';
var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
const formatAnsiString = /* @__PURE__ */ __name((ansiString) => {
const stripped = stripVTControlCharacters(ansiString);
return {
// Original ANSI string
ansi: ansiString,
// JSON stringified version to see all escape codes
json: JSON.stringify(ansiString),
// Length difference between ANSI and stripped string
lengthDifference: ansiString.length - stripped.length,
// String with ANSI codes stripped
stripped,
// String with ANSI escape codes shown as visible characters
visible: ansiString.replaceAll("\x1B", "\\u001B")
};
}, "formatAnsiString");
const expectAnsiStrings = /* @__PURE__ */ __name((actual, expected) => {
const actualFormatted = formatAnsiString(actual);
const expectedFormatted = formatAnsiString(expected);
return {
message: /* @__PURE__ */ __name(() => {
if (actual === expected) {
return "ANSI strings are identical";
}
const strippedEqual = actualFormatted.stripped === expectedFormatted.stripped;
return format(
"ANSI string comparison failed:\n\nActual:\n - Visible content: %s\n - With escape codes: %s\n - JSON: %s\n - Length: %d\n\nExpected:\n - Visible content: %s\n - With escape codes: %s\n - JSON: %s\n - Length: %d\n\n%s\n",
actualFormatted.stripped,
actualFormatted.visible,
actualFormatted.json,
getStringWidth(actualFormatted.ansi),
expectedFormatted.stripped,
expectedFormatted.visible,
expectedFormatted.json,
getStringWidth(expectedFormatted.ansi),
strippedEqual ? "✓ Visible content is identical, but escape codes differ" : "✗ Visible content differs"
);
}, "message"),
pass: actual === expected
};
}, "expectAnsiStrings");
const compareAnsiStrings = /* @__PURE__ */ __name((actual, expected) => {
const actualFormatted = formatAnsiString(actual);
const expectedFormatted = formatAnsiString(expected);
const strippedEqual = actualFormatted.stripped === expectedFormatted.stripped;
const ansiEqual = actual === expected;
return {
// Format information for both strings
actual: actualFormatted,
// Are the strings identical including ANSI codes?
ansiEqual,
expected: expectedFormatted,
// Are the strings identical when ANSI codes are stripped?
strippedEqual,
// Summary information
summary: {
actualLength: actual.length,
actualStrippedLength: actualFormatted.stripped.length,
ansiEqual,
expectedLength: expected.length,
expectedStrippedLength: expectedFormatted.stripped.length,
strippedEqual
}
};
}, "compareAnsiStrings");
export { compareAnsiStrings, expectAnsiStrings, formatAnsiString };