Debian Codegraph @

node/@bufbuild/protobuf/dist/esm/to-json.js

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