Debian Codegraph @

node/@bufbuild/protobuf/dist/esm/clone.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 { reflect } from "./reflect/reflect.js";
16 import { isReflectMessage } from "./reflect/guard.js";
17 /**
18 * Create a deep copy of a message, including extensions and unknown fields.
19 */
20 export function clone(schema, message) {
21 return cloneReflect(reflect(schema, message)).message;
22 }
23 function cloneReflect(i) {
24 const o = reflect(i.desc);
25 for (const f of i.fields) {
26 if (!i.isSet(f)) {
27 continue;
28 }
29 switch (f.fieldKind) {
30 case "list":
31 const list = o.get(f);
32 for (const item of i.get(f)) {
33 list.add(cloneSingular(f, item));
34 }
35 break;
36 case "map":
37 const map = o.get(f);
38 for (const entry of i.get(f).entries()) {
39 map.set(entry[0], cloneSingular(f, entry[1]));
40 }
41 break;
42 default: {
43 o.set(f, cloneSingular(f, i.get(f)));
44 break;
45 }
46 }
47 }
48 const unknown = i.getUnknown();
49 if (unknown && unknown.length > 0) {
50 o.setUnknown([...unknown]);
51 }
52 return o;
53 }
54 function cloneSingular(field, value) {
55 if (field.message !== undefined && isReflectMessage(value)) {
56 return cloneReflect(value);
57 }
58 if (field.scalar == ScalarType.BYTES && value instanceof Uint8Array) {
59 // @ts-expect-error T cannot extend Uint8Array in practice
60 return value.slice();
61 }
62 return value;
63 }