Debian Codegraph @

node/@bufbuild/protobuf/dist/commonjs/merge.js

raw
1 "use strict";
2 // Copyright 2021-2026 Buf Technologies, Inc.
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 // http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 Object.defineProperty(exports, "__esModule", { value: true });
16 exports.merge = merge;
17 const reflect_js_1 = require("./reflect/reflect.js");
18 /**
19 * Merge message `source` into message `target`, following Protobuf semantics.
20 *
21 * This is the same as serializing the source message, then deserializing it
22 * into the target message via `mergeFromBinary()`, with one difference:
23 * While serialization will create a copy of all values, `merge()` will copy
24 * the reference for `bytes` and messages.
25 *
26 * Also see https://protobuf.com/docs/language-spec#merging-protobuf-messages
27 */
28 function merge(schema, target, source) {
29 reflectMerge((0, reflect_js_1.reflect)(schema, target), (0, reflect_js_1.reflect)(schema, source));
30 }
31 function reflectMerge(target, source) {
32 var _a;
33 var _b;
34 const sourceUnknown = source.message.$unknown;
35 if (sourceUnknown !== undefined && sourceUnknown.length > 0) {
36 (_a = (_b = target.message).$unknown) !== null && _a !== void 0 ? _a : (_b.$unknown = []);
37 target.message.$unknown.push(...sourceUnknown);
38 }
39 for (const f of target.fields) {
40 if (!source.isSet(f)) {
41 continue;
42 }
43 switch (f.fieldKind) {
44 case "scalar":
45 case "enum":
46 target.set(f, source.get(f));
47 break;
48 case "message":
49 if (target.isSet(f)) {
50 reflectMerge(target.get(f), source.get(f));
51 }
52 else {
53 target.set(f, source.get(f));
54 }
55 break;
56 case "list":
57 const list = target.get(f);
58 for (const e of source.get(f)) {
59 list.add(e);
60 }
61 break;
62 case "map":
63 const map = target.get(f);
64 for (const [k, v] of source.get(f)) {
65 map.set(k, v);
66 }
67 break;
68 }
69 }
70 }