Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,22 @@ export function destr<T = unknown>(value: any, options: Options = {}): T {
}
return JSON.parse(value, jsonParseTransform);
}
return JSON.parse(value);
const result = JSON.parse(value);
// Guard against silent precision loss for integers beyond MAX_SAFE_INTEGER.
// e.g. '9007199254740993' would silently become 9007199254740992.
if (
typeof result === "number" &&
Number.isInteger(result) &&
!Number.isSafeInteger(result)
) {
if (options.strict) {
throw new SyntaxError(
`[destr] Loss of precision for large integer string: "${value}"`,
);
}
return value as T;
}
return result;
} catch (error) {
if (options.strict) {
throw error;
Expand Down
20 changes: 20 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,4 +197,24 @@ describe("destr", () => {
expect(destr(testCase.input)).toStrictEqual(testCase.output);
}
});

it("returns large integer strings as-is to prevent silent precision loss (#152)", () => {
// Numbers beyond Number.MAX_SAFE_INTEGER cannot be reliably represented
// as JS floats — destr must return the original string to avoid corruption.
const testCases = [
"9007199254740992", // MAX_SAFE_INTEGER + 1 (2^53)
"9007199254740993", // exact value from issue report → would silently become 9007199254740992
"-9007199254740993",
];

for (const input of testCases) {
expect(destr(input)).toStrictEqual(input);
}
});

it("throws on large integer strings in strict mode (#152)", () => {
expect(() => safeDestr("9007199254740993")).toThrowError(
"[destr] Loss of precision for large integer string",
);
});
});