Skip to content
Merged
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
11 changes: 11 additions & 0 deletions packages/protobuf-test/src/serialization-errors.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,17 @@ void suite("serialization errors", () => {
binaryErr:
/^cannot encode field spec.ScalarValuesMessage.uint64_field to binary: invalid uint64: -1$/,
},
{
name: "uint64 field Infinity",
val(m) {
// @ts-expect-error TS2322: Type number is not assignable to type bigint
m.uint64Field = Number.POSITIVE_INFINITY;
},
jsonErr:
/^cannot encode field spec.ScalarValuesMessage.uint64_field to JSON: expected bigint \(uint64\): Infinity out of range/,
binaryErr:
/^cannot encode field spec.ScalarValuesMessage.uint64_field to binary: The number Infinity cannot be converted to a BigInt because it is not an integer$/,
},
{
name: "bytes field true",
val(m) {
Expand Down
14 changes: 9 additions & 5 deletions packages/protobuf/src/to-json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -369,12 +369,16 @@ function scalarToJson(
case ScalarType.INT64:
case ScalarType.SFIXED64:
case ScalarType.SINT64:
if (typeof value != "bigint" && typeof value != "string") {
throw new Error(
`cannot encode ${field} to JSON: ${checkField(field, value)?.message}`,
);
if (
typeof value == "bigint" ||
typeof value == "string" ||
(typeof value == "number" && Number.isInteger(value))
) {
return value.toString();
}
return value.toString();
throw new Error(
`cannot encode ${field} to JSON: ${checkField(field, value)?.message}`,
);

// bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.
// Either standard or URL-safe base64 encoding with/without paddings are accepted.
Expand Down