Debian Codegraph @

node/@bufbuild/protobuf/dist/esm/create.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 { isMessage } from "./is-message.js";
15 import { ScalarType, } from "./descriptors.js";
16 import { scalarZeroValue } from "./reflect/scalar.js";
17 import { isObject } from "./reflect/guard.js";
18 import { isWrapperDesc } from "./wkt/wrappers.js";
19 // bootstrap-inject google.protobuf.Edition.EDITION_PROTO3: const $name = $number;
20 const EDITION_PROTO3 = 999;
21 // bootstrap-inject google.protobuf.Edition.EDITION_PROTO2: const $name = $number;
22 const EDITION_PROTO2 = 998;
23 // bootstrap-inject google.protobuf.FeatureSet.FieldPresence.IMPLICIT: const $name = $number;
24 const IMPLICIT = 2;
25 /**
26 * Create a new message instance.
27 *
28 * The second argument is an optional initializer object, where all fields are
29 * optional.
30 */
31 export function create(schema, init) {
32 if (isMessage(init, schema)) {
33 return init;
34 }
35 return compiledCreate(schema)(init);
36 }
37 const compiledCreates = new WeakMap();
38 /**
39 * Return the compiled create function for a message, compiling it on first use. */
40 function compiledCreate(desc) {
41 let compiled = compiledCreates.get(desc);
42 if (compiled === undefined) {
43 compiled = compileCreate(desc);
44 compiledCreates.set(desc, compiled);
45 }
46 return compiled;
47 }
48 /** Singular field: scalar, enum, or message. */
49 const INIT_SINGULAR = 0;
50 /** List field: a zero message has a fresh empty array. */
51 const INIT_LIST = 1;
52 /** Map field: a zero message has a fresh empty object. */
53 const INIT_MAP = 2;
54 /** Oneof group: the ADT is always stored, cases convert by case name. */
55 const INIT_ONEOF = 3;
56 /* Compile the create function for this message type. */
57 function compileCreate(desc) {
58 const typeName = desc.typeName;
59 const { properties, prototype } = compileInitMessage(desc);
60 return (init) => {
61 let message;
62 if (prototype !== undefined) {
63 message = Object.create(prototype);
64 message.$typeName = typeName;
65 }
66 else {
67 message = { $typeName: typeName };
68 }
69 for (let i = 0; i < properties.length; i++) {
70 const property = properties[i];
71 const name = property.name;
72 const initValue = init === null || init === void 0 ? void 0 : init[name];
73 switch (property.kind) {
74 case INIT_SINGULAR:
75 if (initValue != null) {
76 message[name] =
77 property.convert !== undefined
78 ? property.convert(initValue)
79 : initValue;
80 }
81 else if (property.constant !== undefined) {
82 message[name] = property.constant;
83 }
84 break;
85 case INIT_LIST:
86 message[name] =
87 property.convert !== undefined && Array.isArray(initValue)
88 ? initValue.map(property.convert)
89 : (initValue !== null && initValue !== void 0 ? initValue : []);
90 break;
91 case INIT_MAP:
92 // Object.create(null) would be desirable for the fresh map, but is
93 // unsupported by React:
94 // https://react.dev/reference/react/use-server#serializable-parameters-and-return-values
95 if (property.convert === undefined || !isObject(initValue)) {
96 message[name] = initValue !== null && initValue !== void 0 ? initValue : {};
97 }
98 else {
99 const converted = {};
100 const keys = Object.keys(initValue);
101 for (let k = 0; k < keys.length; k++) {
102 converted[keys[k]] = property.convert(initValue[keys[k]]);
103 }
104 message[name] = converted;
105 }
106 break;
107 case INIT_ONEOF: {
108 const oneofValue = initValue;
109 if ((oneofValue === null || oneofValue === void 0 ? void 0 : oneofValue.case) != null) {
110 const convert = property.convert.get(oneofValue.case);
111 if (convert !== undefined) {
112 message[name] = {
113 case: oneofValue.case,
114 value: convert(oneofValue.value),
115 };
116 break;
117 }
118 }
119 message[name] = { case: undefined };
120 break;
121 }
122 }
123 }
124 return message;
125 };
126 }
127 /**
128 * Classify every member once, so that creating a message is a walk over a
129 * compact list instead of a walk over the descriptor.
130 */
131 function compileInitMessage(desc) {
132 var _a, _b;
133 const properties = [];
134 const prototype = {};
135 const usePrototype = needsPrototypeChain(desc);
136 for (const member of desc.members) {
137 const name = member.localName;
138 if (member.kind == "oneof") {
139 properties.push({
140 name,
141 kind: INIT_ONEOF,
142 constant: undefined,
143 convert: compileConvertOneof(member),
144 });
145 continue;
146 }
147 switch (member.fieldKind) {
148 case "message": {
149 // Singular message fields are absent from a zero message.
150 properties.push({
151 name,
152 kind: INIT_SINGULAR,
153 constant: undefined,
154 convert: compileConvertMessage(member),
155 });
156 break;
157 }
158 case "list": {
159 properties.push({
160 name,
161 kind: INIT_LIST,
162 constant: undefined,
163 convert: member.listKind == "message"
164 ? ((_a = compileConvertMessage(member)) !== null && _a !== void 0 ? _a : ((value) => value))
165 : member.scalar == ScalarType.BYTES
166 ? toU8Arr
167 : undefined,
168 });
169 break;
170 }
171 case "map": {
172 properties.push({
173 name,
174 kind: INIT_MAP,
175 constant: undefined,
176 convert: member.mapKind == "message"
177 ? ((_b = compileConvertMessage(member)) !== null && _b !== void 0 ? _b : ((value) => value))
178 : member.scalar == ScalarType.BYTES
179 ? toU8Arr
180 : undefined,
181 });
182 break;
183 }
184 default: {
185 const zeroValue = createZeroValue(member);
186 properties.push({
187 name,
188 kind: INIT_SINGULAR,
189 constant: member.presence == IMPLICIT ? zeroValue : undefined,
190 convert: member.fieldKind == "scalar" && member.scalar == ScalarType.BYTES
191 ? toU8Arr
192 : undefined,
193 });
194 if (usePrototype) {
195 prototype[name] = zeroValue;
196 }
197 break;
198 }
199 }
200 }
201 return {
202 properties,
203 prototype: usePrototype ? prototype : undefined,
204 };
205 }
206 /**
207 * Compile the conversion of each case of a oneof group, keyed by case name.
208 */
209 function compileConvertOneof(oneof) {
210 const converters = new Map();
211 for (const field of oneof.fields) {
212 let convert;
213 if (field.fieldKind == "message") {
214 convert = compileConvertMessage(field);
215 }
216 else if (field.fieldKind == "scalar" &&
217 field.scalar == ScalarType.BYTES) {
218 convert = toU8Arr;
219 }
220 converters.set(field.localName, convert !== null && convert !== void 0 ? convert : ((value) => value));
221 }
222 return converters;
223 }
224 /**
225 * Compile the conversion of an init value for a message field, a message
226 * list item, or a message map value. Returns undefined if values are used
227 * as-is.
228 */
229 function compileConvertMessage(field) {
230 if (field.fieldKind == "message" &&
231 !field.oneof &&
232 isWrapperDesc(field.message)) {
233 // Types from google/protobuf/wrappers.proto are unwrapped when used in
234 // a singular field that is not part of a oneof group.
235 return field.message.fields[0].scalar == ScalarType.BYTES
236 ? toU8Arr
237 : undefined;
238 }
239 if (field.message.typeName == "google.protobuf.Struct" &&
240 field.parent.typeName !== "google.protobuf.Value") {
241 // google.protobuf.Struct is represented with JsonObject when used in a
242 // field, except when used in google.protobuf.Value.
243 return undefined;
244 }
245 const messageDesc = field.message;
246 // Resolved on first use, not here: the message type can be this very field's
247 // parent, whose create function is still being compiled.
248 let compiled;
249 return (value) => {
250 if (!isObject(value) || isMessage(value, messageDesc)) {
251 return value;
252 }
253 compiled !== null && compiled !== void 0 ? compiled : (compiled = compiledCreate(messageDesc));
254 return compiled(value);
255 };
256 }
257 // converts any ArrayLike<number> to Uint8Array if necessary.
258 function toU8Arr(value) {
259 return Array.isArray(value) ? new Uint8Array(value) : value;
260 }
261 /**
262 * Do we need the prototype chain to track field presence?
263 */
264 function needsPrototypeChain(desc) {
265 switch (desc.file.edition) {
266 case EDITION_PROTO3:
267 // proto3 always uses implicit presence, we never need the prototype chain.
268 return false;
269 case EDITION_PROTO2:
270 // proto2 never uses implicit presence, we always need the prototype chain.
271 return true;
272 default:
273 // If a message uses scalar or enum fields with explicit presence, we need
274 // the prototype chain to track presence. This rule does not apply to fields
275 // in a oneof group - they use a different mechanism to track presence.
276 return desc.fields.some((f) => f.presence != IMPLICIT && f.fieldKind != "message" && !f.oneof);
277 }
278 }
279 /**
280 * Returns the zero value for a scalar or enum field. Scalar and enum fields
281 * can have default values.
282 */
283 function createZeroValue(field) {
284 const defaultValue = field.getDefaultValue();
285 if (defaultValue !== undefined) {
286 return field.fieldKind == "scalar" && field.longAsString
287 ? defaultValue.toString()
288 : defaultValue;
289 }
290 return field.fieldKind == "scalar"
291 ? scalarZeroValue(field.scalar, field.longAsString)
292 : field.enum.values[0].number;
293 }