diff --git a/AGENTS.md b/AGENTS.md index b97b6b9..3eaed2d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -5,7 +5,7 @@ Compact YAML / TOML / JSONC / JSON5 / INI / JSON parser + serializer. Zero runti ## Layout - `src/.ts` — one file per format, each exports `parse` / `stringify` + its option types. Thin wrapper over an upstream lib. -- `src/_format.ts` — style preservation. `storeFormat()` attaches a non-enumerable `Symbol.for("__confbox_fmt__")` (indent sample + leading/trailing whitespace) on parse; `getFormat()` reads it back on stringify. +- `src/_format.ts` — style preservation. `storeFormat()` attaches a non-enumerable `Symbol.for("__confbox_fmt__")` (indent sample + leading/trailing whitespace + line ending) on parse; `getFormat()` reads it back on stringify. - `src/index.ts` — re-exports only. `test/index.test.ts` + `test/fixtures.mjs`, `test/bench.mjs`. Upstream libs: yaml→`js-yaml`, toml→`smol-toml`, jsonc→`jsonc-parser`, json5→`json5` (deep imports `json5/lib/*`), ini→`ini`, json→native. diff --git a/src/_format.ts b/src/_format.ts index cca5c4a..0647380 100644 --- a/src/_format.ts +++ b/src/_format.ts @@ -4,6 +4,8 @@ export interface FormatInfo { indent?: string | number; sample?: string; whiteSpace?: { start: string; end: string }; + /** Line ending of the original text, only stored when it is not `\n`. */ + newline?: "\r\n"; } export interface FormatOptions { @@ -84,9 +86,23 @@ export function detectFormat(text: string, opts: FormatOptions = {}): FormatInfo indent: opts.indent, sample, whiteSpace, + newline: detectNewline(text), }; } +/** Returns `"\r\n"` when the first line of `text` ends with CRLF. */ +function detectNewline(text: string): "\r\n" | undefined { + const lf = text.indexOf("\n"); + return lf > 0 && text[lf - 1] === "\r" ? "\r\n" : undefined; +} + +/** + * Converts the line endings of serializer output (which always uses `\n`) to `newline`. + */ +export function withNewline(str: string, newline: string): string { + return newline === "\n" ? str : str.replace(/\r?\n/g, newline); +} + export function storeFormat(text: string, obj: any, opts?: FormatOptions): void { if (!obj || typeof obj !== "object") { return; @@ -106,9 +122,10 @@ export function getFormat( ): { indent: string | number | undefined; whitespace: { start: string; end: string }; + newline: string; } { if (!obj || typeof obj !== "object" || !(ftmSymbol in obj)) { - return { indent: opts?.indent ?? 2, whitespace: { start: "", end: "" } }; + return { indent: opts?.indent ?? 2, whitespace: { start: "", end: "" }, newline: "\n" }; } const format = obj[ftmSymbol] as FormatInfo; // `0` and `""` are valid explicit requests for minified output, so only `undefined` falls back @@ -119,5 +136,6 @@ export function getFormat( return { indent, whitespace: format.whiteSpace || { start: "", end: "" }, + newline: format.newline || "\n", }; } diff --git a/src/json.ts b/src/json.ts index cf3a2b6..b1e8886 100644 --- a/src/json.ts +++ b/src/json.ts @@ -1,4 +1,4 @@ -import { getFormat, storeFormat, stripBOM, type FormatOptions } from "./_format"; +import { getFormat, storeFormat, stripBOM, type FormatOptions, withNewline } from "./_format"; /** * Converts a [JSON](https://www.json.org/json-en.html) string into an object. @@ -19,7 +19,7 @@ export function parseJSON(text: string, options?: JSONParseOptions) export function stringifyJSON(value: any, options?: JSONStringifyOptions): string { const format = getFormat(value, options); const str = JSON.stringify(value, options?.replacer, format.indent); - return format.whitespace.start + str + format.whitespace.end; + return format.whitespace.start + withNewline(str, format.newline) + format.whitespace.end; } // -- types -- diff --git a/src/json5.ts b/src/json5.ts index ad6b5b6..fe3d962 100644 --- a/src/json5.ts +++ b/src/json5.ts @@ -1,4 +1,4 @@ -import { getFormat, storeFormat, stripBOM, type FormatOptions } from "./_format"; +import { getFormat, storeFormat, stripBOM, type FormatOptions, withNewline } from "./_format"; import parse from "json5/lib/parse.js"; import stringify from "json5/lib/stringify"; @@ -28,7 +28,7 @@ export function parseJSON5(text: string, options?: JSON5ParseOption export function stringifyJSON5(value: any, options?: JSON5StringifyOptions): string { const format = getFormat(value, options); const str = stringify(value, options?.replacer, format.indent); - return format.whitespace.start + str + format.whitespace.end; + return format.whitespace.start + withNewline(str, format.newline) + format.whitespace.end; } // --- Types --- diff --git a/src/toml.ts b/src/toml.ts index 823662c..0593696 100644 --- a/src/toml.ts +++ b/src/toml.ts @@ -1,4 +1,4 @@ -import { getFormat, storeFormat, stripBOM } from "./_format"; +import { getFormat, storeFormat, stripBOM, withNewline } from "./_format"; import { parse, stringify } from "smol-toml"; // Source: https://github.com/squirrelchat/smol-toml @@ -30,5 +30,5 @@ export function parseTOML(text: string): T { export function stringifyTOML(value: any): string { const format = getFormat(value, { preserveIndentation: false }); const str = stringify(value); - return format.whitespace.start + str + format.whitespace.end; + return format.whitespace.start + withNewline(str, format.newline) + format.whitespace.end; } diff --git a/src/yaml.ts b/src/yaml.ts index a352815..b2673f6 100644 --- a/src/yaml.ts +++ b/src/yaml.ts @@ -1,5 +1,5 @@ import { load, dump, YAMLException } from "js-yaml"; -import { type FormatOptions, getFormat, storeFormat, stripBOM } from "./_format"; +import { type FormatOptions, getFormat, storeFormat, stripBOM, withNewline } from "./_format"; // Source: https://github.com/nodeca/js-yaml // Types: https://github.com/nodeca/js-yaml/blob/master/dist/js-yaml.d.ts @@ -45,7 +45,7 @@ export function stringifyYAML(value: any, options?: YAMLStringifyOptions): strin // A flat document has no indentation to detect, but YAML needs a non-zero indent for nesting. indent: options?.indent || detectedIndent || 2, }); - return format.whitespace.start + str.trim() + format.whitespace.end; + return format.whitespace.start + withNewline(str.trim(), format.newline) + format.whitespace.end; } /** diff --git a/test/index.test.ts b/test/index.test.ts index f85b372..f5e96b2 100644 --- a/test/index.test.ts +++ b/test/index.test.ts @@ -141,6 +141,35 @@ describe("confbox", () => { }); }); + describe("line endings", () => { + const roundTrip = { + json: [confbox.parseJSON, confbox.stringifyJSON], + jsonc: [confbox.parseJSONC, confbox.stringifyJSONC], + json5: [confbox.parseJSON5, confbox.stringifyJSON5], + yaml: [confbox.parseYAML, confbox.stringifyYAML], + toml: [confbox.parseTOML, confbox.stringifyTOML], + } as const; + + for (const [format, [parse, stringify]] of Object.entries(roundTrip)) { + const fixture = (fixtures as Record)[format].trim() + "\n"; + const crlf = fixture.replaceAll("\n", "\r\n"); + + it(`${format} keeps CRLF line endings when stringifying back`, () => { + const output = stringify(parse(crlf)); + expect(output).toBe(stringify(parse(fixture)).replaceAll("\n", "\r\n")); + expect(output.replaceAll("\r\n", "")).not.toContain("\n"); + }); + + it(`${format} keeps LF line endings when stringifying back`, () => { + expect(stringify(parse(fixture))).not.toContain("\r"); + }); + } + + it("uses LF for values that were not parsed", () => { + expect(confbox.stringifyJSON({ a: [1, 2] })).not.toContain("\r"); + }); + }); + describe("indent", () => { // `stringifyJSON({ a: 1 }, { indent: 0 })` has always minified, matching `JSON.stringify`. // On a value from `parse*` the stored format used to win because `0` is falsy, so the same