| 1 |
// Copyright 2021-2026 Buf Technologies, Inc. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// |
| 7 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 |
// |
| 9 |
// Unless required by applicable law or agreed to in writing, software |
| 10 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 |
// See the License for the specific language governing permissions and |
| 13 |
// limitations under the License. |
| 14 |
import { BinaryWriter, WireType } from "./wire/binary-encoding.js"; |
| 15 |
import { ScalarType } from "./descriptors.js"; |
| 16 |
import { FieldError } from "./reflect/error.js"; |
| 17 |
import { unsafeLocal } from "./reflect/unsafe.js"; |
| 18 |
import { localMessageMapper } from "./reflect/message.js"; |
| 19 |
import { protoInt64 } from "./proto-int64.js"; |
| 20 |
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.IMPLICIT: const $name = $number; |
| 21 |
const IMPLICIT = 2; |
| 22 |
// bootstrap-inject google.protobuf.FeatureSet.FieldPresence.LEGACY_REQUIRED: const $name = $number; |
| 23 |
const LEGACY_REQUIRED = 3; |
| 24 |
// Default options for serializing binary data. |
| 25 |
const writeDefaults = { |
| 26 |
writeUnknownFields: true, |
| 27 |
}; |
| 28 |
function makeWriteOptions(options) { |
| 29 |
return options ? Object.assign(Object.assign({}, writeDefaults), options) : writeDefaults; |
| 30 |
} |
| 31 |
export function toBinary(schema, message, options) { |
| 32 |
const writer = new BinaryWriter(); |
| 33 |
compiledWriter(schema)(writer, makeWriteOptions(options), message); |
| 34 |
return writer.finish(); |
| 35 |
} |
| 36 |
const compiledWriters = new WeakMap(); |
| 37 |
/** |
| 38 |
* Return the compiled encoder for a message, compiling it on first use. |
| 39 |
*/ |
| 40 |
function compiledWriter(desc) { |
| 41 |
let compiled = compiledWriters.get(desc); |
| 42 |
if (compiled === undefined) { |
| 43 |
compiled = compileMessage(desc); |
| 44 |
} |
| 45 |
return compiled; |
| 46 |
} |
| 47 |
function compileMessage(desc) { |
| 48 |
const typeName = desc.typeName; |
| 49 |
const sortedFields = desc.fields.concat().sort((a, b) => a.number - b.number); |
| 50 |
// The field reported in ForeignFieldError. |
| 51 |
const foreignField = sortedFields[0]; |
| 52 |
const fieldWriters = []; |
| 53 |
const compiled = (writer, opts, message) => { |
| 54 |
if (message.$typeName !== typeName && foreignField !== undefined) { |
| 55 |
throw new FieldError(foreignField, `cannot use ${foreignField} with message ${message.$typeName}`, "ForeignFieldError"); |
| 56 |
} |
| 57 |
for (let i = 0; i < fieldWriters.length; i++) { |
| 58 |
fieldWriters[i](writer, opts, message); |
| 59 |
} |
| 60 |
const unknown = message.$unknown; |
| 61 |
if (unknown !== undefined && opts.writeUnknownFields) { |
| 62 |
for (let i = 0; i < unknown.length; i++) { |
| 63 |
const { no, wireType, data } = unknown[i]; |
| 64 |
writer.tag(no, wireType).raw(data); |
| 65 |
} |
| 66 |
} |
| 67 |
}; |
| 68 |
// Register before compiling fields, so that recursive message types |
| 69 |
// resolve to this instance instead of compiling endlessly. |
| 70 |
compiledWriters.set(desc, compiled); |
| 71 |
for (const field of sortedFields) { |
| 72 |
fieldWriters.push(compileField(field)); |
| 73 |
} |
| 74 |
return compiled; |
| 75 |
} |
| 76 |
function compileField(field) { |
| 77 |
switch (field.fieldKind) { |
| 78 |
case "message": |
| 79 |
case "scalar": |
| 80 |
case "enum": |
| 81 |
return compileSingularField(field); |
| 82 |
case "list": |
| 83 |
return compileListField(field); |
| 84 |
case "map": |
| 85 |
return compileMapField(field); |
| 86 |
} |
| 87 |
} |
| 88 |
/** |
| 89 |
* Compile an encoder for a singular field: the presence check, and the |
| 90 |
* value encoder. |
| 91 |
*/ |
| 92 |
function compileSingularField(field) { |
| 93 |
const writeValue = compileSingularValue(field); |
| 94 |
const localName = field.localName; |
| 95 |
if (field.oneof) { |
| 96 |
const oneofLocalName = field.oneof.localName; |
| 97 |
return (writer, opts, message) => { |
| 98 |
const oneof = message[oneofLocalName]; |
| 99 |
if (oneof.case === localName) { |
| 100 |
writeValue(writer, opts, oneof.value); |
| 101 |
} |
| 102 |
}; |
| 103 |
} |
| 104 |
if (field.presence != IMPLICIT) { |
| 105 |
const requiredError = field.presence == LEGACY_REQUIRED |
| 106 |
? `cannot encode ${field} to binary: required field not set` |
| 107 |
: undefined; |
| 108 |
return (writer, opts, message) => { |
| 109 |
const value = message[localName]; |
| 110 |
// Fields with explicit presence have properties on the prototype |
| 111 |
// chain for default / zero values (except for proto3). |
| 112 |
if (value !== undefined && |
| 113 |
Object.prototype.hasOwnProperty.call(message, localName)) { |
| 114 |
writeValue(writer, opts, value); |
| 115 |
} |
| 116 |
else if (requiredError !== undefined) { |
| 117 |
throw new Error(requiredError); |
| 118 |
} |
| 119 |
}; |
| 120 |
} |
| 121 |
// Implicit presence: the field is set when the value is not the zero |
| 122 |
// value. The check is inlined per type, see isScalarZeroValue. |
| 123 |
if (field.fieldKind == "enum") { |
| 124 |
const zero = field.enum.values[0].number; |
| 125 |
return (writer, opts, message) => { |
| 126 |
const value = message[localName]; |
| 127 |
if (value !== zero) { |
| 128 |
writeValue(writer, opts, value); |
| 129 |
} |
| 130 |
}; |
| 131 |
} |
| 132 |
switch (field.scalar) { |
| 133 |
case ScalarType.BOOL: |
| 134 |
return (writer, opts, message) => { |
| 135 |
const value = message[localName]; |
| 136 |
if (value !== false) { |
| 137 |
writeValue(writer, opts, value); |
| 138 |
} |
| 139 |
}; |
| 140 |
case ScalarType.STRING: |
| 141 |
return (writer, opts, message) => { |
| 142 |
const value = message[localName]; |
| 143 |
if (value !== "") { |
| 144 |
writeValue(writer, opts, value); |
| 145 |
} |
| 146 |
}; |
| 147 |
case ScalarType.BYTES: |
| 148 |
return (writer, opts, message) => { |
| 149 |
const value = message[localName]; |
| 150 |
if (!(value instanceof Uint8Array) || value.byteLength > 0) { |
| 151 |
writeValue(writer, opts, value); |
| 152 |
} |
| 153 |
}; |
| 154 |
case ScalarType.DOUBLE: |
| 155 |
case ScalarType.FLOAT: |
| 156 |
return (writer, opts, message) => { |
| 157 |
const value = message[localName]; |
| 158 |
// Object.is distinguishes -0 from 0. |
| 159 |
if (!Object.is(value, 0)) { |
| 160 |
writeValue(writer, opts, value); |
| 161 |
} |
| 162 |
}; |
| 163 |
default: |
| 164 |
return (writer, opts, message) => { |
| 165 |
const value = message[localName]; |
| 166 |
// Loose comparison matches 0n, 0 and "0". |
| 167 |
if (value != 0) { |
| 168 |
writeValue(writer, opts, value); |
| 169 |
} |
| 170 |
}; |
| 171 |
} |
| 172 |
} |
| 173 |
/** |
| 174 |
* Compile an encoder for the value of a singular field, including the tag. |
| 175 |
*/ |
| 176 |
function compileSingularValue(field) { |
| 177 |
switch (field.fieldKind) { |
| 178 |
case "message": { |
| 179 |
const { toMessage } = localMessageMapper(field); |
| 180 |
const writeChild = compileChildWriter(field); |
| 181 |
return (writer, opts, value) => { |
| 182 |
writeChild(writer, opts, toMessage(value)); |
| 183 |
}; |
| 184 |
} |
| 185 |
case "scalar": |
| 186 |
case "enum": { |
| 187 |
const scalarType = field.fieldKind == "enum" ? ScalarType.INT32 : field.scalar; |
| 188 |
const fieldNo = field.number; |
| 189 |
const wireType = writeTypeOfScalar(scalarType); |
| 190 |
const writeScalar = compileScalarValue(scalarType, field.parent.typeName, field.name); |
| 191 |
return (writer, opts, value) => { |
| 192 |
writer.tag(fieldNo, wireType); |
| 193 |
writeScalar(writer, value); |
| 194 |
}; |
| 195 |
} |
| 196 |
} |
| 197 |
} |
| 198 |
function compileListField(field) { |
| 199 |
const localName = field.localName; |
| 200 |
const fieldNo = field.number; |
| 201 |
switch (field.listKind) { |
| 202 |
case "message": { |
| 203 |
const { toMessage } = localMessageMapper(field); |
| 204 |
const writeChild = compileChildWriter(field); |
| 205 |
return (writer, opts, message) => { |
| 206 |
const items = message[localName]; |
| 207 |
for (let i = 0; i < items.length; i++) { |
| 208 |
writeChild(writer, opts, toMessage(items[i])); |
| 209 |
} |
| 210 |
}; |
| 211 |
} |
| 212 |
case "scalar": |
| 213 |
case "enum": { |
| 214 |
const scalarType = field.listKind == "enum" ? ScalarType.INT32 : field.scalar; |
| 215 |
const writeScalar = compileScalarValue(scalarType, field.parent.typeName, field.name); |
| 216 |
if (field.packed) { |
| 217 |
return (writer, opts, message) => { |
| 218 |
const items = message[localName]; |
| 219 |
if (items.length == 0) { |
| 220 |
return; |
| 221 |
} |
| 222 |
writer.tag(fieldNo, WireType.LengthDelimited).fork(); |
| 223 |
for (let i = 0; i < items.length; i++) { |
| 224 |
writeScalar(writer, items[i]); |
| 225 |
} |
| 226 |
writer.join(); |
| 227 |
}; |
| 228 |
} |
| 229 |
const wireType = writeTypeOfScalar(scalarType); |
| 230 |
return (writer, opts, message) => { |
| 231 |
const items = message[localName]; |
| 232 |
for (let i = 0; i < items.length; i++) { |
| 233 |
writer.tag(fieldNo, wireType); |
| 234 |
writeScalar(writer, items[i]); |
| 235 |
} |
| 236 |
}; |
| 237 |
} |
| 238 |
} |
| 239 |
} |
| 240 |
function compileMapField(field) { |
| 241 |
const localName = field.localName; |
| 242 |
const fieldNo = field.number; |
| 243 |
const writeKey = compileMapKey(field); |
| 244 |
if (field.mapKind == "message") { |
| 245 |
const { toMessage } = localMessageMapper(field); |
| 246 |
const writeMessage = compiledWriter(field.message); |
| 247 |
return (writer, opts, message) => { |
| 248 |
const record = message[localName]; |
| 249 |
const keys = Object.keys(record); |
| 250 |
for (let i = 0; i < keys.length; i++) { |
| 251 |
const key = keys[i]; |
| 252 |
writer.tag(fieldNo, WireType.LengthDelimited).fork(); |
| 253 |
writeKey(writer, key); |
| 254 |
// The value of a map entry is always field number 2. |
| 255 |
writer.tag(2, WireType.LengthDelimited).fork(); |
| 256 |
writeMessage(writer, opts, toMessage(record[key])); |
| 257 |
writer.join(); |
| 258 |
writer.join(); |
| 259 |
} |
| 260 |
}; |
| 261 |
} |
| 262 |
const scalarType = field.mapKind == "enum" ? ScalarType.INT32 : field.scalar; |
| 263 |
const valueWireType = writeTypeOfScalar(scalarType); |
| 264 |
const writeScalar = compileScalarValue(scalarType, field.parent.typeName, field.name); |
| 265 |
return (writer, opts, message) => { |
| 266 |
const record = message[localName]; |
| 267 |
const keys = Object.keys(record); |
| 268 |
for (let i = 0; i < keys.length; i++) { |
| 269 |
const key = keys[i]; |
| 270 |
writer.tag(fieldNo, WireType.LengthDelimited).fork(); |
| 271 |
writeKey(writer, key); |
| 272 |
// The value of a map entry is always field number 2. |
| 273 |
writer.tag(2, valueWireType); |
| 274 |
writeScalar(writer, record[key]); |
| 275 |
writer.join(); |
| 276 |
} |
| 277 |
}; |
| 278 |
} |
| 279 |
/** |
| 280 |
* Compile an encoder for a map key. Map keys are stored as object keys and |
| 281 |
* are always strings locally. Convert them to their scalar type before |
| 282 |
* writing, like the reflect API does when iterating map entries. |
| 283 |
*/ |
| 284 |
function compileMapKey(field) { |
| 285 |
const wireType = writeTypeOfScalar(field.mapKey); |
| 286 |
const writeScalar = compileScalarValue(field.mapKey, field.parent.typeName, field.name); |
| 287 |
const convertKey = compileMapKeyConverter(field.mapKey); |
| 288 |
return (writer, key) => { |
| 289 |
// The key of a map entry is always field number 1. |
| 290 |
writer.tag(1, wireType); |
| 291 |
writeScalar(writer, convertKey(key)); |
| 292 |
}; |
| 293 |
} |
| 294 |
/** |
| 295 |
* Returns a converter from an object key (always a string) to the closest |
| 296 |
* possible type for the map key type. Invalid keys are passed through to |
| 297 |
* the scalar writer, which raises an error for them. |
| 298 |
*/ |
| 299 |
function compileMapKeyConverter(type) { |
| 300 |
switch (type) { |
| 301 |
case ScalarType.STRING: |
| 302 |
return (key) => key; |
| 303 |
case ScalarType.BOOL: |
| 304 |
return (key) => (key === "true" ? true : key === "false" ? false : key); |
| 305 |
case ScalarType.UINT64: |
| 306 |
case ScalarType.FIXED64: |
| 307 |
return (key) => { |
| 308 |
try { |
| 309 |
return protoInt64.uParse(key); |
| 310 |
} |
| 311 |
catch (_a) { |
| 312 |
return key; |
| 313 |
} |
| 314 |
}; |
| 315 |
case ScalarType.INT64: |
| 316 |
case ScalarType.SFIXED64: |
| 317 |
case ScalarType.SINT64: |
| 318 |
return (key) => { |
| 319 |
try { |
| 320 |
return protoInt64.parse(key); |
| 321 |
} |
| 322 |
catch (_a) { |
| 323 |
return key; |
| 324 |
} |
| 325 |
}; |
| 326 |
default: |
| 327 |
// Handles INT32, UINT32, SINT32, FIXED32, SFIXED32. |
| 328 |
// We do not use individual cases to save a few bytes code size. |
| 329 |
return (key) => { |
| 330 |
const n = Number.parseInt(key); |
| 331 |
return Number.isFinite(n) ? n : key; |
| 332 |
}; |
| 333 |
} |
| 334 |
} |
| 335 |
/** |
| 336 |
* Compile an encoder for a bare scalar value (no tag), wrapping errors from |
| 337 |
* the writer with the message and field name. |
| 338 |
*/ |
| 339 |
function compileScalarValue(type, messageName, fieldName) { |
| 340 |
const writeScalar = compileScalarWrite(type); |
| 341 |
return (writer, value) => { |
| 342 |
try { |
| 343 |
writeScalar(writer, value); |
| 344 |
} |
| 345 |
catch (e) { |
| 346 |
if (e instanceof Error) { |
| 347 |
throw new Error(`cannot encode field ${messageName}.${fieldName} to binary: ${e.message}`); |
| 348 |
} |
| 349 |
throw e; |
| 350 |
} |
| 351 |
}; |
| 352 |
} |
| 353 |
function compileScalarWrite(type) { |
| 354 |
switch (type) { |
| 355 |
case ScalarType.STRING: |
| 356 |
return (writer, value) => writer.string(value); |
| 357 |
case ScalarType.BOOL: |
| 358 |
return (writer, value) => writer.bool(value); |
| 359 |
case ScalarType.DOUBLE: |
| 360 |
return (writer, value) => writer.double(value); |
| 361 |
case ScalarType.FLOAT: |
| 362 |
return (writer, value) => writer.float(value); |
| 363 |
case ScalarType.INT32: |
| 364 |
return (writer, value) => writer.int32(value); |
| 365 |
case ScalarType.INT64: |
| 366 |
return (writer, value) => writer.int64(value); |
| 367 |
case ScalarType.UINT64: |
| 368 |
return (writer, value) => writer.uint64(value); |
| 369 |
case ScalarType.FIXED64: |
| 370 |
return (writer, value) => writer.fixed64(value); |
| 371 |
case ScalarType.BYTES: |
| 372 |
return (writer, value) => writer.bytes(value); |
| 373 |
case ScalarType.FIXED32: |
| 374 |
return (writer, value) => writer.fixed32(value); |
| 375 |
case ScalarType.SFIXED32: |
| 376 |
return (writer, value) => writer.sfixed32(value); |
| 377 |
case ScalarType.SFIXED64: |
| 378 |
return (writer, value) => writer.sfixed64(value); |
| 379 |
case ScalarType.SINT64: |
| 380 |
return (writer, value) => writer.sint64(value); |
| 381 |
case ScalarType.UINT32: |
| 382 |
return (writer, value) => writer.uint32(value); |
| 383 |
case ScalarType.SINT32: |
| 384 |
return (writer, value) => writer.sint32(value); |
| 385 |
} |
| 386 |
} |
| 387 |
/** |
| 388 |
* Write a single field to binary format, if it is set. Used to serialize |
| 389 |
* extensions: extensions always have explicit presence, so an extension |
| 390 |
* value that was just set on the container is always written. |
| 391 |
* |
| 392 |
* @private |
| 393 |
*/ |
| 394 |
export function writeField(writer, opts, msg, field) { |
| 395 |
compileField(field)(writer, opts, msg[unsafeLocal]); |
| 396 |
} |
| 397 |
/** |
| 398 |
* Compile an encoder for the wire format of a message field, honoring the |
| 399 |
* delimited encoding of the field. The tag is written by the encoder. |
| 400 |
*/ |
| 401 |
function compileChildWriter(field) { |
| 402 |
const fieldNo = field.number; |
| 403 |
const writeMessage = compiledWriter(field.message); |
| 404 |
if (field.delimitedEncoding) { |
| 405 |
return (writer, opts, child) => { |
| 406 |
writer.tag(fieldNo, WireType.StartGroup); |
| 407 |
writeMessage(writer, opts, child); |
| 408 |
writer.tag(fieldNo, WireType.EndGroup); |
| 409 |
}; |
| 410 |
} |
| 411 |
return (writer, opts, child) => { |
| 412 |
writer.tag(fieldNo, WireType.LengthDelimited).fork(); |
| 413 |
writeMessage(writer, opts, child); |
| 414 |
writer.join(); |
| 415 |
}; |
| 416 |
} |
| 417 |
function writeTypeOfScalar(type) { |
| 418 |
switch (type) { |
| 419 |
case ScalarType.BYTES: |
| 420 |
case ScalarType.STRING: |
| 421 |
return WireType.LengthDelimited; |
| 422 |
case ScalarType.DOUBLE: |
| 423 |
case ScalarType.FIXED64: |
| 424 |
case ScalarType.SFIXED64: |
| 425 |
return WireType.Bit64; |
| 426 |
case ScalarType.FIXED32: |
| 427 |
case ScalarType.SFIXED32: |
| 428 |
case ScalarType.FLOAT: |
| 429 |
return WireType.Bit32; |
| 430 |
default: |
| 431 |
return WireType.Varint; |
| 432 |
} |
| 433 |
} |