fix(cli): bound streamed pretty JSON indentation (#12185)

This commit is contained in:
ShuaixinHuang authored and GitHub committed 2026-11-19 00:08:46 -05:00
1 parent 3fae997886
commit 6bbba76e8a
2 files changed
+33 -6

No files matched your search

+14
View File
@@ -87,6 +87,20 @@ describe("iterative JSON encoding", () => {
);
});
it("emits deep pretty JSON indentation in bounded parts", () => {
const depth = 10_000;
let value: unknown = 0;
for (let index = 0; index < depth; index += 1) value = [value];
let characters = 0;
let largestPart = 0;
for (const part of jsonParts(value, true)) {
characters += part.length;
largestPart = Math.max(largestPart, part.length);
}
expect(characters).toBe(2 * depth * depth + 4 * depth + 1);
expect(largestPart).toBeLessThanOrEqual(16 * 1024);
});
it("yields bounded parts before reading later members", () => {
const value: Record<string, unknown> = { first: "x".repeat(100_000) };
Object.defineProperty(value, "later", {
+19 -6
View File
@@ -114,9 +114,7 @@ function* encodeString(value: string): Generator<string> {
/** Encoded text accumulated before it is yielded as one part. */
const PART_CHARACTERS = 16 * 1024;
const indentation: string[] = [];
const indent = (depth: number): string =>
(indentation[depth] ??= `\n${" ".repeat(depth)}`);
const INDENT_SPACES = " ".repeat(PART_CHARACTERS);
interface ContainerFrame {
readonly value: object;
@@ -226,15 +224,30 @@ function* encodeValue(
const frame = stack.at(-1);
if (frame === undefined) break;
const member = nextMember(frame);
if (member !== undefined && frame.written > 0) buffer += ",";
if (pretty && (member !== undefined || frame.written > 0)) {
if (buffer.length === PART_CHARACTERS) {
yield buffer;
buffer = "";
}
buffer += "\n";
let spaces = 2 * (frame.depth + (member === undefined ? 0 : 1));
// Deep indentation can itself fill several parts. Reuse one whitespace
// block so neither the string allocation nor its retention grows with depth.
while (buffer.length + spaces >= PART_CHARACTERS) {
const available = PART_CHARACTERS - buffer.length;
yield buffer + INDENT_SPACES.slice(0, available);
buffer = "";
spaces -= available;
}
buffer += INDENT_SPACES.slice(0, spaces);
}
if (member === undefined) {
if (pretty && frame.written > 0) buffer += indent(frame.depth);
buffer += frame.array ? "]" : "}";
ancestors.delete(frame.value);
stack.pop();
continue;
}
if (frame.written > 0) buffer += ",";
if (pretty) buffer += indent(frame.depth + 1);
if (member.key !== undefined) {
const key = scalarText(member.key);
if (key !== undefined) buffer += key;