@ai2070/l0
Version:
L0: The Missing Reliability Substrate for AI
130 lines • 3.61 kB
JavaScript
export function trim(str) {
if (!str)
return str;
return str.trim();
}
export function escape(str) {
if (!str)
return str;
return str
.replace(/\\/g, "\\\\")
.replace(/"/g, '\\"')
.replace(/'/g, "\\'")
.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r")
.replace(/\t/g, "\\t");
}
export function unescape(str) {
if (!str)
return str;
const BACKSLASH_PLACEHOLDER = "\x00BACKSLASH\x00";
return str
.replace(/\\\\/g, BACKSLASH_PLACEHOLDER)
.replace(/\\t/g, "\t")
.replace(/\\r/g, "\r")
.replace(/\\n/g, "\n")
.replace(/\\'/g, "'")
.replace(/\\"/g, '"')
.replace(new RegExp(BACKSLASH_PLACEHOLDER, "g"), "\\");
}
export function escapeHtml(str) {
if (!str)
return str;
const entities = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
};
return str.replace(/[&<>"']/g, (char) => entities[char] || char);
}
export function unescapeHtml(str) {
if (!str)
return str;
const entities = {
"&": "&",
"<": "<",
">": ">",
""": '"',
"'": "'",
"'": "'",
};
return str.replace(/&(?:amp|lt|gt|quot|#39|#x27);/g, (entity) => entities[entity] || entity);
}
export function escapeRegex(str) {
if (!str)
return str;
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
export function sanitize(str) {
if (!str)
return str;
return str.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, "");
}
export function truncate(str, maxLength, suffix = "...") {
if (!str || str.length <= maxLength) {
return str;
}
const truncateAt = maxLength - suffix.length;
return str.slice(0, truncateAt) + suffix;
}
export function truncateWords(str, maxLength, suffix = "...") {
if (!str || str.length <= maxLength) {
return str;
}
const truncateAt = maxLength - suffix.length;
const truncated = str.slice(0, truncateAt);
const lastSpace = truncated.lastIndexOf(" ");
if (lastSpace > 0) {
return truncated.slice(0, lastSpace) + suffix;
}
return truncated + suffix;
}
export function wrap(str, width) {
if (!str)
return str;
const words = str.split(/\s+/);
const lines = [];
let currentLine = "";
for (const word of words) {
if (currentLine.length + word.length + 1 <= width) {
currentLine += (currentLine ? " " : "") + word;
}
else {
if (currentLine) {
lines.push(currentLine);
}
currentLine = word;
}
}
if (currentLine) {
lines.push(currentLine);
}
return lines.join("\n");
}
export function pad(str, length, char = " ", align = "left") {
if (!str)
str = "";
if (str.length >= length)
return str;
const padLength = length - str.length;
switch (align) {
case "right":
return char.repeat(padLength) + str;
case "center": {
const leftPad = Math.floor(padLength / 2);
const rightPad = padLength - leftPad;
return char.repeat(leftPad) + str + char.repeat(rightPad);
}
case "left":
default:
return str + char.repeat(padLength);
}
}
export function removeAnsi(str) {
if (!str)
return str;
return str.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, "");
}
//# sourceMappingURL=utils.js.map