Debian Codegraph @

node/@bufbuild/protobuf/dist/commonjs/from-binary.js

raw
1 "use strict";
2 // Copyright 2021-2026 Buf Technologies, Inc.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 Object.defineProperty(exports, "__esModule", { value: true });
16 exports.makeReadContext = makeReadContext;
17 exports.fromBinary = fromBinary;
18 exports.mergeFromBinary = mergeFromBinary;
19 exports.readField = readField;
20 const descriptors_js_1 = require("./descriptors.js");
21 const scalar_js_1 = require("./reflect/scalar.js");
22 const error_js_1 = require("./reflect/error.js");
23 const unsafe_js_1 = require("./reflect/unsafe.js");
24 const message_js_1 = require("./reflect/message.js");
25 const create_js_1 = require("./create.js");
26 const binary_encoding_js_1 = require("./wire/binary-encoding.js");
27 const varint_js_1 = require("./wire/varint.js");
28 /**
29 * @private Only exported for getExtension()
30 */
31 function makeReadContext(options) {
32 return Object.assign(Object.assign({ readUnknownFields: true, recursionLimit: 100 }, options), { depth: 0 });
33 }
34 /**
35 * Parse serialized binary data.
36 */
37 function fromBinary(schema, bytes, options) {
38 const message = (0, create_js_1.create)(schema);
39 compiledReader(schema).read(message, new binary_encoding_js_1.BinaryReader(bytes), makeReadContext(options), bytes.byteLength);
40 return message;
41 }
42 /**
43 * Parse from binary data, merging fields.
44 *
45 * Repeated fields are appended. Map entries are added, overwriting
46 * existing keys.
47 *
48 * If a message field is already present, it will be merged with the
49 * new data.
50 */
51 function mergeFromBinary(schema, target, bytes, options) {
52 if (target.$typeName !== schema.typeName &&
53 schema.fields.length > 0) {
54 throw new error_js_1.FieldError(schema.fields[0], `cannot use ${schema.fields[0]} with message ${target.$typeName}`, "ForeignFieldError");
55 }
56 compiledReader(schema).read(target, new binary_encoding_js_1.BinaryReader(bytes), makeReadContext(options), bytes.byteLength);
57 return target;
58 }
59 const compiledReaders = new WeakMap();
60 /**
61 * Return the compiled decoder for a message, compiling it on first use.
62 */
63 function compiledReader(desc) {
64 let compiled = compiledReaders.get(desc);
65 if (compiled === undefined) {
66 compiled = compileMessage(desc);
67 }
68 return compiled;
69 }
70 function compileMessage(desc) {
71 const descString = String(desc);
72 const fieldReaders = new Map();
73 const compiled = {
74 read: compileMessageReader(descString, fieldReaders),
75 readGroup: compileGroupReader(descString, fieldReaders),
76 };
77 // Register before compiling fields, so that recursive message types
78 // resolve to this instance instead of compiling endlessly.
79 compiledReaders.set(desc, compiled);
80 for (const field of desc.fields) {
81 fieldReaders.set(field.number, compileFieldReader(field));
82 }
83 return compiled;
84 }
85 /**
86 * Create a decoder for a length-prefixed message body, dispatching wire
87 * records to the compiled field decoders by field number.
88 */
89 function compileMessageReader(descString, fieldReaders) {
90 return (message, reader, ctx, length) => {
91 var _a;
92 if (++ctx.depth > ctx.recursionLimit) {
93 throw new Error(`cannot decode ${descString} from binary: maximum recursion depth of ${ctx.recursionLimit} reached`);
94 }
95 const end = reader.pos + length;
96 const unknownFields = (_a = message.$unknown) !== null && _a !== void 0 ? _a : [];
97 while (reader.pos < end) {
98 const [fieldNo, wireType] = reader.tag();
99 const fieldReader = fieldReaders.get(fieldNo);
100 if (fieldReader === undefined) {
101 // Use remaining recursion budget for skipping nested groups
102 const data = reader.skip(wireType, fieldNo, ctx.recursionLimit - ctx.depth);
103 if (ctx.readUnknownFields) {
104 unknownFields.push({ no: fieldNo, wireType, data });
105 }
106 continue;
107 }
108 fieldReader(message, reader, ctx, wireType);
109 }
110 if (unknownFields.length > 0) {
111 message.$unknown = unknownFields;
112 }
113 ctx.depth--;
114 };
115 }
116 /**
117 * Create a decoder for a message with the delimited encoding (group),
118 * reading until the EndGroup tag, like compileMessageReader.
119 */
120 function compileGroupReader(descString, fieldReaders) {
121 return (message, reader, ctx, fieldNo) => {
122 var _a;
123 if (++ctx.depth > ctx.recursionLimit) {
124 throw new Error(`cannot decode ${descString} from binary: maximum recursion depth of ${ctx.recursionLimit} reached`);
125 }
126 let recordFieldNo;
127 let wireType;
128 const unknownFields = (_a = message.$unknown) !== null && _a !== void 0 ? _a : [];
129 while (reader.pos < reader.len) {
130 [recordFieldNo, wireType] = reader.tag();
131 if (wireType == binary_encoding_js_1.WireType.EndGroup) {
132 break;
133 }
134 const fieldReader = fieldReaders.get(recordFieldNo);
135 if (fieldReader === undefined) {
136 // Use remaining recursion budget for skipping nested groups
137 const data = reader.skip(wireType, recordFieldNo, ctx.recursionLimit - ctx.depth);
138 if (ctx.readUnknownFields) {
139 unknownFields.push({ no: recordFieldNo, wireType, data });
140 }
141 continue;
142 }
143 fieldReader(message, reader, ctx, wireType);
144 }
145 if (wireType != binary_encoding_js_1.WireType.EndGroup || recordFieldNo !== fieldNo) {
146 throw new Error("invalid end group tag");
147 }
148 if (unknownFields.length > 0) {
149 message.$unknown = unknownFields;
150 }
151 ctx.depth--;
152 };
153 }
154 /**
155 * @private Only exported for getExtension()
156 */
157 function readField(message, reader, field, wireType, ctx) {
158 compileFieldReader(field)(message[unsafe_js_1.unsafeLocal], reader, ctx, wireType);
159 }
160 function compileFieldReader(field) {
161 switch (field.fieldKind) {
162 case "scalar":
163 return compileScalarFieldReader(field);
164 case "enum":
165 return compileEnumFieldReader(field);
166 case "message":
167 return compileMessageFieldReader(field);
168 case "list":
169 return compileListFieldReader(field);
170 case "map":
171 return compileMapFieldReader(field);
172 }
173 }
174 function compileScalarFieldReader(field) {
175 const readScalar = compileScalarReader(field.scalar, field.utf8Validation, field.longAsString);
176 const localName = field.localName;
177 if (field.oneof) {
178 const oneofLocalName = field.oneof.localName;
179 return (message, reader) => {
180 message[oneofLocalName] = {
181 case: localName,
182 value: readScalar(reader),
183 };
184 };
185 }
186 return (message, reader) => {
187 message[localName] = readScalar(reader);
188 };
189 }
190 function compileEnumFieldReader(field) {
191 var _a;
192 const localName = field.localName;
193 const oneofLocalName = (_a = field.oneof) === null || _a === void 0 ? void 0 : _a.localName;
194 if (field.enum.open) {
195 if (oneofLocalName !== undefined) {
196 return (message, reader) => {
197 message[oneofLocalName] = { case: localName, value: reader.int32() };
198 };
199 }
200 return (message, reader) => {
201 message[localName] = reader.int32();
202 };
203 }
204 // Closed enums: unknown values are stored as unknown fields.
205 const values = field.enum.values;
206 const fieldNo = field.number;
207 return (message, reader, ctx, wireType) => {
208 var _a;
209 const val = reader.int32();
210 if (values.some((v) => v.number === val)) {
211 if (oneofLocalName !== undefined) {
212 message[oneofLocalName] = { case: localName, value: val };
213 }
214 else {
215 message[localName] = val;
216 }
217 }
218 else if (ctx.readUnknownFields) {
219 const bytes = [];
220 (0, varint_js_1.varint32write)(val, bytes);
221 const unknownFields = (_a = message.$unknown) !== null && _a !== void 0 ? _a : [];
222 unknownFields.push({
223 no: fieldNo,
224 wireType,
225 data: new Uint8Array(bytes),
226 });
227 message.$unknown = unknownFields;
228 }
229 };
230 }
231 function compileMessageFieldReader(field) {
232 const localName = field.localName;
233 const { toMessage, toLocal } = (0, message_js_1.localMessageMapper)(field);
234 const readChild = compileChildReader(field);
235 if (field.oneof) {
236 const oneofLocalName = field.oneof.localName;
237 return (message, reader, ctx) => {
238 const oneof = message[oneofLocalName];
239 const child = toMessage(oneof.case === localName ? oneof.value : undefined);
240 readChild(child, reader, ctx);
241 message[oneofLocalName] = { case: localName, value: toLocal(child) };
242 };
243 }
244 return (message, reader, ctx) => {
245 const child = toMessage(message[localName]);
246 readChild(child, reader, ctx);
247 message[localName] = toLocal(child);
248 };
249 }
250 /**
251 * Compile a decoder for the wire format of a message field, honoring the
252 * delimited encoding of the field.
253 */
254 function compileChildReader(field) {
255 const compiledChild = compiledReader(field.message);
256 if (field.delimitedEncoding) {
257 const fieldNo = field.number;
258 return (child, reader, ctx) => compiledChild.readGroup(child, reader, ctx, fieldNo);
259 }
260 return (child, reader, ctx) => compiledChild.read(child, reader, ctx, reader.uint32());
261 }
262 function compileListFieldReader(field) {
263 const localName = field.localName;
264 if (field.listKind == "message") {
265 const { toMessage, toLocal } = (0, message_js_1.localMessageMapper)(field);
266 const readChild = compileChildReader(field);
267 return (message, reader, ctx) => {
268 const child = toMessage(undefined);
269 readChild(child, reader, ctx);
270 message[localName].push(toLocal(child));
271 };
272 }
273 const scalarType = field.listKind == "enum" ? descriptors_js_1.ScalarType.INT32 : field.scalar;
274 const longAsString = field.listKind == "scalar" ? field.longAsString : false;
275 const readScalar = compileScalarReader(scalarType, field.utf8Validation, longAsString);
276 const packedPossible = scalarType != descriptors_js_1.ScalarType.STRING && scalarType != descriptors_js_1.ScalarType.BYTES;
277 return (message, reader, ctx, wireType) => {
278 const items = message[localName];
279 if (wireType == binary_encoding_js_1.WireType.LengthDelimited && packedPossible) {
280 const end = reader.uint32() + reader.pos;
281 while (reader.pos < end) {
282 items.push(readScalar(reader));
283 }
284 }
285 else {
286 items.push(readScalar(reader));
287 }
288 };
289 }
290 function compileMapFieldReader(field) {
291 const localName = field.localName;
292 const readKey = compileScalarReader(field.mapKey, field.utf8Validation, false);
293 const keyZero = (0, scalar_js_1.scalarZeroValue)(field.mapKey, false);
294 let readValue;
295 let valueDefault;
296 switch (field.mapKind) {
297 case "scalar": {
298 const scalar = field.scalar;
299 const readScalar = compileScalarReader(scalar, field.utf8Validation, false);
300 readValue = (reader) => readScalar(reader);
301 // Bytes zero values are created per entry, so that entries do not share
302 // one instance.
303 if (scalar == descriptors_js_1.ScalarType.BYTES) {
304 valueDefault = () => new Uint8Array(0);
305 }
306 else {
307 const zero = (0, scalar_js_1.scalarZeroValue)(scalar, false);
308 valueDefault = () => zero;
309 }
310 break;
311 }
312 case "enum": {
313 const zero = field.enum.values[0].number;
314 readValue = (reader) => reader.int32();
315 valueDefault = () => zero;
316 break;
317 }
318 case "message": {
319 const { toMessage, toLocal } = (0, message_js_1.localMessageMapper)(field);
320 const readChild = compiledReader(field.message).read;
321 readValue = (reader, ctx) => {
322 const child = toMessage(undefined);
323 readChild(child, reader, ctx, reader.uint32());
324 return toLocal(child);
325 };
326 valueDefault = () => toLocal(toMessage(undefined));
327 break;
328 }
329 }
330 return (message, reader, ctx) => {
331 const record = message[localName];
332 let key;
333 let val;
334 // Read the length of the map entry, which is a varint.
335 const len = reader.uint32();
336 // Calculate end AFTER advancing reader.pos (above), so that reader.pos is
337 // at the start of the map entry.
338 const end = reader.pos + len;
339 while (reader.pos < end) {
340 // Map entries have the key in field 1, and the value in field 2.
341 const [fieldNo] = reader.tag();
342 switch (fieldNo) {
343 case 1:
344 key = readKey(reader);
345 break;
346 case 2:
347 val = readValue(reader, ctx);
348 break;
349 }
350 }
351 if (key === undefined) {
352 key = keyZero;
353 }
354 if (val === undefined) {
355 val = valueDefault();
356 }
357 // Object property keys are always strings or symbols. Assigning with a
358 // boolean, number, or bigint key implicitly converts it to a string.
359 record[key] = val;
360 };
361 }
362 /**
363 * Returns a reader for a scalar value. For 64-bit integers, BinaryReader
364 * already returns the local representation (bigint or string), so, unlike in
365 * the reflection layer, no validation is needed here.
366 */
367 function compileScalarReader(type, utf8Validation, longAsString) {
368 switch (type) {
369 case descriptors_js_1.ScalarType.STRING:
370 return (reader) => reader.string(utf8Validation);
371 case descriptors_js_1.ScalarType.BOOL:
372 return (reader) => reader.bool();
373 case descriptors_js_1.ScalarType.DOUBLE:
374 return (reader) => reader.double();
375 case descriptors_js_1.ScalarType.FLOAT:
376 return (reader) => reader.float();
377 case descriptors_js_1.ScalarType.INT32:
378 return (reader) => reader.int32();
379 case descriptors_js_1.ScalarType.INT64:
380 if (longAsString) {
381 return (reader) => String(reader.int64());
382 }
383 return (reader) => reader.int64();
384 case descriptors_js_1.ScalarType.UINT64:
385 if (longAsString) {
386 return (reader) => String(reader.uint64());
387 }
388 return (reader) => reader.uint64();
389 case descriptors_js_1.ScalarType.FIXED64:
390 if (longAsString) {
391 return (reader) => String(reader.fixed64());
392 }
393 return (reader) => reader.fixed64();
394 case descriptors_js_1.ScalarType.BYTES:
395 return (reader) => reader.bytes();
396 case descriptors_js_1.ScalarType.FIXED32:
397 return (reader) => reader.fixed32();
398 case descriptors_js_1.ScalarType.SFIXED32:
399 return (reader) => reader.sfixed32();
400 case descriptors_js_1.ScalarType.SFIXED64:
401 if (longAsString) {
402 return (reader) => String(reader.sfixed64());
403 }
404 return (reader) => reader.sfixed64();
405 case descriptors_js_1.ScalarType.SINT64:
406 if (longAsString) {
407 return (reader) => String(reader.sint64());
408 }
409 return (reader) => reader.sint64();
410 case descriptors_js_1.ScalarType.UINT32:
411 return (reader) => reader.uint32();
412 case descriptors_js_1.ScalarType.SINT32:
413 return (reader) => reader.sint32();
414 }
415 }