| 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 |
/** |
| 15 |
* Hydrate an enum descriptor. |
| 16 |
* |
| 17 |
* @private |
| 18 |
*/ |
| 19 |
export function enumDesc(file, path, ...paths) { |
| 20 |
if (paths.length == 0) { |
| 21 |
return file.enums[path]; |
| 22 |
} |
| 23 |
const e = paths.pop(); // we checked length above |
| 24 |
return paths.reduce((acc, cur) => acc.nestedMessages[cur], file.messages[path]).nestedEnums[e]; |
| 25 |
} |
| 26 |
/** |
| 27 |
* Construct a TypeScript enum object at runtime from a descriptor. |
| 28 |
* |
| 29 |
* The returned object is identical to a transpiled TS enum and includes the |
| 30 |
* reverse mapping, see https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings |
| 31 |
*/ |
| 32 |
export function tsEnum(desc) { |
| 33 |
const enumObject = {}; |
| 34 |
for (const value of desc.values) { |
| 35 |
enumObject[value.localName] = value.number; |
| 36 |
enumObject[value.number] = value.localName; |
| 37 |
} |
| 38 |
return enumObject; |
| 39 |
} |
| 40 |
/** |
| 41 |
* Construct an object enum at runtime from a descriptor. |
| 42 |
* |
| 43 |
* The returned object is a record of enum value name to integer value. It's |
| 44 |
* a subset of transpiled TS enums - it does not include the reverse mapping, |
| 45 |
* and only supports lookup by value name. |
| 46 |
*/ |
| 47 |
export function objEnum(desc) { |
| 48 |
const enumObject = {}; |
| 49 |
for (const value of desc.values) { |
| 50 |
enumObject[value.localName] = value.number; |
| 51 |
} |
| 52 |
return enumObject; |
| 53 |
} |