import { cloneMessage, cloneMessageTerm, commandLine, createMessageFormatter, envVar, formatMessage, lineBreak, link, type Message, message, type MessageFormatOptions, type MessageTerm, metavar, optionName, optionNames, text, url, value, values, valueSet, } from "#src/message.ts"; import assert from "node:assert/strict"; import { describe, it } from "node:test"; import * as fc from "fast-check"; import { getDisplayWidth } from "#src/displaywidth.ts"; describe("message template function", () => { it("should create message with text only", () => { const msg = message`This is a simple message`; assert.ok(Array.isArray(msg)); assert.deepEqual(msg, [ { type: "text", text: "This is a simple message" }, ] as const); }); it("should create message with interpolated strings", () => { const val = "testValue"; const msg = message`Expected valid input, got ${val}`; assert.ok(Array.isArray(msg)); assert.deepEqual(msg, [ { type: "text", text: "Expected valid input, got " }, { type: "value", value: "testValue" }, ] as const); }); it("should create message with multiple interpolated values", () => { const min = "10"; const max = "100"; const actual = "150"; const msg = message`Value ${actual} is not between ${min} and ${max}`; assert.ok(Array.isArray(msg)); assert.deepEqual(msg, [ { type: "text", text: "Value " }, { type: "value", value: "150" }, { type: "text", text: " is not between " }, { type: "value", value: "10" }, { type: "text", text: " and " }, { type: "value", value: "100" }, ] as const); }); it("should handle MessageTerm objects in interpolation", () => { const optName = optionName("--port"); const msg = message`Option ${optName} is required`; assert.ok(Array.isArray(msg)); assert.deepEqual(msg, [ { type: "text", text: "Option " }, { type: "optionName", optionName: "--port" }, { type: "text", text: " is required" }, ] as const); }); it("should handle nested Message arrays", () => { const innerMessage = message`invalid value`; const msg = message`Parsing failed: ${innerMessage}`; assert.ok(Array.isArray(msg)); assert.deepEqual(msg, [ { type: "text", text: "Parsing failed: " }, { type: "text", text: "invalid value" }, ] as const); }); it("should create message with text ending (dot case)", () => { const expected = "42"; const actual = "invalid"; const msg = message`Expected ${expected}, got ${actual}.`; assert.ok(Array.isArray(msg)); assert.deepEqual(msg, [ { type: "text", text: "Expected " }, { type: "value", value: expected }, { type: "text", text: ", got " }, { type: "value", value: actual }, { type: "text", text: "." }, ] as const); }); it("should create message with range format", () => { const min = "1"; const max = "100"; const value = "150"; const msg = message`Value ${value} is out of range [${min}, ${max}]`; assert.ok(Array.isArray(msg)); assert.deepEqual(msg, [ { type: "text", text: "Value " }, { type: "value", value: "150" }, { type: "text", text: " is out of range [" }, { type: "value", value: "1" }, { type: "text", text: ", " }, { type: "value", value: "100" }, { type: "text", text: "]" }, ] as const); }); it("should clone interpolated MessageTerm objects", () => { const term = optionName("--port"); const msg = message`Option ${term} is required`; assert.deepEqual(msg[1], term); assert.notEqual(msg[1], term); }); it("should clone interpolated Message arrays", () => { const inner = message`invalid ${optionName("--port")}`; const outer = message`Error: ${inner}`; for (let i = 0; i < inner.length; i++) { assert.deepEqual(outer[i + 1], inner[i]); assert.notEqual(outer[i + 1], inner[i]); } }); it("should throw TypeError for unsupported interpolation value types", () => { const invalid = 42 as unknown as MessageTerm; assert.throws( () => message`Invalid: ${invalid}`, /Invalid value type in message: number\./, ); }); }); describe("message term constructors", () => { it("should create text term", () => { const term = text("Hello world"); assert.equal(term.type, "text"); assert.equal(term.text, "Hello world"); }); it("should create option name term", () => { const term = optionName("--verbose"); assert.equal(term.type, "optionName"); assert.equal(term.optionName, "--verbose"); }); it("should create option names term", () => { const term = optionNames(["--help", "-h"]); assert.equal(term.type, "optionNames"); assert.deepEqual(term.optionNames, ["--help", "-h"]); }); it("should create metavar term", () => { const term = metavar("FILE"); assert.equal(term.type, "metavar"); assert.equal(term.metavar, "FILE"); }); it("should create value term", () => { const term = value("42"); assert.equal(term.type, "value"); assert.equal(term.value, "42"); }); it("should create values term", () => { const term = values(["foo", "bar", "baz"]); assert.equal(term.type, "values"); assert.deepEqual(term.values, ["foo", "bar", "baz"]); }); it("should throw TypeError for empty values array", () => { assert.throws(() => values([]), { name: "TypeError", message: /empty/ }); }); it("should create envVar term", () => { const term = envVar("API_URL"); assert.equal(term.type, "envVar"); assert.equal(term.envVar, "API_URL"); }); it("should create commandLine term", () => { const term = commandLine("myapp completion bash > output.bash"); assert.equal(term.type, "commandLine"); assert.equal(term.commandLine, "myapp completion bash > output.bash"); }); it("should create lineBreak term", () => { const term = lineBreak(); assert.equal(term.type, "lineBreak"); }); it("should create url term from valid HTTP URL string", () => { const term = url("http://example.com"); assert.equal(term.type, "url"); assert.ok(term.url instanceof URL); assert.equal(term.url.href, "http://example.com/"); }); it("should create url term from valid HTTPS URL string", () => { const term = url("https://example.com/path"); assert.equal(term.type, "url"); assert.ok(term.url instanceof URL); assert.equal(term.url.href, "https://example.com/path"); }); it("should create url term from URL object", () => { const urlObj = new URL("https://example.com"); const term = url(urlObj); assert.equal(term.type, "url"); assert.equal(term.url.href, urlObj.href); assert.notEqual(term.url, urlObj); }); it("should accept various protocols (ftp, file, etc.)", () => { const term = url("ftp://ftp.example.com"); assert.equal(term.type, "url"); assert.ok(term.url instanceof URL); assert.equal(term.url.protocol, "ftp:"); }); it("should throw RangeError for invalid URL string", () => { assert.throws(() => url("not a valid url"), RangeError); }); it("should throw RangeError for empty string", () => { assert.throws(() => url(""), RangeError); }); it("should handle URL with query parameters", () => { const term = url("https://example.com?foo=bar&baz=qux"); assert.equal(term.type, "url"); assert.ok(term.url.href.includes("foo=bar")); }); it("should handle URL with hash fragment", () => { const term = url("https://example.com/page#section"); assert.equal(term.type, "url"); assert.equal(term.url.hash, "#section"); }); it("should normalize URL (add trailing slash to origin)", () => { const term = url("https://example.com"); assert.equal(term.type, "url"); // URL constructor normalizes this to include trailing slash assert.equal(term.url.href, "https://example.com/"); }); it("should create url term using link() alias", () => { const term = link("https://example.com"); assert.equal(term.type, "url"); assert.ok(term.url instanceof URL); assert.equal(term.url.href, "https://example.com/"); }); it("link() should work identically to url()", () => { const urlTerm = url("https://example.com/path"); const linkTerm = link("https://example.com/path"); assert.deepEqual(urlTerm, linkTerm); }); it("link() should accept URL object", () => { const urlObj = new URL("https://example.com"); const term = link(urlObj); assert.equal(term.type, "url"); assert.equal(term.url.href, urlObj.href); assert.notEqual(term.url, urlObj); }); it("link() should throw RangeError for invalid URL", () => { assert.throws(() => link("not valid"), RangeError); }); it("optionNames() should not be affected by later mutation of the input array", () => { const names = ["--a", "--b"]; const term = optionNames(names); names[0] = "--z"; assert.equal(term.type, "optionNames"); assert.deepEqual(term.optionNames, ["--a", "--b"]); }); it("values() should not be affected by later mutation of the input array", () => { const vals = ["a", "b"]; const term = values(vals); vals[1] = "y"; assert.equal(term.type, "values"); assert.deepEqual(term.values, ["a", "b"]); }); it("url(URL) should not be affected by later mutation of the input URL", () => { const href = new URL("https://example.com"); const term = url(href); href.pathname = "/changed"; assert.equal(term.type, "url"); assert.equal(term.url.href, "https://example.com/"); }); }); describe("formatMessage", () => { it("should throw TypeError for unknown MessageTerm type", () => { const invalid = [{ type: "unknown" } as unknown as MessageTerm]; assert.throws( () => formatMessage(invalid), /Invalid MessageTerm type: unknown\./, ); }); it("should format simple text message", () => { const msg: Message = [{ type: "text", text: "Simple message" }]; const formatted = formatMessage(msg); assert.equal(formatted, "Simple message"); }); it("should format option name without colors", () => { const msg: Message = [ { type: "text", text: "Unknown option " }, { type: "optionName", optionName: "--invalid" }, ]; const formatted = formatMessage(msg, { colors: false, quotes: true, }); assert.equal(formatted, "Unknown option `--invalid`"); }); it("should format option name with colors", () => { const msg: Message = [ { type: "text", text: "Unknown option " }, { type: "optionName", optionName: "--invalid" }, ]; const formatted = formatMessage(msg, { colors: true, quotes: true }); assert.equal(formatted, "Unknown option \x1b[3m`--invalid`\x1b[0m"); }); it("should format option names without quotes", () => { const msg: Message = [ { type: "text", text: "Use one of " }, { type: "optionNames", optionNames: ["--help", "--version"] }, ]; const formatted = formatMessage(msg, { quotes: false }); assert.equal(formatted, "Use one of --help/--version"); }); it("should format option names with quotes", () => { const msg: Message = [ { type: "text", text: "Use one of " }, { type: "optionNames", optionNames: ["--help", "--version"] }, ]; const formatted = formatMessage(msg, { quotes: true }); assert.equal(formatted, "Use one of `--help`/`--version`"); }); it("should format metavar without colors", () => { const msg: Message = [ { type: "text", text: "Expected " }, { type: "metavar", metavar: "FILE" }, ]; const formatted = formatMessage(msg, { colors: false, quotes: true, }); assert.equal(formatted, "Expected `FILE`"); }); it("should format metavar with colors", () => { const msg: Message = [ { type: "text", text: "Expected " }, { type: "metavar", metavar: "FILE" }, ]; const formatted = formatMessage(msg, { colors: true, quotes: true }); assert.equal(formatted, "Expected \x1b[1m`FILE`\x1b[0m"); }); it("should format envVar without colors", () => { const msg: Message = [ { type: "text", text: "Environment variable " }, { type: "envVar", envVar: "API_URL" }, { type: "text", text: " is not set" }, ]; const formatted = formatMessage(msg, { colors: false, quotes: true, }); assert.equal(formatted, "Environment variable `API_URL` is not set"); }); it("should format envVar with colors", () => { const msg: Message = [ { type: "text", text: "Environment variable " }, { type: "envVar", envVar: "API_URL" }, { type: "text", text: " is not set" }, ]; const formatted = formatMessage(msg, { colors: true, quotes: true }); assert.equal( formatted, "Environment variable \x1b[1;4m`API_URL`\x1b[0m is not set", ); }); it("should format commandLine without colors", () => { const msg: Message = [ { type: "text", text: "Run: " }, { type: "commandLine", commandLine: "myapp completion bash > output.bash", }, ]; const formatted = formatMessage(msg, { colors: false, quotes: true, }); assert.equal(formatted, "Run: `myapp completion bash > output.bash`"); }); it("should format commandLine with colors", () => { const msg: Message = [ { type: "text", text: "Run: " }, { type: "commandLine", commandLine: "myapp completion bash > output.bash", }, ]; const formatted = formatMessage(msg, { colors: true, quotes: true }); assert.equal( formatted, "Run: \x1b[36m`myapp completion bash > output.bash`\x1b[0m", ); }); it("should format commandLine without quotes", () => { const msg: Message = [ { type: "text", text: "Example: " }, { type: "commandLine", commandLine: "myapp --help" }, ]; const formatted = formatMessage(msg, { quotes: false }); assert.equal(formatted, "Example: myapp --help"); }); it("should format single value without colors", () => { const msg: Message = [ { type: "text", text: "Invalid value " }, { type: "value", value: "invalid" }, ]; const formatted = formatMessage(msg, { colors: false, quotes: true, }); assert.equal(formatted, 'Invalid value "invalid"'); }); it("should format single value with colors", () => { const msg: Message = [ { type: "text", text: "Invalid value " }, { type: "value", value: "invalid" }, ]; const formatted = formatMessage(msg, { colors: true, quotes: true }); assert.equal(formatted, 'Invalid value \x1b[32m"invalid"\x1b[0m'); }); it("should format multiple values", () => { const msg: Message = [ { type: "text", text: "Expected one of " }, { type: "values", values: ["red", "green", "blue"] }, ]; const formatted = formatMessage(msg, { quotes: true }); assert.equal(formatted, 'Expected one of "red" "green" "blue"'); }); it("should format values without quotes", () => { const msg: Message = [ { type: "text", text: "Got " }, { type: "values", values: ["foo", "bar"] }, ]; const formatted = formatMessage(msg, { quotes: false }); assert.equal(formatted, "Got foo bar"); }); it("should handle default options", () => { const msg: Message = [ { type: "text", text: "Error: " }, { type: "value", value: "test" }, ]; const formatted = formatMessage(msg); assert.equal(formatted, 'Error: "test"'); }); it("should handle complex mixed message", () => { const msg: Message = [ { type: "text", text: "Option " }, { type: "optionName", optionName: "--port" }, { type: "text", text: " expects " }, { type: "metavar", metavar: "NUMBER" }, { type: "text", text: ", got " }, { type: "value", value: "invalid" }, ]; const formatted = formatMessage(msg, { quotes: true }); assert.equal(formatted, 'Option `--port` expects `NUMBER`, got "invalid"'); }); it("should wrap message at maxWidth", () => { const msg: Message = [ { type: "text", text: "This is a very long message that should be wrapped ", }, { type: "optionName", optionName: "--port" }, { type: "text", text: " expects " }, { type: "metavar", metavar: "NUMBER" }, ]; const formatted = formatMessage(msg, { maxWidth: 30 }); assert.ok(formatted.includes("\n")); const lines = formatted.split("\n"); assert.ok(lines.length > 1); // The wrapping logic wraps when the next segment would exceed maxWidth // So lines may be longer than maxWidth if a single segment is long const nonEmptyLines = lines.filter((line) => line.length > 0); assert.ok(nonEmptyLines.length >= 2); }); it("should not wrap when maxWidth is not set", () => { const msg: Message = [ { type: "text", text: "This is a very long message that should not be wrapped without maxWidth option ", }, { type: "optionName", optionName: "--port" }, ]; const formatted = formatMessage(msg); assert.ok(!formatted.includes("\n")); }); it("should wrap at word boundaries with maxWidth", () => { const msg: Message = [ { type: "text", text: "Short text " }, { type: "value", value: "very-long-value-that-exceeds-width" }, { type: "text", text: " more text" }, ]; const formatted = formatMessage(msg, { maxWidth: 20 }); assert.ok(formatted.includes("\n")); }); it("should handle maxWidth with colors enabled", () => { const msg: Message = [ { type: "text", text: "Error with " }, { type: "optionName", optionName: "--verbose-option" }, { type: "text", text: " parameter value " }, { type: "value", value: "test" }, ]; const formatted = formatMessage(msg, { maxWidth: 25, colors: true }); assert.ok(formatted.includes("\n")); // Should still wrap based on visual width, not ANSI code length const lines = formatted.split("\n"); assert.ok(lines.length > 1); }); it("should handle maxWidth of zero", () => { const msg: Message = [ { type: "text", text: "Test" }, { type: "value", value: "value" }, ]; const formatted = formatMessage(msg, { maxWidth: 0 }); // Should still produce output but might wrap aggressively assert.ok(typeof formatted === "string"); assert.ok(formatted.length > 0); }); it("should not emit leading newline for oversize first word", () => { const msg: Message = [{ type: "text", text: "SUPERLONGWORD" }]; const formatted = formatMessage(msg, { maxWidth: 3 }); assert.equal(formatted, "SUPERLONGWORD"); }); it("should handle single character maxWidth", () => { const msg: Message = [ { type: "text", text: "A" }, { type: "text", text: "B" }, { type: "text", text: "C" }, ]; const formatted = formatMessage(msg, { maxWidth: 1 }); assert.ok(formatted.includes("\n")); const lines = formatted.split("\n"); assert.ok(lines.length >= 2); }); describe("Unicode display width", () => { it("should wrap Korean text based on display width", () => { const msg: Message = [text("한글 한글 한글")]; // Each "한글" = 4 display columns. With maxWidth 9, two words // fit ("한글 한글" = 4+1+4 = 9) but three do not. const formatted = formatMessage(msg, { quotes: false, maxWidth: 9 }); const lines = formatted.split("\n"); assert.equal(lines.length, 2); for (const line of lines) { assert.ok( getDisplayWidth(line) <= 9, `Line display width exceeds 9: "${line}" (${getDisplayWidth( line, )} columns)`, ); } }); it("should not wrap Korean text when it fits", () => { const msg: Message = [text("한글")]; // "한글" = 4 display columns, maxWidth = 4 const formatted = formatMessage(msg, { quotes: false, maxWidth: 4 }); assert.ok(!formatted.includes("\n")); assert.equal(getDisplayWidth(formatted), 4); }); it("should wrap combining marks based on display width", () => { // "e\u0301" = 1 display column each const msg: Message = [text("e\u0301 e\u0301 e\u0301")]; const formatted = formatMessage(msg, { quotes: false, maxWidth: 5 }); // "e\u0301 e\u0301 e\u0301" = 5 columns, should fit in one line assert.ok(!formatted.includes("\n")); assert.equal(getDisplayWidth(formatted), 5); }); it("should wrap emoji based on display width", () => { const msg: Message = [text("😀 😀 😀")]; // Each "😀" = 2 columns. "😀 " = 3 columns. With maxWidth 5, // "😀 😀" doesn't fit (3+3=6 > 5), so second emoji wraps, // then "😀 😀" (3+2=5 <= 5) fits on the second line. const formatted = formatMessage(msg, { quotes: false, maxWidth: 5 }); const lines = formatted.split("\n"); assert.equal(lines.length, 2); for (const line of lines) { assert.ok( getDisplayWidth(line) <= 5, `Line display width exceeds 5: "${line}" (${getDisplayWidth( line, )} columns)`, ); } }); it("should handle ZWJ emoji sequences", () => { const msg: Message = [text("👨‍👩‍👧‍👦 x")]; // "👨‍👩‍👧‍👦" = 2 columns, " " = 1, "x" = 1, total = 4 const formatted = formatMessage(msg, { quotes: false, maxWidth: 5 }); assert.ok(!formatted.includes("\n")); assert.equal(getDisplayWidth(formatted), 4); }); }); describe("resetSuffix functionality", () => { it("should apply resetSuffix after ANSI reset sequences", () => { const msg: Message = [ { type: "text", text: "Environment variable " }, { type: "envVar", envVar: "PATH" }, { type: "text", text: " is required" }, ]; const formatted = formatMessage(msg, { colors: { resetSuffix: "\x1b[2m" }, quotes: false, }); // Should contain the resetSuffix after the envVar reset assert.ok(formatted.includes("\x1b[0m\x1b[2m")); assert.ok(formatted.includes("\x1b[1;4mPATH\x1b[0m\x1b[2m is required")); }); it("should work with boolean colors option (backward compatibility)", () => { const msg: Message = [ { type: "text", text: "Value " }, { type: "value", value: "test" }, { type: "text", text: " is invalid" }, ]; // Test with colors: true (boolean) const withColors = formatMessage(msg, { colors: true, quotes: false }); assert.equal(withColors, "Value \x1b[32mtest\x1b[0m is invalid"); // Test with colors: false (boolean) const withoutColors = formatMessage(msg, { colors: false, quotes: false, }); assert.equal(withoutColors, "Value test is invalid"); }); it("should apply resetSuffix to all styled elements", () => { const msg: Message = [ { type: "optionName", optionName: "--verbose" }, { type: "text", text: " and " }, { type: "metavar", metavar: "FILE" }, { type: "text", text: " with " }, { type: "envVar", envVar: "HOME" }, ]; const formatted = formatMessage(msg, { colors: { resetSuffix: "\x1b[2m" }, quotes: false, }); // Each styled element should end with resetSuffix assert.ok(formatted.includes("--verbose\x1b[0m\x1b[2m")); assert.ok(formatted.includes("FILE\x1b[0m\x1b[2m")); assert.ok(formatted.includes("HOME\x1b[0m\x1b[2m")); }); it("should handle empty resetSuffix", () => { const msg: Message = [ { type: "text", text: "Option " }, { type: "optionName", optionName: "--help" }, { type: "text", text: " is available" }, ]; const formatted = formatMessage(msg, { colors: { resetSuffix: "" }, quotes: false, }); // Should behave like normal colors: true assert.equal(formatted, "Option \x1b[3m--help\x1b[0m is available"); }); it("should handle undefined resetSuffix", () => { const msg: Message = [ { type: "text", text: "Value " }, { type: "value", value: "42" }, ]; const formatted = formatMessage(msg, { colors: { resetSuffix: undefined }, quotes: false, }); // Should behave like normal colors: true assert.equal(formatted, "Value \x1b[32m42\x1b[0m"); }); }); }); describe("integration tests", () => { it("should create and format complete message", () => { const option = "--timeout"; const expected = "NUMBER"; const actual = "not-a-number"; const msg = message`Option ${optionName(option)} expects ${metavar( expected, )}, got ${actual}`; const formatted = formatMessage(msg, { quotes: true }); assert.equal( formatted, 'Option `--timeout` expects `NUMBER`, got "not-a-number"', ); }); it("should handle constraint violation message", () => { const min = "10"; const max = "100"; const actual = "150"; const msg = message`Value must be between ${min} and ${max}, got ${actual}`; const formatted = formatMessage(msg); assert.equal(formatted, 'Value must be between "10" and "100", got "150"'); }); it("should format choice error message", () => { const choices = ["red", "green", "blue"]; const invalid = "purple"; const msg = message`Expected one of ${values(choices)}, got ${invalid}`; const formatted = formatMessage(msg, { quotes: true }); assert.equal( formatted, 'Expected one of "red" "green" "blue", got "purple"', ); }); it("should handle resetSuffix when colors is an object", () => { const msg = message`Port: ${value("8080")}`; const formatted = formatMessage(msg, { colors: { resetSuffix: "\x1b[2m" }, quotes: false, }); assert.equal(formatted, "Port: \x1b[32m8080\x1b[0m\x1b[2m"); }); it("should handle resetSuffix with multiple terms", () => { const msg = message`Options: ${optionName("--verbose")} and ${value( "true", )}`; const formatted = formatMessage(msg, { colors: { resetSuffix: "\x1b[2m" }, quotes: false, }); assert.equal( formatted, "Options: \x1b[3m--verbose\x1b[0m\x1b[2m and \x1b[32mtrue\x1b[0m\x1b[2m", ); }); it("should handle resetSuffix with boolean colors for backward compatibility", () => { const msg = message`Port: ${value("8080")}`; const formatted = formatMessage(msg, { colors: true, quotes: false }); assert.equal(formatted, "Port: \x1b[32m8080\x1b[0m"); }); it("should handle resetSuffix with envVar term", () => { const msg = message`Environment variable: ${envVar("API_URL")}`; const formatted = formatMessage(msg, { colors: { resetSuffix: "\x1b[2m" }, quotes: false, }); assert.equal( formatted, "Environment variable: \x1b[1;4mAPI_URL\x1b[0m\x1b[2m", ); }); it("should handle resetSuffix with commandLine term", () => { const msg = message`Run: ${commandLine("myapp --help")}`; const formatted = formatMessage(msg, { colors: { resetSuffix: "\x1b[2m" }, quotes: false, }); assert.equal(formatted, "Run: \x1b[36mmyapp --help\x1b[0m\x1b[2m"); }); it("should handle resetSuffix with values term", () => { const msg = message`Values: ${values(["red", "green", "blue"])}`; const formatted = formatMessage(msg, { colors: { resetSuffix: "\x1b[2m" }, quotes: false, }); assert.equal(formatted, "Values: \x1b[32mred green blue\x1b[0m\x1b[2m"); }); for (const quotes of [false, true]) { it(`should reset color after a single value with quotes=${quotes}`, () => { const msg = message`List: ${values(["one"])} tail`; assert.equal( formatMessage(msg, { colors: true, quotes }), quotes ? 'List: \x1b[32m"one"\x1b[0m tail' : "List: \x1b[32mone\x1b[0m tail", ); }); it(`should restore parent style after a single value with quotes=${quotes}`, () => { const msg = message`List: ${values(["one"])} tail`; assert.equal( formatMessage(msg, { colors: { resetSuffix: "\x1b[2m" }, quotes }), quotes ? 'List: \x1b[32m"one"\x1b[0m\x1b[2m tail' : "List: \x1b[32mone\x1b[0m\x1b[2m tail", ); }); } it("should not apply resetSuffix when colors is false", () => { const msg = message`Port: ${value("8080")}`; const formatted = formatMessage(msg, { colors: false, quotes: false, }); assert.equal(formatted, "Port: 8080"); }); it("should handle empty resetSuffix", () => { const msg = message`Port: ${value("8080")}`; const formatted = formatMessage(msg, { colors: { resetSuffix: "" }, quotes: false, }); assert.equal(formatted, "Port: \x1b[32m8080\x1b[0m"); }); }); describe("formatMessage - explicit line breaks", () => { it("should render explicit lineBreak term as single hard break", () => { const msg: Message = [ { type: "text", text: "Line 1." }, lineBreak(), { type: "text", text: "Line 2." }, ]; const formatted = formatMessage(msg, { quotes: false }); assert.equal(formatted, "Line 1.\nLine 2."); }); it("should support lineBreak in template interpolation", () => { const msg = message`First:${lineBreak()} ${optionName("--help")}`; const formatted = formatMessage(msg, { quotes: false }); assert.equal(formatted, "First:\n --help"); }); it("should treat single newline as space (soft break)", () => { const msg: Message = [ { type: "text", text: "Line 1." }, { type: "text", text: "\n" }, { type: "text", text: "Line 2." }, ]; const formatted = formatMessage(msg, { quotes: false }); // Single newline is converted to space assert.equal(formatted, "Line 1. Line 2."); }); it("should treat single newline within text as space", () => { const msg: Message = [{ type: "text", text: "Line 1.\nLine 2." }]; const formatted = formatMessage(msg, { quotes: false }); // Single newline is converted to space assert.equal(formatted, "Line 1. Line 2."); }); it("should treat double newline as hard break", () => { const msg: Message = [{ type: "text", text: "Para 1.\n\nPara 2." }]; const formatted = formatMessage(msg, { quotes: false }); // Double newline creates paragraph break (double newline in output) assert.equal(formatted, "Para 1.\n\nPara 2."); }); it("should handle multiple double newlines", () => { const msg: Message = [{ type: "text", text: "A\n\nB\n\nC" }]; const formatted = formatMessage(msg, { quotes: false }); assert.equal(formatted, "A\n\nB\n\nC"); }); it("should handle triple+ newlines as single hard break", () => { const msg: Message = [{ type: "text", text: "Line 1\n\n\nLine 2" }]; const formatted = formatMessage(msg, { quotes: false }); // Triple newlines still treated as single paragraph break assert.equal(formatted, "Line 1\n\nLine 2"); }); it("should handle double newline with option names", () => { const msg: Message = [ { type: "text", text: "No matched option for " }, { type: "optionName", optionName: "--verbos" }, { type: "text", text: "." }, { type: "text", text: "\n\n" }, { type: "text", text: "Did you mean " }, { type: "optionName", optionName: "--verbose" }, { type: "text", text: "?" }, ]; const formatted = formatMessage(msg, { quotes: false }); assert.ok(formatted.includes("\n\n")); assert.ok(formatted.includes("--verbos")); assert.ok(formatted.includes("--verbose")); const lines = formatted.split("\n"); assert.equal(lines.length, 3); // paragraph break = empty line between }); it("should reset width tracking after hard line break", () => { const msg: Message = [ { type: "text", text: "Short.\n\nThis is a much longer second line." }, ]; const formatted = formatMessage(msg, { quotes: false, maxWidth: 50 }); const lines = formatted.split("\n"); assert.equal(lines.length, 3); // paragraph break = empty line between assert.ok(lines[0].startsWith("Short.")); assert.equal(lines[1], ""); assert.ok(lines[2].includes("This is a much longer second line.")); }); it("should normalize single newlines in long text", () => { const msg: Message = [ { type: "text", text: "This is a\nvery long\nsentence that\nspans multiple\nlines.", }, ]; const formatted = formatMessage(msg, { quotes: false }); // All single newlines become spaces assert.equal( formatted, "This is a very long sentence that spans multiple lines.", ); }); it("should handle mixed single and double newlines", () => { const msg: Message = [ { type: "text", text: "Para 1 line 1.\nPara 1 line 2.\n\nPara 2 line 1.\nPara 2 line 2.", }, ]; const formatted = formatMessage(msg, { quotes: false }); assert.equal( formatted, "Para 1 line 1. Para 1 line 2.\n\nPara 2 line 1. Para 2 line 2.", ); }); it("should handle empty paragraphs (multiple consecutive double newlines)", () => { const msg: Message = [{ type: "text", text: "Line 1\n\n\n\nLine 2" }]; const formatted = formatMessage(msg, { quotes: false }); // Multiple double newlines still create single paragraph break assert.equal(formatted, "Line 1\n\nLine 2"); }); it("should strip leading newline from text immediately after lineBreak()", () => { // When lineBreak() is followed by a text term starting with \n (as happens in // template literals like `${lineBreak()}\nContent`), the leading \n must be // dropped to avoid yielding an extra space. const msg: Message = [ { type: "text", text: "Before" }, lineBreak(), { type: "text", text: "\nAfter" }, ]; const formatted = formatMessage(msg, { quotes: false }); assert.equal(formatted, "Before\nAfter"); }); it("should strip leading newline but preserve remaining indentation after lineBreak()", () => { // The leading \n must be stripped, but subsequent whitespace (indentation) // must be preserved. const msg: Message = [ { type: "text", text: "Before" }, lineBreak(), { type: "text", text: "\n indented" }, ]; const formatted = formatMessage(msg, { quotes: false }); assert.equal(formatted, "Before\n indented"); }); it("should not add extra space between lineBreak() and commandLine() in template literal", () => { // Regression test: template literals produce a text("\n") between lineBreak() // and the next interpolated value. That \n was being normalized to a space, // creating a spurious leading space on the next line. const msg = message`Common:${lineBreak()} ${commandLine("myapp add .")} Stage changes${lineBreak()} ${commandLine("myapp status")} Show status`; const formatted = formatMessage(msg, { quotes: false }); const lines = formatted.split("\n"); assert.equal(lines.length, 3); assert.equal(lines[0], "Common:"); assert.ok( lines[1].startsWith("myapp add ."), `Expected line to start with "myapp add .", got: ${JSON.stringify( lines[1], )}`, ); assert.ok( lines[2].startsWith("myapp status"), `Expected line to start with "myapp status", got: ${JSON.stringify( lines[2], )}`, ); }); it("should preserve paragraph break (\\n\\n) following lineBreak()", () => { // A double newline after lineBreak() is an intentional paragraph separator // and must NOT be stripped. Only a lone \n (soft-break artifact) is absorbed. const msg: Message = [ { type: "text", text: "Line 1" }, lineBreak(), { type: "text", text: "\n\nSection header" }, ]; const formatted = formatMessage(msg, { quotes: false }); // lineBreak() yields one \n; the \n\n yields another \n (paragraph break); // total: two \n before "Section header". assert.equal(formatted, "Line 1\n\nSection header"); }); }); describe("formatMessage - carriage-return line endings", () => { for (const ending of ["\r\n", "\r"]) { it(`should normalize ${JSON.stringify(ending)} as a soft break`, () => { assert.equal(formatMessage([text(ending)]), " "); assert.equal(formatMessage([text(`${ending} `)]), " "); assert.equal( formatMessage([text("before"), text(ending), text("after")]), "before after", ); assert.equal( formatMessage([text(`before${ending}after`)]), "before after", ); }); it(`should recognize ${JSON.stringify(ending)} paragraph breaks`, () => { assert.equal( formatMessage([text(`before${ending}${ending} after`)]), "before\n\n after", ); assert.equal( formatMessage([ text("before"), lineBreak(), text(`${ending}${ending}after`), ]), "before\n\nafter", ); }); it(`should absorb ${JSON.stringify(ending)} after lineBreak()`, () => { const options = { colors: false, quotes: false }; assert.equal( formatMessage( [ text("Examples:"), lineBreak(), text(`${ending} `), commandLine("kayra status"), ], options, ), "Examples:\n kayra status", ); assert.equal( formatMessage([lineBreak(), text(`${ending} next`)], options), "\n next", ); assert.equal( formatMessage([lineBreak(), text(ending), text("next")], options), "\nnext", ); }); it(`should wrap using normalized ${JSON.stringify(ending)} spacing`, () => { const msg: Message = [text("ab"), text(`${ending} `), text("c")]; assert.equal(formatMessage(msg), "ab c"); assert.equal(formatMessage(msg, { maxWidth: 3 }), "ab\nc"); }); } }); // https://github.com/dahlia/optique/issues/1003 describe("formatMessage - whitespace-only text terms", () => { it("should preserve spaces across text term boundaries", () => { const options = { colors: false, quotes: false }; assert.equal(formatMessage([text(" ")], options), " "); assert.equal( formatMessage([text(" "), commandLine("kayra status")], options), " kayra status", ); assert.equal( formatMessage([text(" "), text("kayra status")], options), formatMessage([text(" kayra status")], options), ); assert.equal( formatMessage([text("a"), text(" "), text("b"), text(" ")], options), "a b ", ); assert.equal( formatMessage([text(" "), text(""), text(" "), text("b")], options), " b", ); }); it("should preserve whitespace after newline normalization", () => { assert.equal(formatMessage([text("\t")]), "\t"); assert.equal(formatMessage([text(" ")]), " "); assert.equal(formatMessage([text(" \n\t ")]), " \t "); assert.equal(formatMessage([text("a"), text("\n "), text("b")]), "a b"); assert.equal(formatMessage([text("")]), ""); }); it("should preserve split indentation after explicit breaks", () => { const options = { colors: false, quotes: false }; assert.equal( formatMessage( message`Examples:${lineBreak()} ${commandLine("kayra status")}`, options, ), "Examples:\n kayra status", ); assert.equal( formatMessage( message`Examples:${lineBreak()} ${commandLine("kayra status")}`, options, ), "Examples:\n kayra status", ); assert.equal( formatMessage([lineBreak(), text("\n"), text("end")], options), "\nend", ); assert.equal( formatMessage([lineBreak(), text(" "), commandLine("bb")], { ...options, maxWidth: 4, }), "\n bb", ); }); it("should keep indentation outside command-line styling and quotes", () => { for (const colors of [false, true]) { for (const quotes of [false, true]) { const command = quotes ? "`kayra status`" : "kayra status"; const styled = colors ? `\x1b[36m${command}\x1b[0m` : command; assert.equal( formatMessage([text(" "), commandLine("kayra status")], { colors, quotes, }), ` ${styled}`, ); } } }); it("should count the full display width of whitespace-only terms", () => { assert.equal( formatMessage([text("ab"), text(" "), text("c")], { maxWidth: 3 }), "ab\nc", ); const wideSpace: Message = [text("a"), text(" "), text("b")]; assert.equal(formatMessage(wideSpace, { maxWidth: 2 }), "a\nb"); assert.equal(formatMessage(wideSpace, { maxWidth: 4 }), "a b"); // A separator that fits exactly stays on the preceding line. assert.equal( formatMessage([text("ab"), text(" "), text("c")], { maxWidth: 4 }), "ab \nc", ); }); it("should keep deferred-wrap behavior for multi-space separators", () => { const prefix: Message = [text("abc"), text(" ")]; assert.equal(formatMessage(prefix, { maxWidth: 4 }), "abc"); assert.equal( formatMessage([...prefix, lineBreak(), text("d")], { maxWidth: 4 }), "abc\nd", ); // Existing behavior: an empty semantic term must not flush a pending wrap. assert.equal( formatMessage([...prefix, value(""), text(" "), text("def")], { quotes: false, maxWidth: 3, }), "abc\ndef", ); }); it("should drop multi-space separators when initialWidth forces a wrap", () => { const options: MessageFormatOptions = { maxWidth: 3, initialWidth: 2, }; assert.equal(formatMessage([text(" "), text("b")], options), "\nb"); }); }); describe("formatMessage - whitespace at automatic wraps", () => { it("should drop a text term's leading space when it wraps", () => { const msg: Message = [ text("Enable or disable highlighting"), text(" (default: auto)"), ]; assert.equal( formatMessage(msg, { maxWidth: 20 }), "Enable or disable \nhighlighting\n(default: auto)", ); }); it("should not count the dropped space toward the new line", () => { // " bb " wraps; without its leading space, "bb cc" fits in 5 columns. const msg: Message = [text("aaaa"), text(" bb cc")]; assert.equal(formatMessage(msg, { maxWidth: 5 }), "aaaa\nbb cc"); }); it("should drop the leading space of a term with paragraph breaks", () => { const msg: Message = [text("abc"), text(" def\n\nghi")]; assert.equal(formatMessage(msg, { maxWidth: 3 }), "abc\ndef\n\nghi"); }); it("should not start a line with a whitespace-only text term", () => { const msg: Message = [text("abc"), text(" "), text("def")]; assert.equal(formatMessage(msg, { maxWidth: 3 }), "abc\ndef"); }); it("should not end with a newline for a trailing whitespace term", () => { const msg: Message = [text("abc"), text(" ")]; assert.equal(formatMessage(msg, { maxWidth: 3 }), "abc"); }); it("should not emit an extra newline before a lineBreak() term", () => { const msg: Message = [text("abc"), text(" "), lineBreak(), text("def")]; assert.equal(formatMessage(msg, { maxWidth: 3 }), "abc\ndef"); }); it("should keep zero-width content after a dropped space on the new line", () => { const msg: Message = [text("abc"), text(" "), value("́")]; assert.equal(formatMessage(msg, { quotes: false, maxWidth: 3 }), "abc\ń"); }); it("should keep trimming at a wrapped line start after empty values", () => { const msg: Message = [text("abc"), text(" "), value(""), text(" def")]; assert.equal( formatMessage(msg, { quotes: false, maxWidth: 3 }), "abc\ndef", ); assert.equal( formatMessage([text("abc"), text(" "), value("")], { quotes: false, maxWidth: 3, }), "abc", ); assert.equal( formatMessage(msg, { quotes: false, colors: true, maxWidth: 3 }), "abc\x1b[32m\x1b[0m\ndef", ); }); it("should not flush a deferred wrap for a styled empty value", () => { const options = { quotes: false, colors: true, maxWidth: 3 } as const; assert.equal( formatMessage([text("abc"), text(" "), value("")], options), "abc\x1b[32m\x1b[0m", ); assert.equal( formatMessage( [text("abc"), text(" "), value(""), lineBreak(), text("def")], options, ), "abc\x1b[32m\x1b[0m\ndef", ); }); it("should still wrap before an empty value on an overfull line", () => { // formatDocPage() relies on this to move an annotation suffix to the // next line when the annotation content is empty. const options: MessageFormatOptions = { quotes: false, maxWidth: 3, initialWidth: 5, }; assert.equal(formatMessage([value("")], options), "\n"); }); it("should drop the separator between values() items when it wraps", () => { const msg: Message = [values(["aaa", "bbb"])]; assert.equal( formatMessage(msg, { quotes: false, maxWidth: 3 }), "aaa\nbbb", ); assert.equal( formatMessage(msg, { quotes: false, colors: true, maxWidth: 3 }), "\x1b[32maaa\nbbb\x1b[0m", ); }); it("should drop the values() separator with a themed value formatter", () => { const format = createMessageFormatter({ value: (_term, ctx) => ({ type: "text", text: `<${ctx.text}>` }), }); assert.equal( format([values(["aaa", "bbb"])], { quotes: false, maxWidth: 5 }), "\n", ); }); it("should keep whitespace that belongs to values", () => { assert.equal( formatMessage([text("abc"), value(" xyz")], { quotes: false, maxWidth: 3, }), "abc\n xyz", ); assert.equal( formatMessage([text("abc"), values(["abc", " b"])], { quotes: false, maxWidth: 3, }), "abc\nabc\n b", ); }); it("should keep leading whitespace placed by the caller", () => { assert.equal( formatMessage([text(" indented text here")], { maxWidth: 10 }), " indented \ntext here", ); assert.equal( formatMessage([text("first\n\n second line")], { maxWidth: 8 }), "first\n\n second \nline", ); assert.equal( formatMessage([text("a"), lineBreak(), text(" bb"), text(" cc")], { maxWidth: 4, }), "a\n bb\ncc", ); }); it("should drop the space with colors enabled", () => { const msg: Message = [ text("Use "), optionName("--color"), text(" to enable highlighting"), ]; assert.equal( formatMessage(msg, { colors: true, maxWidth: 13 }), "Use \x1b[3m`--color`\x1b[0m\nto enable \nhighlighting", ); }); it("should drop ideographic spaces by display width", () => { const msg: Message = [text("한글"), text(" 한글 한")]; // After dropping U+3000 (2 columns), "한글 " (5) + "한" (2) fits in 7. assert.equal( formatMessage(msg, { quotes: false, maxWidth: 7 }), "한글\n한글 한", ); }); it("should drop the space when the start width forces a wrap", () => { const at = (initialWidth: number): MessageFormatOptions => ({ maxWidth: 10, initialWidth, }); assert.equal(formatMessage([text(" ab cd")], at(10)), "\nab cd"); assert.equal(formatMessage([text(" ab cd")], at(12)), "\nab cd"); assert.equal(formatMessage([text("ab"), text(" cd")], at(7)), "ab\ncd"); }); }); describe("valueSet", () => { it("should format list with conjunction by default", () => { const msg = valueSet(["error", "warn", "info"], { fallback: "", locale: "en", }); // Should have 5 terms: value, text(", "), value, text(", and "), value assert.ok(Array.isArray(msg)); assert.equal(msg.length, 5); assert.deepEqual(msg[0], { type: "value", value: "error" }); assert.deepEqual(msg[1], { type: "text", text: ", " }); assert.deepEqual(msg[2], { type: "value", value: "warn" }); assert.deepEqual(msg[3], { type: "text", text: ", and " }); assert.deepEqual(msg[4], { type: "value", value: "info" }); }); it("should format list with disjunction", () => { const msg = valueSet(["error", "warn", "info"], { fallback: "", locale: "en", type: "disjunction", }); assert.ok(Array.isArray(msg)); assert.equal(msg.length, 5); assert.deepEqual(msg[0], { type: "value", value: "error" }); assert.deepEqual(msg[1], { type: "text", text: ", " }); assert.deepEqual(msg[2], { type: "value", value: "warn" }); assert.deepEqual(msg[3], { type: "text", text: ", or " }); assert.deepEqual(msg[4], { type: "value", value: "info" }); }); it("should return empty array for empty input with empty fallback", () => { const msg = valueSet([], ""); assert.ok(Array.isArray(msg)); assert.equal(msg.length, 0); }); it("should return fallback text for empty input", () => { const msg = valueSet([], "(none)"); assert.ok(Array.isArray(msg)); assert.equal(msg.length, 1); assert.deepEqual(msg[0], { type: "text", text: "(none)" }); }); it("should return fallback text from options for empty input", () => { const msg = valueSet([], { fallback: "(없음)", locale: "ko" }); assert.ok(Array.isArray(msg)); assert.equal(msg.length, 1); assert.deepEqual(msg[0], { type: "text", text: "(없음)" }); }); it("should ignore fallback when values are non-empty", () => { const msg = valueSet(["a"], "(none)"); assert.ok(Array.isArray(msg)); assert.equal(msg.length, 1); assert.deepEqual(msg[0], { type: "value", value: "a" }); }); it("should throw TypeError when called without fallback", () => { // Runtime validation for JavaScript callers or old compiled code assert.throws( /* oxlint-disable no-explicit-any -- Keep unchecked input. */ // deno-lint-ignore no-explicit-any () => (valueSet as any)([]), /* oxlint-enable no-explicit-any */ { name: "TypeError", message: /fallback/ }, ); assert.throws( /* oxlint-disable no-explicit-any -- Keep unchecked input. */ // deno-lint-ignore no-explicit-any () => (valueSet as any)([], { locale: "en" }), /* oxlint-enable no-explicit-any */ { name: "TypeError", message: /fallback/ }, ); }); it("should handle single element", () => { const msg = valueSet(["only"], { fallback: "", locale: "en" }); assert.ok(Array.isArray(msg)); assert.equal(msg.length, 1); assert.deepEqual(msg[0], { type: "value", value: "only" }); }); it("should handle two elements", () => { const msg = valueSet(["first", "second"], { fallback: "", locale: "en" }); // Should have 3 terms: value, text(" and "), value assert.ok(Array.isArray(msg)); assert.equal(msg.length, 3); assert.deepEqual(msg[0], { type: "value", value: "first" }); assert.deepEqual(msg[1], { type: "text", text: " and " }); assert.deepEqual(msg[2], { type: "value", value: "second" }); }); it("should handle two elements with disjunction", () => { const msg = valueSet(["first", "second"], { fallback: "", locale: "en", type: "disjunction", }); assert.ok(Array.isArray(msg)); assert.equal(msg.length, 3); assert.deepEqual(msg[0], { type: "value", value: "first" }); assert.deepEqual(msg[1], { type: "text", text: " or " }); assert.deepEqual(msg[2], { type: "value", value: "second" }); }); it("should work with Korean locale", () => { const msg = valueSet(["error", "warn", "info"], { fallback: "", locale: "ko", type: "disjunction", }); // Korean uses different separators assert.ok(Array.isArray(msg)); assert.equal(msg.length, 5); // Check that values are preserved assert.deepEqual(msg[0], { type: "value", value: "error" }); assert.deepEqual(msg[2], { type: "value", value: "warn" }); assert.deepEqual(msg[4], { type: "value", value: "info" }); // Korean "or" is "또는" assert.equal(msg[3].type, "text"); if (msg[3].type === "text") { assert.ok(msg[3].text.includes("또는")); } }); it("should accept Intl.Locale object", () => { const locale = new Intl.Locale("en-US"); const msg = valueSet(["a", "b"], { fallback: "", locale }); assert.ok(Array.isArray(msg)); assert.equal(msg.length, 3); assert.deepEqual(msg[0], { type: "value", value: "a" }); assert.deepEqual(msg[2], { type: "value", value: "b" }); }); it("should accept array of locales", () => { const msg = valueSet(["a", "b"], { fallback: "", locale: ["en-US", "en"] }); assert.ok(Array.isArray(msg)); assert.equal(msg.length, 3); }); it("should work without options (use system default)", () => { const msg = valueSet(["a", "b", "c"], ""); // Should produce valid output with system default locale assert.ok(Array.isArray(msg)); assert.equal(msg.length, 5); assert.deepEqual(msg[0], { type: "value", value: "a" }); assert.deepEqual(msg[2], { type: "value", value: "b" }); assert.deepEqual(msg[4], { type: "value", value: "c" }); }); it("should integrate with message template", () => { const msg = message`Expected ${valueSet(["a", "b"], { fallback: "", locale: "en", })}.`; const formatted = formatMessage(msg, { quotes: true }); assert.equal(formatted, 'Expected "a" and "b".'); }); it("should integrate with message template using disjunction", () => { const msg = message`Expected one of ${valueSet(["error", "warn", "info"], { fallback: "", locale: "en", type: "disjunction", })}.`; const formatted = formatMessage(msg, { quotes: true }); assert.equal(formatted, 'Expected one of "error", "warn", or "info".'); }); }); describe("formatMessage with url term", () => { it("should format url without colors and without quotes", () => { const msg: Message = [ { type: "text", text: "Visit " }, { type: "url", url: new URL("https://example.com") }, ]; const formatted = formatMessage(msg, { colors: false, quotes: false }); assert.equal(formatted, "Visit https://example.com/"); }); it("should format url without colors and with quotes", () => { const msg: Message = [ { type: "text", text: "Visit " }, { type: "url", url: new URL("https://example.com") }, ]; const formatted = formatMessage(msg, { colors: false, quotes: true }); assert.equal(formatted, "Visit "); }); it("should format url with colors and without quotes (OSC 8)", () => { const msg: Message = [ { type: "text", text: "Visit " }, { type: "url", url: new URL("https://example.com") }, ]; const formatted = formatMessage(msg, { colors: true, quotes: false }); // OSC 8 format: \x1b]8;;URL\x1b\\TEXT\x1b]8;;\x1b\\ assert.ok(formatted.includes("\x1b]8;;https://example.com/\x1b\\")); assert.ok(formatted.includes("https://example.com/")); assert.ok(formatted.includes("\x1b]8;;\x1b\\")); assert.equal( formatted, "Visit \x1b]8;;https://example.com/\x1b\\https://example.com/\x1b]8;;\x1b\\", ); }); it("should format url with colors and with quotes (OSC 8 + angle brackets)", () => { const msg: Message = [ { type: "text", text: "Visit " }, { type: "url", url: new URL("https://example.com") }, ]; const formatted = formatMessage(msg, { colors: true, quotes: true }); // Should show with hyperlink assert.ok(formatted.includes("\x1b]8;;https://example.com/\x1b\\")); assert.ok(formatted.includes("")); assert.ok(formatted.includes("\x1b]8;;\x1b\\")); assert.equal( formatted, "Visit \x1b]8;;https://example.com/\x1b\\\x1b]8;;\x1b\\", ); }); it("should apply resetSuffix with url term", () => { const msg: Message = [ { type: "text", text: "Visit " }, { type: "url", url: new URL("https://example.com") }, { type: "text", text: " now" }, ]; const formatted = formatMessage(msg, { colors: { resetSuffix: "\x1b[2m" }, quotes: false, }); assert.ok(formatted.includes("\x1b]8;;\x1b\\\x1b[2m")); assert.equal( formatted, "Visit \x1b]8;;https://example.com/\x1b\\https://example.com/\x1b]8;;\x1b\\\x1b[2m now", ); }); it("should work with message template and url()", () => { const msg = message`Visit ${url("https://example.com")} for details.`; const formatted = formatMessage(msg, { quotes: true }); assert.equal(formatted, "Visit for details."); }); it("should handle multiple urls in one message", () => { const msg = message`Check ${url("https://docs.example.com")} and ${url( "https://github.com/example", )}.`; const formatted = formatMessage(msg, { colors: false, quotes: true }); assert.ok(formatted.includes("")); assert.ok(formatted.includes("")); }); it("should work with mixed message components", () => { const msg = message`Run ${commandLine("myapp --help")} or visit ${url( "https://example.com/help", )} for ${metavar("INFO")}.`; const formatted = formatMessage(msg, { quotes: true }); assert.ok(formatted.includes("`myapp --help`")); assert.ok(formatted.includes("")); assert.ok(formatted.includes("`INFO`")); }); it("should handle url with query parameters", () => { const msg: Message = [ { type: "url", url: new URL("https://example.com?foo=bar") }, ]; const formatted = formatMessage(msg, { quotes: false }); assert.ok(formatted.includes("foo=bar")); }); it("should handle url with hash", () => { const msg: Message = [ { type: "url", url: new URL("https://example.com/page#section") }, ]; const formatted = formatMessage(msg, { quotes: true }); assert.equal(formatted, ""); }); it("should handle very long URLs with maxWidth", () => { const msg: Message = [ { type: "text", text: "Visit " }, { type: "url", url: new URL( "https://example.com/very/long/path/that/exceeds/the/maximum/width", ), }, { type: "text", text: " for more information" }, ]; const formatted = formatMessage(msg, { quotes: false, maxWidth: 40 }); assert.ok(formatted.includes("\n")); }); it("should calculate width based on display text, not ANSI codes", () => { const msg: Message = [{ type: "url", url: new URL("https://example.com") }]; const formatted = formatMessage(msg, { colors: true, quotes: false }); // The ANSI codes are long, but display width should be ~21 chars (https://example.com/) // Not the full length including escape sequences assert.ok(formatted.length > 50); // Has ANSI codes // But wrapping should be based on display text length only }); it("should work with message template and link() alias", () => { const msg = message`Visit ${link("https://example.com")} for details.`; const formatted = formatMessage(msg, { quotes: true }); assert.equal(formatted, "Visit for details."); }); it("link() and url() should produce identical output", () => { const msgWithUrl = message`Check ${url("https://example.com")}.`; const msgWithLink = message`Check ${link("https://example.com")}.`; const formattedUrl = formatMessage(msgWithUrl, { quotes: true }); const formattedLink = formatMessage(msgWithLink, { quotes: true }); assert.equal(formattedUrl, formattedLink); }); }); describe("property-based tests", () => { const propertyParameters = { numRuns: 150 } as const; const safeStringArbitrary = fc .string({ minLength: 0, maxLength: 20 }) .filter((value: string) => !value.includes("\x1b")); const safeSingleLineStringArbitrary = safeStringArbitrary.filter( (value: string) => !value.includes("\n"), ); const nonEmptySingleLineStringArbitrary = safeSingleLineStringArbitrary.filter((value: string) => value.length > 0); const optionNameArbitrary = safeSingleLineStringArbitrary .filter((value: string) => value.length > 0) .map((value: string) => `--${value}`); const stripAnsi = (value: string): string => { let output = ""; for (let i = 0; i < value.length; i++) { if (value.charCodeAt(i) === 0x1b && value[i + 1] === "[") { i += 2; while (i < value.length) { const code = value.charCodeAt(i); if (code >= 0x40 && code <= 0x7e) { break; } i++; } continue; } output += value[i]; } return output; }; it("formatMessage colors should preserve plain-text semantics", () => { const messageTermArbitrary: fc.Arbitrary = fc.oneof( safeStringArbitrary.map((textValue: string) => ({ type: "text" as const, text: textValue, })), optionNameArbitrary.map((name: string) => ({ type: "optionName" as const, optionName: name, })), fc .uniqueArray(optionNameArbitrary, { minLength: 1, maxLength: 3 }) .map((names: readonly string[]) => ({ type: "optionNames" as const, optionNames: names, })), fc .constantFrom<"ARG" | "FILE" | "PATH" | "VALUE">( "ARG", "FILE", "PATH", "VALUE", ) .map((name: "ARG" | "FILE" | "PATH" | "VALUE") => ({ type: "metavar" as const, metavar: name, })), safeSingleLineStringArbitrary.map((singleValue: string) => ({ type: "value" as const, value: singleValue, })), fc .array(safeSingleLineStringArbitrary, { minLength: 0, maxLength: 4 }) .map((manyValues: readonly string[]) => ({ type: "values" as const, values: manyValues, })), safeSingleLineStringArbitrary.map((name: string) => ({ type: "envVar" as const, envVar: name, })), safeSingleLineStringArbitrary.map((cmd: string) => ({ type: "commandLine" as const, commandLine: cmd, })), fc.constant({ type: "lineBreak" as const }), ); fc.assert( fc.property( fc.array(messageTermArbitrary, { minLength: 0, maxLength: 20 }), fc.boolean(), (msg: readonly MessageTerm[], quotes: boolean) => { const plain = formatMessage(msg, { colors: false, quotes }); const colored = formatMessage(msg, { colors: true, quotes }); assert.equal(stripAnsi(colored), plain); }, ), propertyParameters, ); }); it("valueSet should preserve value order in value terms", () => { fc.assert( fc.property( fc.array(nonEmptySingleLineStringArbitrary, { minLength: 1, maxLength: 8, }), fc.option(fc.constantFrom("en", "ko", "fr"), { nil: undefined }), fc.constantFrom<"conjunction" | "disjunction" | "unit">( "conjunction", "disjunction", "unit", ), fc.constantFrom<"long" | "short" | "narrow">("long", "short", "narrow"), ( valuesInput: readonly string[], locale: string | undefined, type: "conjunction" | "disjunction" | "unit", style: "long" | "short" | "narrow", ) => { const msg = valueSet(valuesInput, { fallback: "", locale, type, style, }); const extractedValues = msg .filter((term) => term.type === "value") .map((term) => term.value); assert.deepEqual(extractedValues, valuesInput); assert.ok(msg.length > 0); }, ), propertyParameters, ); }); // https://github.com/dahlia/optique/issues/1003 it("should never start an automatically wrapped line with whitespace", () => { const wordArbitrary = fc.stringMatching(/^[a-z]{1,8}$/); const termArbitrary = fc.record({ leadingSpace: fc.boolean(), trailingSpace: fc.boolean(), words: fc.array(wordArbitrary, { minLength: 1, maxLength: 4 }), }); fc.assert( fc.property( fc.array(termArbitrary, { minLength: 1, maxLength: 8 }), fc.integer({ min: 1, max: 30 }), (terms, maxWidth) => { const msg: Message = terms.map((term, i) => text( `${term.leadingSpace && i > 0 ? " " : ""}${term.words.join(" ")}${ term.trailingSpace ? " " : "" }`, ), ); const formatted = formatMessage(msg, { maxWidth }); for (const line of formatted.split("\n")) { assert.ok(!/^\s/.test(line), JSON.stringify(formatted)); } assert.equal( formatted.replace(/\s/g, ""), msg .map((term) => (term.type === "text" ? term.text : "")) .join("") .replace(/\s/g, ""), ); }, ), propertyParameters, ); }); }); describe("cloneMessageTerm", () => { it("should clone a text term", () => { const term = text("hello"); const cloned = cloneMessageTerm(term); assert.deepEqual(cloned, term); assert.notEqual(cloned, term); }); it("should clone an optionNames term with array copy", () => { const term = optionNames(["--foo", "--bar"]); const cloned = cloneMessageTerm(term); assert.deepEqual(cloned, term); assert.notEqual(cloned, term); if (cloned.type === "optionNames" && term.type === "optionNames") { assert.notEqual(cloned.optionNames, term.optionNames); } }); it("should clone a values term with array copy", () => { const term = values(["a", "b"]); const cloned = cloneMessageTerm(term); assert.deepEqual(cloned, term); assert.notEqual(cloned, term); if (cloned.type === "values" && term.type === "values") { assert.notEqual(cloned.values, term.values); } }); it("should clone a url term with a new URL object", () => { const term = url("https://example.com/path"); const cloned = cloneMessageTerm(term); assert.deepEqual(cloned, term); assert.notEqual(cloned, term); if (cloned.type === "url" && term.type === "url") { assert.notEqual(cloned.url, term.url); assert.equal(cloned.url.href, term.url.href); } }); }); describe("cloneMessage", () => { it("should deep-clone a message with mixed term types", () => { const msg: Message = [ text("See "), url("https://example.com"), text(" for details"), ]; const cloned = cloneMessage(msg); assert.deepEqual(cloned, msg); assert.notEqual(cloned, msg); for (let i = 0; i < msg.length; i++) { assert.notEqual(cloned[i], msg[i]); } }); });