Debian Codegraph @

node/@bufbuild/protobuf/dist/esm/txtpb/to-text.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 { protoInt64 } from "../proto-int64.js";
16 import { reflect } from "../reflect/reflect.js";
17 import { createExtensionContainer, getExtension } from "../extensions.js";
18 import { BinaryReader, WireType } from "../wire/index.js";
19 import { anyUnpack } from "../wkt/index.js";
20 import { isGroupLike } from "./is-group-like.js";
21 import { quoteBytes, quoteString, Writer } from "./writer.js";
22 const textWriteDefaults = {
23 printUnknownFields: false,
24 };
25 function makeWriteOptions(options) {
26 return options ? Object.assign(Object.assign({}, textWriteDefaults), options) : textWriteDefaults;
27 }
28 // A bound on nested unknown-field rendering. The known-field tree is a finite,
29 // valid in-memory message and needs no limit, but printUnknownFields re-parses
30 // bytes and recurses (the length-delimited and group heuristics), so we cap
31 // that path as defense-in-depth.
32 const unknownFieldDepthLimit = 100;
33 /**
34 * Serialize a message to the protobuf text format.
35 *
36 * The output matches the default formatting of txtpbfmt: two-space indentation,
37 * one field per line, and a trailing newline.
38 *
39 * Requires BigInt: throws immediately if the environment does not support it.
40 */
41 export function toText(schema, message, options) {
42 if (!protoInt64.supported) {
43 throw new Error("the protobuf text format requires BigInt, which is unavailable in this environment");
44 }
45 const writer = new Writer();
46 writeMessage(writer, reflect(schema, message), makeWriteOptions(options));
47 return writer.toString();
48 }
49 /**
50 * Write the body of a message: regular fields in declaration order, then
51 * resolvable extensions sorted by full name, then unknown fields by number
52 * (only when printUnknownFields is enabled). For `google.protobuf.Any`, the
53 * expanded form replaces all of this.
54 */
55 function writeMessage(writer, msg, opts) {
56 var _a;
57 if (writeAny(writer, msg, opts)) {
58 return;
59 }
60 for (const field of msg.fields) {
61 // Unset fields are omitted, including unset required fields; like
62 // protobuf-go, we do not validate required fields when serializing.
63 if (msg.isSet(field)) {
64 writeField(writer, fieldTextName(field), field, msg, opts);
65 }
66 }
67 const extensionNumbers = writeExtensions(writer, msg, opts);
68 if (opts.printUnknownFields) {
69 for (const field of (_a = msg.getUnknown()) !== null && _a !== void 0 ? _a : []) {
70 if (!extensionNumbers.has(field.no)) {
71 writeUnknownField(writer, field, 0);
72 }
73 }
74 }
75 }
76 function writeField(writer, name, field, msg, opts) {
77 // Narrowing on fieldKind lets msg.get(field) return the precise reflect type
78 // for each case — ReflectMessage, ReflectList, ReflectMap, number, or a scalar
79 // value — so none of the branches need a cast.
80 switch (field.fieldKind) {
81 case "scalar":
82 writer.scalar(name, scalarToText(field.scalar, msg.get(field)));
83 break;
84 case "enum":
85 writer.scalar(name, enumToText(field.enum, msg.get(field)));
86 break;
87 case "message":
88 writeMessageValue(writer, name, msg.get(field), opts);
89 break;
90 case "list":
91 writeList(writer, name, field, msg.get(field), opts);
92 break;
93 case "map":
94 writeMap(writer, name, field, msg.get(field), opts);
95 break;
96 }
97 }
98 /**
99 * Write a message value as `name: { ... }`, or `name: {}` when it has no body.
100 * The body is rendered speculatively and rolled back if it turns out empty.
101 */
102 function writeMessageValue(writer, name, msg, opts) {
103 const mark = writer.mark();
104 writer.openMessage(name);
105 writeMessage(writer, msg, opts);
106 if (writer.writesSince(mark) === 1) {
107 // Only the opener was written, so the message is empty.
108 writer.reset(mark);
109 writer.emptyMessage(name);
110 }
111 else {
112 writer.end();
113 }
114 }
115 function writeList(writer, name, field, list, opts) {
116 switch (field.listKind) {
117 case "scalar":
118 for (const item of list) {
119 writer.scalar(name, scalarToText(field.scalar, item));
120 }
121 break;
122 case "enum":
123 for (const item of list) {
124 writer.scalar(name, enumToText(field.enum, item));
125 }
126 break;
127 case "message":
128 for (const item of list) {
129 writeMessageValue(writer, name, item, opts);
130 }
131 break;
132 }
133 }
134 function writeMap(writer, name, field, map, opts) {
135 // Map entries are emitted in iteration (insertion) order; unlike protobuf-go,
136 // we deliberately do not sort them.
137 for (const [key, value] of map) {
138 writer.openMessage(name);
139 writer.scalar("key", scalarToText(field.mapKey, key));
140 switch (field.mapKind) {
141 case "scalar":
142 writer.scalar("value", scalarToText(field.scalar, value));
143 break;
144 case "enum":
145 writer.scalar("value", enumToText(field.enum, value));
146 break;
147 case "message":
148 writeMessageValue(writer, "value", value, opts);
149 break;
150 }
151 writer.end();
152 }
153 }
154 /**
155 * Write `google.protobuf.Any` in its expanded form `[type.url]: { ... }`.
156 * Returns false (so the generic path writes `type_url`/`value` instead) when
157 * the message is not an Any, has no type URL, or the type cannot be resolved.
158 */
159 function writeAny(writer, msg, opts) {
160 if (msg.desc.typeName !== "google.protobuf.Any" ||
161 opts.registry === undefined) {
162 return false;
163 }
164 const any = msg.message;
165 if (any.typeUrl === "") {
166 return false;
167 }
168 const unpacked = anyUnpack(any, opts.registry);
169 if (unpacked === undefined) {
170 return false;
171 }
172 const desc = opts.registry.getMessage(unpacked.$typeName);
173 if (desc === undefined) {
174 return false;
175 }
176 // The bracketed name preserves the exact type URL, including a custom domain.
177 writeMessageValue(writer, "[" + any.typeUrl + "]", reflect(desc, unpacked), opts);
178 return true;
179 }
180 /**
181 * Write resolvable extensions, sorted by full name, and return their field
182 * numbers so writeMessage does not also emit them as raw unknown fields.
183 */
184 function writeExtensions(writer, msg, opts) {
185 const numbers = new Set();
186 const unknown = msg.getUnknown();
187 if (opts.registry === undefined || unknown === undefined) {
188 return numbers;
189 }
190 const extensions = [];
191 for (const { no } of unknown) {
192 if (numbers.has(no)) {
193 continue;
194 }
195 const extension = opts.registry.getExtensionFor(msg.desc, no);
196 if (extension !== undefined) {
197 numbers.add(no);
198 extensions.push(extension);
199 }
200 }
201 extensions.sort((a, b) => a.typeName < b.typeName ? -1 : a.typeName > b.typeName ? 1 : 0);
202 for (const extension of extensions) {
203 const value = getExtension(msg.message, extension);
204 const [container, field] = createExtensionContainer(extension, value);
205 writeField(writer, "[" + extension.typeName + "]", field, container, opts);
206 }
207 return numbers;
208 }
209 /**
210 * Write an unknown field by its field number, mirroring protobuf-go: varints as
211 * decimal, fixed-width values as hexadecimal, length-delimited data as a nested
212 * message when it parses cleanly as one and a quoted byte string otherwise, and
213 * groups recursively.
214 */
215 function writeUnknownField(writer, field, depth) {
216 const name = field.no.toString();
217 const reader = new BinaryReader(field.data);
218 switch (field.wireType) {
219 case WireType.Varint:
220 writer.scalar(name, reader.uint64().toString());
221 break;
222 case WireType.Bit32:
223 writer.scalar(name, "0x" + (reader.fixed32() >>> 0).toString(16).padStart(8, "0"));
224 break;
225 case WireType.Bit64:
226 writer.scalar(name, "0x" + BigInt(reader.fixed64()).toString(16).padStart(16, "0"));
227 break;
228 case WireType.LengthDelimited: {
229 const bytes = reader.bytes();
230 const nested = depth < unknownFieldDepthLimit ? parseUnknownMessage(bytes) : undefined;
231 if (nested === undefined) {
232 writer.scalar(name, quoteBytes(bytes));
233 }
234 else {
235 writeUnknownGroup(writer, name, nested, depth);
236 }
237 break;
238 }
239 case WireType.StartGroup: {
240 const fields = [];
241 while (reader.pos < reader.len) {
242 const [no, wireType] = reader.tag();
243 if (wireType === WireType.EndGroup) {
244 break;
245 }
246 fields.push({ no, wireType, data: reader.skip(wireType, no) });
247 }
248 writeUnknownGroup(writer, name, fields, depth);
249 break;
250 }
251 }
252 }
253 function writeUnknownGroup(writer, name, fields, depth) {
254 if (fields.length === 0) {
255 writer.emptyMessage(name);
256 return;
257 }
258 writer.openMessage(name);
259 for (const field of fields) {
260 writeUnknownField(writer, field, depth + 1);
261 }
262 writer.end();
263 }
264 /**
265 * Try to interpret length-delimited bytes as a nested message. Returns its
266 * unknown fields if the bytes parse cleanly and completely, otherwise undefined
267 * (in which case the data is rendered as a quoted byte string).
268 */
269 function parseUnknownMessage(bytes) {
270 if (bytes.length === 0) {
271 return undefined;
272 }
273 const reader = new BinaryReader(bytes);
274 const fields = [];
275 try {
276 while (reader.pos < reader.len) {
277 const [no, wireType] = reader.tag();
278 if (no <= 0 || wireType === WireType.EndGroup) {
279 return undefined;
280 }
281 fields.push({ no, wireType, data: reader.skip(wireType, no) });
282 }
283 }
284 catch (_a) {
285 return undefined;
286 }
287 return reader.pos === reader.len ? fields : undefined;
288 }
289 /**
290 * The name a field is addressed by in the text format: a group-like (delimited)
291 * field uses its message type name, every other field its proto name.
292 */
293 function fieldTextName(field) {
294 return isGroupLike(field) ? field.message.name : field.name;
295 }
296 function scalarToText(type, value) {
297 switch (type) {
298 case ScalarType.STRING:
299 return quoteString(value);
300 case ScalarType.BYTES:
301 return quoteBytes(value);
302 case ScalarType.BOOL:
303 return value === true ? "true" : "false";
304 case ScalarType.FLOAT:
305 return floatToText(value, true);
306 case ScalarType.DOUBLE:
307 return floatToText(value, false);
308 default:
309 // All integer types print as decimal with no prefix. 64-bit values are
310 // bigint; String() gives the decimal form for both bigint and number.
311 return String(value);
312 }
313 }
314 function enumToText(descEnum, value) {
315 // Emit the first-declared name for a value, so allow_alias enums match
316 // protobuf-go (the by-number record can resolve to a non-first alias). An
317 // unknown value prints as a decimal.
318 for (const v of descEnum.values) {
319 if (v.number === value) {
320 return v.name;
321 }
322 }
323 return value.toString();
324 }
325 function floatToText(value, single) {
326 // Round to 32-bit precision first so an overflow becomes inf (not the JS
327 // "Infinity") and the value is the true 32-bit value before we test it.
328 const n = single ? Math.fround(value) : value;
329 if (Number.isNaN(n)) {
330 return "nan";
331 }
332 if (n === Number.POSITIVE_INFINITY) {
333 return "inf";
334 }
335 if (n === Number.NEGATIVE_INFINITY) {
336 return "-inf";
337 }
338 if (Object.is(n, -0)) {
339 return "-0";
340 }
341 if (!single) {
342 // Number.prototype.toString already yields the shortest decimal that
343 // round-trips to the same 64-bit value.
344 return n.toString();
345 }
346 // For 32-bit floats, find the shortest decimal that round-trips to the same
347 // float32, mirroring strconv.AppendFloat(n, 'g', -1, 32) in protobuf-go.
348 for (let precision = 1; precision <= 9; precision++) {
349 const candidate = Number(n.toPrecision(precision));
350 if (Math.fround(candidate) === n) {
351 return candidate.toString();
352 }
353 }
354 return n.toString();
355 }