import { assert } from "../../../assert.js";

/**
 * Escapes special characters in a string for use in a GraphViz label.
 *
 * This function handles the most common escaping requirements for standard
 * string labels (i.e., label="..."). It ensures that literal backslashes,
 * double quotes, and newlines in the input string are correctly represented
 * in the final DOT language output.
 *
 * @param {string} input The raw string to be escaped.
 * @returns {string} The escaped string, safe to be used within double quotes in a .dot file.
 * @see https://graphviz.org/docs/attr-types/escString/
 */
export function graphviz_escape_string(input) {
    assert.isString(input, 'input');

    return input
        .replace(/([|{}\\])/g, '\\$1') // escape special characters
        .replace(/"/g, '\\"')   // 2. Escape double quotes
        .replace(/\n/g, '\\n');  // 3. Convert newlines to the \n sequence for centered lines
}