Debian Codegraph @

node/@bufbuild/protobuf/dist/esm/txtpb/writer.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 const indentUnit = " ";
15 /**
16 * A writer for the protobuf text format.
17 *
18 * The Writer owns layout: indentation, line breaks, and braces. Its output
19 * matches the default formatting of txtpbfmt and the multi-line output of
20 * protobuf-go: two-space indentation, `name: value` with a single space after
21 * the colon, submessages as `name: {` with the body indented and `}` aligned
22 * under the field name, and a trailing newline. It never inserts the randomized
23 * extra spaces that protobuf-go adds to discourage parsing its output as
24 * canonical.
25 *
26 * Output accumulates into a single buffer of lines, so a deep tree costs no
27 * more than the bytes it prints. To decide between `name: {}` and an indented
28 * block, the caller renders the body, then rolls back with mark()/reset() if it
29 * turned out empty — an O(1) decision that needs no separate child buffer.
30 */
31 export class Writer {
32 constructor() {
33 this.chunks = [];
34 this.depth = 0;
35 }
36 /**
37 * Write a scalar field: `<indent>name: value` followed by a newline.
38 */
39 scalar(name, value) {
40 this.chunks.push(this.indent() + name + ": " + value + "\n");
41 }
42 /**
43 * Write an empty message field: `<indent>name: {}` followed by a newline.
44 */
45 emptyMessage(name) {
46 this.chunks.push(this.indent() + name + ": {}\n");
47 }
48 /**
49 * Open a message field: `<indent>name: {` followed by a newline, then indent
50 * the body. Close it with end().
51 */
52 openMessage(name) {
53 this.chunks.push(this.indent() + name + ": {\n");
54 this.depth++;
55 }
56 /**
57 * Close a message opened with openMessage(): outdent and write `<indent>}`
58 * followed by a newline.
59 */
60 end() {
61 this.depth--;
62 this.chunks.push(this.indent() + "}\n");
63 }
64 /**
65 * Capture the current output position so it can be rolled back with reset().
66 */
67 mark() {
68 return { size: this.chunks.length, depth: this.depth };
69 }
70 /**
71 * Roll back to a position captured with mark().
72 */
73 reset(mark) {
74 this.chunks.length = mark.size;
75 this.depth = mark.depth;
76 }
77 /**
78 * The number of lines written since the given mark.
79 */
80 writesSince(mark) {
81 return this.chunks.length - mark.size;
82 }
83 toString() {
84 return this.chunks.join("");
85 }
86 indent() {
87 return indentUnit.repeat(this.depth);
88 }
89 }
90 /**
91 * Quote and escape a string field value as a double-quoted text format literal.
92 *
93 * Uses the single escaping decision in escapeCodePoint, so string fields, bytes
94 * fields, and unknown length-delimited rendering can never drift apart. Valid
95 * non-ASCII passes through as raw UTF-8; surrogates are never escaped.
96 */
97 export function quoteString(value) {
98 var _a;
99 let out = '"';
100 for (const ch of value) {
101 out += (_a = escapeCodePoint(ch.codePointAt(0))) !== null && _a !== void 0 ? _a : ch;
102 }
103 return out + '"';
104 }
105 /**
106 * Quote and escape a bytes field value as a double-quoted text format literal.
107 *
108 * Valid UTF-8 runs are emitted with escapeCodePoint (so they read identically
109 * to a string field); any byte that is not part of a valid UTF-8 sequence is
110 * emitted as `\xHH`, keeping the output plain ASCII that round-trips exactly.
111 */
112 export function quoteBytes(value) {
113 var _a;
114 let out = '"';
115 for (let i = 0; i < value.length;) {
116 const rune = decodeUtf8(value, i);
117 if (rune === undefined) {
118 out += "\\x" + hex2(value[i]);
119 i++;
120 continue;
121 }
122 out += (_a = escapeCodePoint(rune.code)) !== null && _a !== void 0 ? _a : String.fromCodePoint(rune.code);
123 i += rune.size;
124 }
125 return out + '"';
126 }
127 /**
128 * The single source of truth for escaping a code point in a text format string
129 * literal. Returns the escape sequence, or undefined when the code point may be
130 * emitted raw.
131 *
132 * Escapes the conventional sequences, all C0 controls and DEL as `\xHH`, and
133 * the C1 controls (U+0080–U+009F) as `\u00HH`. Surrogates and everything else
134 * pass through raw.
135 */
136 function escapeCodePoint(code) {
137 switch (code) {
138 case 0x5c:
139 return "\\\\";
140 case 0x22:
141 return '\\"';
142 case 0x0a:
143 return "\\n";
144 case 0x0d:
145 return "\\r";
146 case 0x09:
147 return "\\t";
148 }
149 if (code < 0x20 || code === 0x7f) {
150 return "\\x" + hex2(code);
151 }
152 if (code >= 0x80 && code <= 0x9f) {
153 return "\\u" + code.toString(16).padStart(4, "0");
154 }
155 return undefined;
156 }
157 /**
158 * Decode the UTF-8 sequence starting at `offset`, returning the code point and
159 * its byte length, or undefined if the bytes there are not valid UTF-8. We
160 * decode manually (rather than via TextDecoder) so an invalid byte can be
161 * pinpointed and escaped individually.
162 */
163 function decodeUtf8(bytes, offset) {
164 const b0 = bytes[offset];
165 if (b0 < 0x80) {
166 return { code: b0, size: 1 };
167 }
168 if (b0 < 0xc0) {
169 return undefined;
170 }
171 if (b0 < 0xe0) {
172 const b1 = bytes[offset + 1];
173 if (!isContinuation(b1)) {
174 return undefined;
175 }
176 const code = ((b0 & 0x1f) << 6) | (b1 & 0x3f);
177 return code < 0x80 ? undefined : { code, size: 2 };
178 }
179 if (b0 < 0xf0) {
180 const b1 = bytes[offset + 1];
181 const b2 = bytes[offset + 2];
182 if (!isContinuation(b1) || !isContinuation(b2)) {
183 return undefined;
184 }
185 const code = ((b0 & 0x0f) << 12) | ((b1 & 0x3f) << 6) | (b2 & 0x3f);
186 if (code < 0x800 || (code >= 0xd800 && code <= 0xdfff)) {
187 return undefined;
188 }
189 return { code, size: 3 };
190 }
191 if (b0 < 0xf8) {
192 const b1 = bytes[offset + 1];
193 const b2 = bytes[offset + 2];
194 const b3 = bytes[offset + 3];
195 if (!isContinuation(b1) || !isContinuation(b2) || !isContinuation(b3)) {
196 return undefined;
197 }
198 const code = ((b0 & 0x07) << 18) |
199 ((b1 & 0x3f) << 12) |
200 ((b2 & 0x3f) << 6) |
201 (b3 & 0x3f);
202 if (code < 0x10000 || code > 0x10ffff) {
203 return undefined;
204 }
205 return { code, size: 4 };
206 }
207 return undefined;
208 }
209 function isContinuation(byte) {
210 return byte !== undefined && (byte & 0xc0) === 0x80;
211 }
212 function hex2(value) {
213 return value.toString(16).padStart(2, "0");
214 }