perf(json): eliminate per-object generators and defineProperty overhead in jsonValue (#13444)

* perf(json): eliminate per-object generators and defineProperty overhead in jsonValue

* style(json): format the depth traversal
This commit is contained in:
morluto authored and GitHub committed 2026-11-22 10:28:26 -05:00
1 parent d8a0e06c61
commit 1e6880cef7
2 files changed
+91 -33

No files matched your search

+19
View File
@@ -6,6 +6,7 @@ import {
equalJsonValues,
jsonObjectSchema,
ownedJsonObjectSchema,
jsonValueExceedsDepth,
jsonValueSchema,
jsonValueValidationIssue,
jsonValueValidationSteps,
@@ -96,6 +97,24 @@ describe("jsonValueSchema depth bound", () => {
expect(jsonValueSchema.safeParse(deepObject(MAX_JSON_DEPTH)).success).toBe(
true,
);
expect(jsonValueExceedsDepth({}, 0)).toBe(false);
expect(jsonValueExceedsDepth([], 0)).toBe(false);
expect(jsonValueExceedsDepth({ a: 1 }, 0)).toBe(true);
expect(jsonValueExceedsDepth([1], 0)).toBe(true);
expect(jsonValueExceedsDepth({ a: [1] }, 2)).toBe(false);
expect(jsonValueExceedsDepth({ a: [1] }, 1)).toBe(true);
expect(
jsonValueExceedsDepth(
deepObject(MAX_JSON_DEPTH) as Record<string, never>,
MAX_JSON_DEPTH,
),
).toBe(false);
expect(
jsonValueExceedsDepth(
deepObject(MAX_JSON_DEPTH + 1) as Record<string, never>,
MAX_JSON_DEPTH,
),
).toBe(true);
});
it("rejects values nested past the maximum depth without throwing", () => {
+72 -33
View File
@@ -60,30 +60,60 @@ export const jsonValueValidationIssue = (root: unknown): string | undefined => {
}
};
function* ownEnumerableKeys(value: Record<string, unknown>): Generator<string> {
for (const key in value) if (Object.hasOwn(value, key)) yield key;
}
function* jsonObjectValues(
record: Record<string, JsonValue>,
): Generator<JsonValue> {
for (const key of ownEnumerableKeys(record)) yield record[key]!;
}
/** Check a validated value's nesting without queuing whole containers. */
export const jsonValueExceedsDepth = (
root: JsonValue,
limit: number,
): boolean => {
const levels: Iterator<JsonValue>[] = [[root].values()];
for (let level = levels.at(-1); level !== undefined; level = levels.at(-1)) {
const next = level.next();
if (next.done === true) levels.pop();
else if (levels.length - 1 > limit) return true;
else if (Array.isArray(next.value)) levels.push(next.value.values());
else if (isRecord(next.value)) levels.push(jsonObjectValues(next.value));
type DepthFrame =
| {
readonly kind: "array";
readonly value: readonly JsonValue[];
index: number;
}
| {
readonly kind: "object";
readonly value: Record<string, JsonValue>;
readonly keys: readonly string[];
index: number;
};
const frames: DepthFrame[] = [];
let value: JsonValue = root;
let depth = 0;
let inspect = true;
for (;;) {
if (inspect) {
if (depth > limit) return true;
if (Array.isArray(value)) {
if (value.length > 0) frames.push({ kind: "array", value, index: 0 });
} else if (isRecord(value)) {
const keys = Object.keys(value);
if (keys.length > 0)
frames.push({ kind: "object", value, keys, index: 0 });
}
inspect = false;
continue;
}
const frame = frames[frames.length - 1];
if (frame === undefined) return false;
if (frame.kind === "array") {
if (frame.index >= frame.value.length) {
frames.pop();
continue;
}
value = frame.value[frame.index++]!;
depth = frames.length;
inspect = true;
continue;
}
if (frame.index >= frame.keys.length) {
frames.pop();
continue;
}
value = frame.value[frame.keys[frame.index++]!]!;
depth = frames.length;
inspect = true;
}
return false;
};
/** Validate JSON in bounded steps; cache only authenticated immutable roots. */
@@ -111,7 +141,8 @@ export function* jsonValueValidationSteps(
readonly kind: "object";
readonly value: Record<string, unknown>;
readonly depth: number;
readonly keys: Generator<string>;
readonly keys: readonly string[];
index: number;
};
const pending: Frame[] = [];
let value = root;
@@ -159,7 +190,8 @@ export function* jsonValueValidationSteps(
kind: "object",
value,
depth,
keys: ownEnumerableKeys(value),
keys: Object.keys(value),
index: 0,
});
inspect = false;
} else return finish("Invalid JSON value");
@@ -185,12 +217,12 @@ export function* jsonValueValidationSteps(
continue;
}
const next = frame.keys.next();
if (next.done) {
if (frame.index >= frame.keys.length) {
pending.pop();
continue;
}
const descriptor = Object.getOwnPropertyDescriptor(frame.value, next.value);
const key = frame.keys[frame.index++]!;
const descriptor = Object.getOwnPropertyDescriptor(frame.value, key);
if (descriptor?.enumerable !== true) continue;
if (!Object.hasOwn(descriptor, "value"))
return finish("JSON objects cannot contain accessors");
@@ -208,20 +240,27 @@ const copyJsonValue = (
if (borrowImmutable && isImmutableJsonSnapshot(immutableCandidate))
return value;
if (Array.isArray(value)) {
const copy: JsonValue[] = [];
for (let index = 0; index < value.length; index += 1)
copy.push(copyJsonValue(value[index]!, borrowImmutable));
const length = value.length;
const copy = new Array<JsonValue>(length);
for (let index = 0; index < length; index += 1)
copy[index] = copyJsonValue(value[index]!, borrowImmutable);
return copy;
}
if (value !== null && typeof value === "object") {
const copy: Record<string, JsonValue> = {};
for (const key of ownEnumerableKeys(value))
Object.defineProperty(copy, key, {
value: copyJsonValue(value[key]!, borrowImmutable),
enumerable: true,
configurable: true,
writable: true,
});
const keys = Object.keys(value);
for (let index = 0; index < keys.length; index += 1) {
const key = keys[index]!;
const copied = copyJsonValue(value[key]!, borrowImmutable);
if (key === "__proto__")
Object.defineProperty(copy, key, {
value: copied,
enumerable: true,
configurable: true,
writable: true,
});
else copy[key] = copied;
}
return copy;
}
return value;