Debian Codegraph @

node/@bufbuild/protobuf/dist/commonjs/to-json.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.toJson = toJson;
17 exports.toJsonString = toJsonString;
18 exports.enumToJson = enumToJson;
19 const descriptors_js_1 = require("./descriptors.js");
20 const names_js_1 = require("./reflect/names.js");
21 const index_js_1 = require("./wkt/index.js");
22 const wrappers_js_1 = require("./wkt/wrappers.js");
23 const json_js_1 = require("./wkt/json.js");
24 const index_js_2 = require("./wire/index.js");
25 const extensions_js_1 = require("./extensions.js");
26 const reflect_check_js_1 = require("./reflect/reflect-check.js");
27 const error_js_1 = require("./reflect/error.js");
28 const unsafe_js_1 = require("./reflect/unsafe.js");
29 const scalar_js_1 = require("./reflect/scalar.js");
30 const message_js_1 = require("./reflect/message.js");
31 // bootstrap-inject google.protobuf.FeatureSet.FieldPresence.LEGACY_REQUIRED: const $name = $number;
32 const LEGACY_REQUIRED = 3;
33 // bootstrap-inject google.protobuf.FeatureSet.FieldPresence.IMPLICIT: const $name = $number;
34 const IMPLICIT = 2;
35 // Default options for serializing to JSON.
36 const jsonWriteDefaults = {
37 alwaysEmitImplicit: false,
38 enumAsInteger: false,
39 useProtoFieldName: false,
40 };
41 function makeWriteOptions(options) {
42 return options ? Object.assign(Object.assign({}, jsonWriteDefaults), options) : jsonWriteDefaults;
43 }
44 /**
45 * Serialize the message to a JSON value, a JavaScript value that can be
46 * passed to JSON.stringify().
47 */
48 function toJson(schema, message, options) {
49 return compiledWriter(schema)(makeWriteOptions(options), message);
50 }
51 /**
52 * Serialize the message to a JSON string.
53 */
54 function toJsonString(schema, message, options) {
55 var _a;
56 const jsonValue = toJson(schema, message, options);
57 return JSON.stringify(jsonValue, null, (_a = options === null || options === void 0 ? void 0 : options.prettySpaces) !== null && _a !== void 0 ? _a : 0);
58 }
59 /**
60 * Serialize a single enum value to JSON.
61 */
62 function enumToJson(descEnum, value) {
63 var _a;
64 if (descEnum.typeName == "google.protobuf.NullValue") {
65 return null;
66 }
67 const name = (_a = descEnum.value[value]) === null || _a === void 0 ? void 0 : _a.name;
68 if (name === undefined) {
69 throw new Error(`${value} is not a value in ${descEnum}`);
70 }
71 return name;
72 }
73 const compiledWriters = new WeakMap();
74 /**
75 * Return the compiled encoder for a message, compiling it on first use.
76 */
77 function compiledWriter(desc) {
78 let compiled = compiledWriters.get(desc);
79 if (compiled === undefined) {
80 compiled = compileMessage(desc);
81 }
82 return compiled;
83 }
84 function compileMessage(desc) {
85 const typeName = desc.typeName;
86 const writeWkt = compileWkt(desc);
87 if (writeWkt !== undefined) {
88 // The field reported in ForeignFieldError. All well-known types with a
89 // custom JSON representation have at least one field.
90 const foreignField = desc.fields[0];
91 const compiledWriter = (opts, message) => {
92 if (message.$typeName !== typeName && foreignField !== undefined) {
93 throw new error_js_1.FieldError(foreignField, `cannot use ${foreignField} with message ${message.$typeName}`, "ForeignFieldError");
94 }
95 return writeWkt(opts, message);
96 };
97 compiledWriters.set(desc, compiledWriter);
98 return compiledWriter;
99 }
100 const sortedFields = desc.fields.concat().sort((a, b) => a.number - b.number);
101 // The field reported in ForeignFieldError.
102 const foreignField = sortedFields[0];
103 const fieldWriters = [];
104 const compiledWriter = (opts, message) => {
105 if (message.$typeName !== typeName && foreignField !== undefined) {
106 throw new error_js_1.FieldError(foreignField, `cannot use ${foreignField} with message ${message.$typeName}`, "ForeignFieldError");
107 }
108 const json = {};
109 for (let i = 0; i < fieldWriters.length; i++) {
110 fieldWriters[i](opts, message, json);
111 }
112 if (opts.registry) {
113 writeExtensions(json, opts, opts.registry, message, desc);
114 }
115 return json;
116 };
117 // Register before compiling fields, so that recursive message types
118 // resolve to this instance instead of compiling endlessly.
119 compiledWriters.set(desc, compiledWriter);
120 for (const field of sortedFields) {
121 fieldWriters.push(compileField(field));
122 }
123 return compiledWriter;
124 }
125 /**
126 * Compile an encoder for a well-known type with a custom JSON representation,
127 * or return undefined for other messages.
128 */
129 function compileWkt(desc) {
130 if (!desc.typeName.startsWith("google.protobuf.")) {
131 return undefined;
132 }
133 switch (desc.typeName) {
134 case "google.protobuf.Any":
135 return (opts, message) => anyToJson(message, opts);
136 case "google.protobuf.Timestamp":
137 return (opts, message) => timestampToJson(message);
138 case "google.protobuf.Duration":
139 return (opts, message) => durationToJson(message);
140 case "google.protobuf.FieldMask":
141 return (opts, message) => fieldMaskToJson(message);
142 case "google.protobuf.Struct":
143 return (opts, message) => structToJson(message);
144 case "google.protobuf.Value":
145 return (opts, message) => valueToJson(message);
146 case "google.protobuf.ListValue":
147 return (opts, message) => listValueToJson(message);
148 default:
149 if ((0, wrappers_js_1.isWrapperDesc)(desc)) {
150 const valueField = desc.fields[0];
151 const localName = valueField.localName;
152 const zero = (0, scalar_js_1.scalarZeroValue)(valueField.scalar, false);
153 const writeScalar = compileScalarValue(valueField);
154 return (opts, message) => {
155 const value = message[localName];
156 return writeScalar(opts, value === undefined ? zero : value);
157 };
158 }
159 return undefined;
160 }
161 }
162 function compileField(field) {
163 switch (field.fieldKind) {
164 case "scalar":
165 case "enum":
166 case "message":
167 return compileSingularField(field);
168 case "list":
169 case "map": {
170 const writeValue = field.fieldKind == "list"
171 ? compileListValue(field)
172 : compileMapValue(field);
173 const protoName = field.name;
174 const jsonKey = field.jsonName;
175 const localName = field.localName;
176 return (opts, message, json) => {
177 const value = writeValue(opts, message[localName]);
178 if (value !== undefined) {
179 json[opts.useProtoFieldName ? protoName : jsonKey] = value;
180 }
181 };
182 }
183 }
184 }
185 /**
186 * Compile an encoder for a singular field: the presence check, and the
187 * value encoder.
188 */
189 function compileSingularField(field) {
190 const writeValue = compileSingularValue(field);
191 const protoName = field.name;
192 const jsonKey = field.jsonName;
193 const localName = field.localName;
194 if (field.oneof) {
195 const oneofLocalName = field.oneof.localName;
196 return (opts, message, json) => {
197 const oneof = message[oneofLocalName];
198 if (oneof.case === localName) {
199 json[opts.useProtoFieldName ? protoName : jsonKey] = writeValue(opts, oneof.value);
200 }
201 };
202 }
203 if (field.presence != IMPLICIT) {
204 const requiredError = field.presence == LEGACY_REQUIRED
205 ? `cannot encode ${field} to JSON: required field not set`
206 : undefined;
207 return (opts, message, json) => {
208 const value = message[localName];
209 // Fields with explicit presence have properties on the prototype
210 // chain for default / zero values (except for proto3).
211 if (value !== undefined &&
212 Object.prototype.hasOwnProperty.call(message, localName)) {
213 json[opts.useProtoFieldName ? protoName : jsonKey] = writeValue(opts, value);
214 }
215 else if (requiredError !== undefined) {
216 throw new Error(requiredError);
217 }
218 };
219 }
220 // Implicit presence: the field is emitted when the value is not the zero
221 // value, or when alwaysEmitImplicit is enabled. The zero check is inlined
222 // per type, see isScalarZeroValue.
223 if (field.fieldKind == "enum") {
224 const zero = field.enum.values[0].number;
225 return (opts, message, json) => {
226 const value = message[localName];
227 if (value !== zero || opts.alwaysEmitImplicit) {
228 json[opts.useProtoFieldName ? protoName : jsonKey] = writeValue(opts, value);
229 }
230 };
231 }
232 switch (field.scalar) {
233 case descriptors_js_1.ScalarType.BOOL:
234 return (opts, message, json) => {
235 const value = message[localName];
236 if (value !== false || opts.alwaysEmitImplicit) {
237 json[opts.useProtoFieldName ? protoName : jsonKey] = writeValue(opts, value);
238 }
239 };
240 case descriptors_js_1.ScalarType.STRING:
241 return (opts, message, json) => {
242 const value = message[localName];
243 if (value !== "" || opts.alwaysEmitImplicit) {
244 json[opts.useProtoFieldName ? protoName : jsonKey] = writeValue(opts, value);
245 }
246 };
247 case descriptors_js_1.ScalarType.BYTES:
248 return (opts, message, json) => {
249 const value = message[localName];
250 if (!(value instanceof Uint8Array) ||
251 value.byteLength > 0 ||
252 opts.alwaysEmitImplicit) {
253 json[opts.useProtoFieldName ? protoName : jsonKey] = writeValue(opts, value);
254 }
255 };
256 case descriptors_js_1.ScalarType.DOUBLE:
257 case descriptors_js_1.ScalarType.FLOAT:
258 return (opts, message, json) => {
259 const value = message[localName];
260 // Object.is distinguishes -0 from 0.
261 if (!Object.is(value, 0) || opts.alwaysEmitImplicit) {
262 json[opts.useProtoFieldName ? protoName : jsonKey] = writeValue(opts, value);
263 }
264 };
265 default:
266 return (opts, message, json) => {
267 const value = message[localName];
268 // Loose comparison matches 0n, 0 and "0".
269 if (value != 0 || opts.alwaysEmitImplicit) {
270 json[opts.useProtoFieldName ? protoName : jsonKey] = writeValue(opts, value);
271 }
272 };
273 }
274 }
275 /**
276 * Compile an encoder for the value of a field of any kind. Used for
277 * extension values.
278 */
279 function compileFieldValue(field) {
280 switch (field.fieldKind) {
281 case "scalar":
282 case "enum":
283 case "message":
284 return compileSingularValue(field);
285 case "list":
286 return compileListValue(field);
287 case "map":
288 return compileMapValue(field);
289 }
290 }
291 /**
292 * Compile an encoder for the value of a singular field.
293 */
294 function compileSingularValue(field) {
295 switch (field.fieldKind) {
296 case "scalar":
297 return compileScalarValue(field);
298 case "enum":
299 return compileEnumValue(field);
300 case "message":
301 return compileMessageValue(field);
302 }
303 }
304 /**
305 * Compile an encoder for the value of a message field.
306 */
307 function compileMessageValue(field) {
308 const { toMessage } = (0, message_js_1.localMessageMapper)(field);
309 const writeMessage = compiledWriter(field.message);
310 return (opts, value) => writeMessage(opts, toMessage(value));
311 }
312 /**
313 * Compile an encoder for a list field value. Returns undefined for an empty
314 * list, unless alwaysEmitImplicit is enabled.
315 */
316 function compileListValue(field) {
317 const writeItem = compileListItemValue(field);
318 return (opts, value) => {
319 const items = value;
320 if (items.length == 0 && !opts.alwaysEmitImplicit) {
321 return undefined;
322 }
323 const jsonArray = [];
324 for (let i = 0; i < items.length; i++) {
325 jsonArray.push(writeItem(opts, items[i]));
326 }
327 return jsonArray;
328 };
329 }
330 function compileListItemValue(field) {
331 switch (field.listKind) {
332 case "scalar":
333 return compileScalarValue(field);
334 case "enum":
335 return compileEnumValue(field);
336 case "message":
337 return compileMessageValue(field);
338 }
339 }
340 /**
341 * Compile an encoder for a map field value. Returns undefined for an empty
342 * map, unless alwaysEmitImplicit is enabled. Map keys are stored as object
343 * keys and are used as JSON keys as-is.
344 */
345 function compileMapValue(field) {
346 const writeMapValue = compileMapEntryValue(field);
347 return (opts, value) => {
348 const record = value;
349 const keys = Object.keys(record);
350 if (keys.length == 0 && !opts.alwaysEmitImplicit) {
351 return undefined;
352 }
353 const jsonObject = {};
354 for (let i = 0; i < keys.length; i++) {
355 const key = keys[i];
356 jsonObject[key] = writeMapValue(opts, record[key]);
357 }
358 return jsonObject;
359 };
360 }
361 function compileMapEntryValue(field) {
362 switch (field.mapKind) {
363 case "scalar":
364 return compileScalarValue(field);
365 case "enum":
366 return compileEnumValue(field);
367 case "message":
368 return compileMessageValue(field);
369 }
370 }
371 /**
372 * Compile an encoder for an enum value.
373 */
374 function compileEnumValue(field) {
375 const desc = field.enum;
376 if (desc.typeName == "google.protobuf.NullValue") {
377 return (opts, value) => {
378 if (typeof value != "number") {
379 throw errorEnumValue(desc, value);
380 }
381 return null;
382 };
383 }
384 return (opts, value) => {
385 var _a, _b;
386 if (typeof value != "number") {
387 throw errorEnumValue(desc, value);
388 }
389 if (opts.enumAsInteger) {
390 return value;
391 }
392 // If we don't know the enum value, just return the number.
393 return (_b = (_a = desc.value[value]) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : value;
394 };
395 }
396 function errorEnumValue(desc, value) {
397 return new Error(`cannot encode ${desc} to JSON: expected number, got ${(0, reflect_check_js_1.formatVal)(value)}`);
398 }
399 /**
400 * Compile an encoder for a scalar value. Errors report the original field
401 * descriptor, which may be a list or map field for items of those fields.
402 */
403 function compileScalarValue(field) {
404 switch (field.scalar) {
405 // int32, fixed32, uint32: JSON value will be a decimal number. Either numbers or strings are accepted.
406 case descriptors_js_1.ScalarType.INT32:
407 case descriptors_js_1.ScalarType.SFIXED32:
408 case descriptors_js_1.ScalarType.SINT32:
409 case descriptors_js_1.ScalarType.FIXED32:
410 case descriptors_js_1.ScalarType.UINT32:
411 return (opts, value) => {
412 if (typeof value != "number") {
413 throw errorScalarValue(field, value);
414 }
415 return value;
416 };
417 // float, double: JSON value will be a number or one of the special string values "NaN", "Infinity", and "-Infinity".
418 // Either numbers or strings are accepted. Exponent notation is also accepted.
419 case descriptors_js_1.ScalarType.FLOAT:
420 case descriptors_js_1.ScalarType.DOUBLE:
421 return (opts, value) => {
422 if (typeof value != "number") {
423 throw errorScalarValue(field, value);
424 }
425 if (Number.isNaN(value))
426 return "NaN";
427 if (value === Number.POSITIVE_INFINITY)
428 return "Infinity";
429 if (value === Number.NEGATIVE_INFINITY)
430 return "-Infinity";
431 return value;
432 };
433 // string:
434 case descriptors_js_1.ScalarType.STRING:
435 return (opts, value) => {
436 if (typeof value != "string") {
437 throw errorScalarValue(field, value);
438 }
439 return value;
440 };
441 // bool:
442 case descriptors_js_1.ScalarType.BOOL:
443 return (opts, value) => {
444 if (typeof value != "boolean") {
445 throw errorScalarValue(field, value);
446 }
447 return value;
448 };
449 // JSON value will be a decimal string. Either numbers or strings are accepted.
450 case descriptors_js_1.ScalarType.UINT64:
451 case descriptors_js_1.ScalarType.FIXED64:
452 case descriptors_js_1.ScalarType.INT64:
453 case descriptors_js_1.ScalarType.SFIXED64:
454 case descriptors_js_1.ScalarType.SINT64:
455 return (opts, value) => {
456 if (typeof value == "bigint" ||
457 typeof value == "string" ||
458 (typeof value == "number" && Number.isInteger(value))) {
459 return value.toString();
460 }
461 throw errorScalarValue(field, value);
462 };
463 // bytes: JSON value will be the data encoded as a string using standard base64 encoding with paddings.
464 // Either standard or URL-safe base64 encoding with/without paddings are accepted.
465 case descriptors_js_1.ScalarType.BYTES:
466 return (opts, value) => {
467 if (value instanceof Uint8Array) {
468 return (0, index_js_2.base64Encode)(value);
469 }
470 throw errorScalarValue(field, value);
471 };
472 }
473 }
474 function errorScalarValue(field, value) {
475 var _a;
476 return new Error(`cannot encode ${field} to JSON: ${(_a = (0, reflect_check_js_1.checkField)(field, value)) === null || _a === void 0 ? void 0 : _a.message}`);
477 }
478 /**
479 * Write extensions for unknown fields that are found in the registry.
480 */
481 function writeExtensions(json, opts, registry, message, desc) {
482 const unknown = message.$unknown;
483 if (unknown === undefined) {
484 return;
485 }
486 const tagSeen = new Set();
487 for (let i = 0; i < unknown.length; i++) {
488 const { no } = unknown[i];
489 // Same tag can appear multiple times, so we
490 // keep track and skip identical ones.
491 if (!tagSeen.has(no)) {
492 tagSeen.add(no);
493 const extension = registry.getExtensionFor(desc, no);
494 if (!extension) {
495 continue;
496 }
497 const value = (0, extensions_js_1.getExtension)(message, extension);
498 const [container, field] = (0, extensions_js_1.createExtensionContainer)(extension, value);
499 const local = container[unsafe_js_1.unsafeLocal];
500 const jsonValue = compileFieldValue(field)(opts, local[field.localName]);
501 if (jsonValue !== undefined) {
502 json[extension.jsonName] = jsonValue;
503 }
504 }
505 }
506 }
507 function anyToJson(val, opts) {
508 if (val.typeUrl === "") {
509 return {};
510 }
511 const { registry } = opts;
512 let message;
513 let desc;
514 if (registry) {
515 message = (0, index_js_1.anyUnpack)(val, registry);
516 if (message) {
517 desc = registry.getMessage(message.$typeName);
518 }
519 }
520 if (!desc || !message) {
521 throw new Error(`cannot encode message ${val.$typeName} to JSON: "${val.typeUrl}" is not in the type registry`);
522 }
523 const json = (0, wrappers_js_1.hasCustomJsonRepresentation)(desc)
524 ? {
525 value: compiledWriter(desc)(opts, message),
526 }
527 : compiledWriter(desc)(opts, message);
528 json["@type"] = val.typeUrl;
529 return json;
530 }
531 function durationToJson(val) {
532 const seconds = Number(val.seconds);
533 const nanos = val.nanos;
534 if (seconds > json_js_1.durationSecondsMax || seconds < json_js_1.durationSecondsMin) {
535 throw new Error(`cannot encode message ${val.$typeName} to JSON: value out of range`);
536 }
537 if ((seconds > 0 && nanos < 0) || (seconds < 0 && nanos > 0)) {
538 throw new Error(`cannot encode message ${val.$typeName} to JSON: nanos sign must match seconds sign`);
539 }
540 let text = val.seconds.toString();
541 if (nanos !== 0) {
542 let nanosStr = Math.abs(nanos).toString();
543 nanosStr = "0".repeat(9 - nanosStr.length) + nanosStr;
544 if (nanosStr.substring(3) === "000000") {
545 nanosStr = nanosStr.substring(0, 3);
546 }
547 else if (nanosStr.substring(6) === "000") {
548 nanosStr = nanosStr.substring(0, 6);
549 }
550 text += "." + nanosStr;
551 if (nanos < 0 && seconds == 0) {
552 text = "-" + text;
553 }
554 }
555 return text + "s";
556 }
557 function fieldMaskToJson(val) {
558 return val.paths
559 .map((p) => {
560 if ((0, names_js_1.protoSnakeCase)((0, names_js_1.protoCamelCase)(p)) !== p) {
561 throw new Error(`cannot encode message ${val.$typeName} to JSON: lowerCamelCase of path name "${p}" is irreversible`);
562 }
563 return (0, names_js_1.protoCamelCase)(p);
564 })
565 .join(",");
566 }
567 function structToJson(val) {
568 const json = {};
569 const keys = Object.keys(val.fields);
570 for (let i = 0; i < keys.length; i++) {
571 const key = keys[i];
572 json[key] = valueToJson(val.fields[key]);
573 }
574 return json;
575 }
576 function valueToJson(val) {
577 switch (val.kind.case) {
578 case "nullValue":
579 return null;
580 case "numberValue":
581 if (!Number.isFinite(val.kind.value)) {
582 throw new Error(`${val.$typeName} cannot be NaN or Infinity`);
583 }
584 return val.kind.value;
585 case "boolValue":
586 return val.kind.value;
587 case "stringValue":
588 return val.kind.value;
589 case "structValue":
590 return structToJson(val.kind.value);
591 case "listValue":
592 return listValueToJson(val.kind.value);
593 default:
594 throw new Error(`${val.$typeName} must have a value`);
595 }
596 }
597 function listValueToJson(val) {
598 return val.values.map(valueToJson);
599 }
600 function timestampToJson(val) {
601 const ms = Number(val.seconds) * 1000;
602 if (ms < json_js_1.timestampMsMin || ms > json_js_1.timestampMsMax) {
603 throw new Error(`cannot encode message ${val.$typeName} to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);
604 }
605 if (val.nanos < 0) {
606 throw new Error(`cannot encode message ${val.$typeName} to JSON: nanos must not be negative`);
607 }
608 if (val.nanos > 999999999) {
609 throw new Error(`cannot encode message ${val.$typeName} to JSON: nanos must not be greater than 99999999`);
610 }
611 let z = "Z";
612 if (val.nanos > 0) {
613 const nanosStr = (val.nanos + 1000000000).toString().substring(1);
614 if (nanosStr.substring(3) === "000000") {
615 z = "." + nanosStr.substring(0, 3) + "Z";
616 }
617 else if (nanosStr.substring(6) === "000") {
618 z = "." + nanosStr.substring(0, 6) + "Z";
619 }
620 else {
621 z = "." + nanosStr + "Z";
622 }
623 }
624 return new Date(ms).toISOString().replace(".000Z", z);
625 }